Error in seq.int(0, to0 - from, by) : wrong sign in 'by' argument

本文探讨了在R语言中构建时间序列时遇到的常见错误,特别是使用seq函数时因时间格式不匹配或序列方向错误导致的问题,并提供了解决方案。
部署运行你感兴趣的模型镜像
seq(first(as.Date(dat$updateTime)), last(as.Date(dat$updateTime)), by = "day")

代码解读:
dat是一个数据框,其中存在一列是updateTime,找到updateTime中的最大值和最小值,从而用seq(dateTime_1, dateTime_2, by= ‘’)的方式,构建一个连续的时间列(注意:不是ts类型的那种时间序列)。
seq用法详参:seq函数的时间用法 R document
出现报错如题:

Error in seq.int(0, to0 - from, by) : wrong sign in 'by' argument

经过查找,报错可能性有:

  1. 时间格式不对
    R中默认的时间格式是:yyyy-mm-dd(“2012-02-06”),若使用了格式为其他格式的时间,例如:dd-mm-yyyy(“01-11-1979”),则会报错。
    修正方法详参:Stackoverflow 中的同名问题
  2. 另外一种报错原因就很蛋疼了…(我遇到的情况)
    在代码中,我使用了first, last函数,而由于我的date是倒序排列的,所以出现了一种情况是,我取出来的第一个数字是比最后一个数字要大的。这种报错原因约等于:
seq(as.Date('2020-04-21'),as.Date('2020-1-23'),by="day")

的报错原因。
将代码更改为:

seq(as.Date('2020-04-21'),as.Date('2020-1-23'),by="-1 day")

更改序列为递减序列,最后正常运行。

P.S: 写代码的时候脑子还是不能不清醒…祝大家debug顺利

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':multiple-dex-core:buildCMakeDebug[armeabi-v7a]'. > com.android.ide.common.process.ProcessException: ninja: Entering directory `D:\project\AndroidProjects\2025\release\code\Demo\multiple-dex-core\.cxx\Debug\f664384u\armeabi-v7a' [1/2] Building C object CMakeFiles/openssl.dir/native-lib.c.o D:/project/AndroidProjects/2025/release/code/Demo/multiple-dex-core/src/main/cpp/native-lib.c:37:54: warning: passing 'char[17]' to parameter of type 'const unsigned char *' converts between pointers to integer types where one is of the unique plain 'char' type and the other is not [-Wpointer-sign] 37 | EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, "kimhslmultiplede", NULL); | ^~~~~~~~~~~~~~~~~~ D:/project/AndroidProjects/2025/release/code/Demo/multiple-dex-core/src/main/cpp/include/openssl/evp.h:556:56: note: passing argument to parameter 'key' here 556 | const unsigned char *key, | ^ D:/project/AndroidProjects/2025/release/code/Demo/multiple-dex-core/src/main/cpp/native-lib.c:57:42: warning: passing 'jbyte *' (aka 'signed char *') to parameter of type 'const unsigned char *' converts between pointers to integer types with different sign [-Wpointer-sign] 57 | EVP_DecryptUpdate(ctx, out, &outlen, src, srcLen); | ^~~ D:/project/AndroidProjects/2025/release/code/Demo/multiple-dex-core/src/main/cpp/include/openssl/evp.h:559:66: note: passing argument to parameter 'in' here 559 | int *outl, const unsigned char *in, int inl); | ^ 2 warnings generated. [2/2] Linking C shared library D:\project\AndroidProjects\2025\release\code\Demo\multiple-dex-core\build\intermediates\cxx\Debug\f664384u\obj\armeabi-v7a\libopenssl.so FAILED: D:/project/AndroidProjects/2025/release/code/Demo/multiple-dex-core/build/intermediates/cxx/Debug/f664384u/obj/armeabi-v7a/libopenssl.so cmd.exe /C "cd . && D:\tools\Android\Sdk\ndk\27.0.12077973\toolchains\llvm\prebuilt\windows-x86_64\bin\clang.exe --target=armv7-none-linux-androideabi29 --sysroot=D:/tools/Android/Sdk/ndk/27.0.12077973/toolchains/llvm/prebuilt /windows-x86_64/sysroot -fPIC -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -march=armv7-a -mthumb -Wformat -Werror=format-security -fno-lim it-debug-info -static-libstdc++ -Wl,--build-id=sha1 -Wl,--no-rosegment -Wl,--no-undefined-version -Wl,--fatal-warnings -Wl,--no-undefined -Qunused-arguments -shared -Wl,-soname,libopenssl.so -o D:\project\AndroidProjects\2025\r elease\code\Demo\multiple-dex-core\build\intermediates\cxx\Debug\f664384u\obj\armeabi-v7a\libopenssl.so CMakeFiles/openssl.dir/native-lib.c.o D:/project/AndroidProjects/2025/release/code/Demo/multiple-dex-core/src/main/cpp/lib/armeabi-v7a/libcrypto.a -landroid D:/tools/Android/Sdk/ndk/27.0.12077973/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/lib/arm-linux-androideabi/29/liblog.so -latomic -lm && cd ." ld.lld: error: undefined symbol: __sync_add_and_fetch_4 >>> referenced by threads_pthread.c >>> threads_pthread.o:(CRYPTO_atomic_add) in archive D:/project/AndroidProjects/2025/release/code/Demo/multiple-dex-core/src/main/cpp/lib/armeabi-v7a/libcrypto.a clang: error: linker command failed with exit code 1 (use -v to see invocation) ninja: build stopped: subcommand failed. C++ build system [build] failed while executing: @echo off "D:\\tools\\Android\\Sdk\\cmake\\3.22.1\\bin\\ninja.exe" ^ -C ^ "D:\\project\\AndroidProjects\\2025\\release\\code\\Demo\\multiple-dex-core\\.cxx\\Debug\\f664384u\\armeabi-v7a" ^ openssl from D:\project\AndroidProjects\2025\release\code\Demo\multiple-dex-core * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. > Get more help at https://help.gradle.org. Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0. You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins. For more on this, please refer to https://docs.gradle.org/8.11.1/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation. BUILD FAILED in 11s 43 actionable tasks: 2 executed, 41 up-to-date
08-26
当前python版本2.6.5,运行以上代码总是报错,我现在不能升级python,帮我修改这段,在保持原来意义的情况下,修改语言模式适配版本import requests import re import typing import hashlib import base64 import argparse import sys import tp_link_crypto DEBUG = False USERNAME = "admin" # Hardcoded in the router USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0" AES_KEY = "A" * 16 AES_IV = "B" * 16 def print_d(msg: str) -> None: if DEBUG: print(msg) def is_supported_model(ip_addr: str) -> bool: """ Determines if a router is supported. :param ip_addr: IP address of the router :return: True if supported, otherwise False """ # Tuples of model name and model description supported_models = [ ("Archer C20", "AC750 Wireless Dual Band Router ") # The space at the end of the model desc is intentional ] headers = { "User-Agent": USER_AGENT, "Accept": "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Connection": "keep-alive", "Update-Insecure-Request": "1", } r = requests.post(f"http://{ip_addr}/", headers=headers) print_d(r.text) # Parse the response for the model name and model description match = re.search(r"modelName=\"([a-zA-Z0-9 ]+)\"", r.text) if not match: print("[-] Could not find the router's model name") return False model_name: str = match.group(1) match = re.search(r"modelDesc=\"(.+)\"", r.text) if not match: print("[-] Could not find the router's model description") return False model_desc: str = match.group(1) # Determine if it's in the list of supported models for supported_model in supported_models: if supported_model[0] in model_name and supported_model[1] in model_desc: print(f"[+] Found supported device: {model_name} {model_desc}") return True else: return True print(f"[-] Model name \"{model_name}\" and model description \"{model_desc}\" is not supported") return False def get_rsa_public_key(s: requests.Session, ip_addr: str) -> typing.Union[typing.Tuple[int, int, int], None]: """ Requests the public key and sequence from the router. :param s: The active HTTP session with the router. :param ip_addr: The router's IP address :return: A tuple of RSA e and n values with the sequence number on success, otherwise None """ headers = { "User-Agent": USER_AGENT, "Accept": "*/*", "Origin": f"http://{ip_addr}", "Connection": "keep-alive", "Referer": f"http://{ip_addr}", "Accept-Language": "en-US,en;q=0.5", } data = "[/cgi/getParm#0,0,0,0,0,0#0,0,0,0,0,0]0,0\r\n" resp = s.post(f"http://{ip_addr}/cgi?8", headers=headers, data=data) # On success, response should look like the following: # # ``` # [cgi]0 # var ee="010001"; # var nn="CB8FD67593B228445BBB882ED34B0787AF19AF3F6BE73793AC64BC64D3C4C41EBD149599F5801848DF92C244749DB07834789060B420979377D24DF7C7E437EB"; # var seq="690699493"; # $.ret=0; # [error]0 # ``` print_d(resp.headers) print_d(resp.text) # Get the RSA public key (i.e. n and e values) match = re.search("nn=\"(.+)\"", resp.text) if not match: print("[-] Could not find RSA n value in get RSA public key response") return None n_bytes = match.group(1) print(f"[+] RSA n: {n_bytes}") match = re.search("ee=\"(.+)\"", resp.text) if not match: print("[-] Could not find RSA e value in get RSA public key response") return None e_bytes = match.group(1) print(f"[+] RSA e: {e_bytes}") # Get the sequence. This is set to sequence += data_len and verified server-side. match = re.search("seq=\"(.+)\"", resp.text) if not match: print("[-] Could not find seq value in get RSA public key response") return None seq_bytes = match.group(1) print(f"[+] Sequence: {seq_bytes}") e = int(e_bytes, 16) n = int(n_bytes, 16) seq = int(seq_bytes, 10) return e, n, seq def authenticate(s: requests.Session, ip_addr: str, password: str) -> bool: """ Authenticates with the TP-Link router. :param s: The active requests session :param ip_addr: The router's IP address :param password: The password to the router's web server :return: True on success, otherwise False """ # Get the RSA public key parameters and the sequence rsa_vals = get_rsa_public_key(s, ip_addr) if rsa_vals is None: print("[-] Failed to get RSA public key and sequence values") return False e, n, seq = rsa_vals # Create the data field aes_key = AES_KEY.encode("utf-8") aes_iv = AES_IV.encode("utf-8") login_data: str = f"8\r\n[/cgi/login#0,0,0,0,0,0#0,0,0,0,0,0]0,2\r\nusername={USERNAME}\r\npassword={password}\r\n" data_ciphertext = tp_link_crypto.aes_encrypt(aes_key, aes_iv, login_data.encode()) data = base64.b64encode(data_ciphertext).decode() print_d(login_data) # Create the sign field seq_with_data_len = seq + len(data) auth_hash = hashlib.md5(f"{USERNAME}{password}".encode()).digest() # The string __must__ be null terminated, otherwise strlen gets the wrong size print(f"[*] Setting AES key to {AES_KEY}") print(f"[*] Setting AES IV to {AES_IV}") plaintext = f"key={AES_KEY}&iv={AES_IV}&h={auth_hash.hex()}&s={seq_with_data_len}\x00\r\n" sign = tp_link_crypto.rsa_encrypt(e, n, plaintext.encode()) print_d(plaintext) # Send the authentication request headers = { "User-Agent": USER_AGENT, "Content-Type": "text/plain", "Accept": "*/*", "Origin": f"http://{ip_addr}", "Connection": "keep-alive", "Referer": f"http://{ip_addr}/", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en-US,en;q=0.9", } request_data = f"sign={sign.hex()}\r\ndata={data}\r\n" resp = s.post(f"http://{ip_addr}/cgi_gdpr", headers=headers, data=request_data) # Get the session cookie cookie = resp.headers["Set-Cookie"] if cookie is None: print("[-] Login response did not include a Set-Cookie field in the header") return False # Example of the cookie field: # ``` # JSESSIONID=fc1e35a7a860e860be66d44bc7b34e; Path=/; HttpOnly # ``` # Get the JSESSIONID field because it's used during other requests. match = re.search(r"JSESSIONID=([a-z0-9]+)", cookie) if not match: print("[-] Could not find the JSESSIONID in the Set-Cookie filed of the login response") return False jsessionid = match.group(1) print(f"[+] JSESSIONID: {jsessionid}") # Decode the Base64 encoded response decoded: bytes = base64.b64decode(resp.text) decrypted_resp = tp_link_crypto.aes_decrypt(aes_key, aes_iv, decoded) # Remove the PKCS #7 padding num_padding_bytes = int(decrypted_resp[-1]) decrypted_resp = decrypted_resp[:-num_padding_bytes] decrypted_resp_str: str = decrypted_resp.decode() print_d(decrypted_resp_str) if "[cgi]0" in decrypted_resp_str and "$.ret=0" in decrypted_resp_str and "[error]0" in decrypted_resp_str: print("[+] Successfully authenticated with the router") else: # This might not be an error because other routers may have different response codes. The Archer C20 returns: # ``` # [cgi]0 # $.ret=0; # [error]0 # ``` print("[-] Unknown response message from router") print(decrypted_resp_str) return True def main(ip_addr: str, password: str) -> int: print(f"[*] Connecting to router at {ip_addr}") if not is_supported_model(ip_addr): print("[-] Router is not supported") return 1 s = requests.Session() success = authenticate(s, ip_addr, password) if not success: print("[-] Could not authenticate with the router") s.close() return 1 s.close() return 0 if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("ip_address", type=str) parser.add_argument("password", type=str) args = parser.parse_args() sys.exit(main(args.ip_address, args.password))
最新发布
10-16
### R语言 `seq` 和 `seq.int` 函数中的 `'to must be a finite number'` 错误 当遇到错误消息 `'to must be a finite number'` 时,这通常意味着传递给 `seq` 或 `seq.int` 的参数不是有限数值。具体来说,`from` 参数或 `to` 参数可能包含了无穷大 (`Inf`)、负无穷大 (`-Inf`) 或者非数值 (NA)[^1]。 为了更好地理解这个问题并找到解决方案,可以考虑以下几个方面: #### 检查输入数据的有效性 确保用于创建序列的起始值和结束值都是有效的有限数。可以通过打印这些变量来验证它们的内容是否符合预期。如果发现有异常值,则需要追溯到上游的数据处理逻辑中寻找问题所在。 ```r print(from_value) print(to_value) ``` #### 处理缺失值或无限值 如果有任何可能性存在 NA 值或其他特殊类型的数值,在调用 `seq()` 之前应该先清理掉这些问题数据点。一种方法是使用 `is.finite()` 来过滤掉不符合条件的元素。 ```r if (!all(is.finite(c(from_value, to_value)))) { stop("The 'from' and/or 'to' values are not finite numbers.") } sequence <- seq.int(from = from_value, to = to_value, by = step_size) ``` #### 设置合理的边界范围 有时由于计算误差或者其他因素的影响,可能会得到非常接近于零但是仍然大于机器精度极限的小数作为界限之一。这种情况下即使看起来像是有效数字也有可能触发此错误。因此建议设置一个小的安全边际以防止这种情况发生。 ```r epsilon <- .Machine$double.eps ^ 0.5 safe_from <- max(-Inf, min(Inf, from_value)) safe_to <- max(-Inf, min(Inf, to_value)) # Ensure safe boundaries with epsilon margin final_from <- pmax(safe_from - epsilon, -Inf) final_to <- pmin(safe_to + epsilon, Inf) result_sequence <- seq.int(final_from, final_to, length.out = desired_length) ``` 通过上述措施能够有效地解决大部分由非法输入引起的 `'to must be a finite number'` 类型的错误。当然具体情况还需要根据实际应用场景灵活调整策略。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值