I was also getting this king of issue when I use to type '/' as after typing '/' it was not including '\' , but if you will type '/**' then it will give '/** *\'
After the '/* * \' is written you can remove the '' from middle & the multi line comment '/* *\' will be added.
If this resolves your issue, so please upvote my answer.
the main thread may exit before the goroutines have a chance to run
@Srikanth Gopi Vivian, did you find a solution?
This issue may be caused by the HTTP request to api/users/me being made too early, before the authentication cookies for API requests are fully set.
To resolve this issue, use a wait and UI update process, as in the sample code below, to have the system wait a while for the logged-in user to be marked as authenticated.
If the error persists, please share the ApiService and UserService codes so I can investigate further and provide further assistance.
@code {
private bool _loaded = false;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender && !_loaded)
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity is not null && user.Identity.IsAuthenticated)
{
try
{
await UserService.LoadCurrentUserAsync();
_loaded = true;
StateHasChanged(); // Update UI for get the changes
}
catch (Exception ex)
{
await Console.Error.WriteLineAsync("Error with LoadCurrentUserAsync: " + ex.Message);
}
}
}
}
}
You are probably looking at using a CustomScrollView
with a series of Sliver
widgets to accomplish what you're looking for.
Fact table must have any numeric measurement like spend 200 $ on shopping.
Factless fact table is a fact table with no numeric measurement facts. It contains only foreign keys referring to dimension table. It is used to track events, conditions or relationships where no direct measurement is available or needed.
e.g- Tracking student attendance events, Tracking student registration events
This is what happens when a negro is allowed to use a personal computer.
Solved. Turns out the fragment shader's uniform input texture's 4th chanel was zero by default, it made the image transperent.
use the jdaughter module instead
jfather, json and jholy spirit
Whoever upvoted upvote this too so i can participate in chat bb
I think you should use getPrescriptionId
instead, for your schizophrenic meds before you write such shitty code again. Given your username I think you are of an inferior race so it doesn't matter?
What you are doing wrong is using Python in C (unless we talking about discord.py, then its valid)
But if u still wanna shoot yourself in the leg, hint: PyImport_ImportModule and setuptools.
GUI is itself outdated. Nowadays standalone applications are basically webapps shoved into nerfed embedded browser.
Vivado operate no just simple string, but things named "collection". To be honest, not only Xilinx use this terminology, its typical for FPGA/ASIC tools.
Collection means that when you get a result of command, like get_* , it will return not a simple list, but collection (which looks like a typical Tcl list or string), but in fact it will contains special "tag" relative to objects class (like ports, pins, bels, nets etc).
If you used get_* command and saved result into Tcl variable, this variable will also contains this "tag" and no reason to identify this objects again using get_* command.
For those using Expo, you should use getLocales()
function:
const getDeviceLocale = () => {
const locale = Localization.getLocales()[0]?.languageCode || 'en'
return locale
}
It returns the prefered app languages in order from app settings on iOS.
Source: https://docs.expo.dev/versions/latest/sdk/localization/
To fix this issue, you should use FullCalendar version 6 or newer. The API has been updated, and many configuration options—such as editable
, plugins
, and events
—are now passed directly to the <full-calendar>
component. Ensure your implementation aligns with the new structure
I have a problem with this, that I can't find a solution yet. I have two modals on my code, one of them make this when it opens:
<body class="modal-open" id="page-top" style="padding-right: 15px; overflow: hidden;" data-bs-padding-right="15px" data-bs-overflow="hidden">
But, the other add only this when it opens:
<body class="modal-open" id="page-top" style="overflow: hidden; padding-right: 15px;">
The problem is, when it closes, the first version don't remove the overflow: hidden
, and because this, the scroll bar stay hidden.
Very crazy, sorry for my comment about the problem, but it's a strange behaviour.
I fix the problem with that add to index.css or app.css and give a name to your theme variable. something like:
<div ClassName="dark:bg-amber-500">
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
if you want to read more you can read my solution
box-shadow
shouldn't have commas
You should update your box-shadow
like this:
box-shadow: 0px 0px 50px rgba(0,0,0,0.8);
Needed to add "*Friday*"
The transition from Xamarin.Forms to .NET MAUI included a move away from multiple projects in the solution (one shared project plus one project per-platform). .NET MAUI offers a single project to keep the code base more maintainable. It also provides a "Platforms" folder that can contain platform-specific code (see https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/invoke-platform-code?view=net-maui-9.0).
If you are looking to implement a "test" project for the purposes of implementing unit tests or other testing code, you can manually add a new project to your solution. You can then add your main project as a reference to the "test" project and all of the code in your main project will be available to create tests with.
This works well because it keeps your file structure cleaner, allows for implementing a unit test project, and keeps your main project smaller for the purposes of publishing the application.
This video provides a SwiftUI solution https://www.youtube.com/watch?v=dAt8qh4xi9I
(I understand SO wants code copy/pasted here. It's not my responsibility and I won't steal this video creator's traffic to help a PE-owned business. Someone else can do that if they like, or delete this working answer if they don't.)
Sometimes, this problem is caused by issues in the pubspec.lock file after a merge. I usually solve it by:
Deleting the pubspec.lock
file.
Running flutter pub get
This will recreate the file correctly and should resolve the issue.
The list of endpoints in 'shouldNotFilter' is incomplete and does not perfectly match the configuration in 'SecurityConfig'. For instance, it is missing paths like '/configuration/security', which are required for Swagger UI to function correctly. When a request for such a path is made, 'shouldNotFilter' returns 'false', causing your filter to run. Since the request to a Swagger endpoint does not contain an authentication token, your filter does nothing to the security context. However, the request is then processed by Spring Security's filter chain, which ultimately denies access because it's treated as an unauthenticated request to a protected resource, triggering your 'firebaseAuthenticationEntryPoint'.
Hope this helps. Sorry those are images but Stack seems to be new and improved and when you paste text it requires that you make them into images, cooperating w a popup they pop.
from zipfile import ZipFile
import shutil
# مسار الصورة الأصلية
image_path = "/mnt/data/A_colored_version_of_the_image_showing_the_woman_i.png"
# اسم الملف المضغوط
zip_path = "/mnt/data/colored_image.zip"
# إنشاء ملف ZIP يحتوي على الصورة
with ZipFile(zip_path, 'w') as zipf:
zipf.write(image_path, arcname="colored_image.png")
zip_path
Use credentials: 'include' when calling your API:
fetch('http://localhost:8080/api/comment/edit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include', // REQUIRED for HttpSession
body: JSON.stringify({
commentId: 1,
isPublished: true
Fix on Backend (Spring Boot)
Your current config uses setAllowCredentials(true), which is correct, but you cannot use "*" for origins when credentials are allowed. You must specify the exact origin of your frontend.
Here’s a working global CORS configuration:
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:5173"); // React dev server
config.addAllowedHeader("\*");
config.addAllowedMethod("\*"); // GET, POST, PUT, DELETE, OPTIONS
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/\*\*", config);
return new CorsFilter(so
urce);
}
}
Are primary keys and foreign keys just a unique id?
Primary keys act as a unique identifier for a tuple, yes. Foreign keys are not. A foreign key is simply a reference to another tuple in another table. However, since multiple tuples can have a foreign key that points to the same tuple, it is not unique.
Why not just call them unique ids?
Because there are multiple kinds of keys, and primary keys are just one type. Calling them a unique ID would be extraneous vocabulary. Furthermore, nothing is stopping another candidate key from also having a unique ID (e.x. a table that has User ID as a primary key, but also has SSN), so that would lead to confusion.
because calling them "primary keys" or "foreign keys" sounds odd to me
They might now, but once you understand the concepts behind these and how they differ from UUIDs and other similar terms, you'll understand why they are called that.
A primary key is a unique identifier for each record in a table. However, another table can reference that primary key and when it does, we call it a foreign key. This creates a relationship between the two tables.
Multiple records in the referencing table can point to the same foreign key value , so while a primary key must be unique, a foreign key doesn’t have to be. In other words, a foreign key is not unique because it can appear many times, but it always points to a unique primary key in another table.
Check if you have set the environment variable before running your application.
setenv('PATH',[getenv('PATH') ';' fullfile(matlabroot,'sys','FastDDS','win64','bin')])
There are some libs inside this folder you should have.
Honestly, I had much more success with RTI’s implementation in DDS Blockset.
You should install Flask-Mail in activated virtual environement:
C:\Flask_project> & C:/Flask_project/venv/Scripts/Activate.ps1
and then install by:
(venv) PS C:\Flask_project> pip install Flask-Mail
After some trial and error I determined that this error was caused by the @sentry/nextjs
package. The error no longer occurred once I removed sentry from the project. I don't know why it caused an issue. Who needs observability anyway :D
For anyone looking in future, @IvanShatsky's answer above solved it. Disable PrivateTmp and it works
sudo bash -c "cat > /etc/systemd/system/nginx.service.d/override.conf" <<EOF
[Service]
PrivateTmp=false
EOF
IMHO setting the requireForce
via environment variable does not make sense.
I want to have it active ALWAYS.
So that the application will never drop my database unless I actively set force=true
.
As Spring Boot unfortunately does not support the requireForce
parameter, I set it like so:
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
System.setProperty("liquibase.command.dropAll.requireForce", "true");
SpringApplication.run(MyApplication.class, args);
}
}
Then in my run configuration for my dev environment I can add -Dliquibase.command.dropAll.force=true
.
This way, when I have spring.liquibase.drop-first=true
in my properties in my production environment, my application startup will ALWAYS fail instead of dropping my production database.
As @Tilman Hausherr pointed out, you embed a subsetted Unicode font, but I think the font is subsetted correctly. You may share your PDF for examination.
I believe you see the wrong order of Arabic/Hebrew words and/or reversed order of symbols in those words. Is it what you mean by "garbled"?
PDFBox doesn't support RTL scripts, so in case of RTL you need to use a 3rd-party library for BIDI reordering. See a good discussion about this topic and the solution here: Writing Arabic with PDFBOX with correct characters presentation form without being separated
---
As for proper text displaying on MacOS:
The default value of text fields (/V value in the Text field dictionary) is constructed using explicit UTF_16BE encoding.
Text in the default appearance stream is created by Unicode code points and the Java default character encoding.
You may compare the /V value in the field dictionary and the text inside the default appearance stream of the field (in angular brackets before the Tj operator).
So I guess you have different Java/System encodings on Windows and MacOS. Another thing I can think of is that a viewing PDF software on MacOS skips the Appearance Stream dictionaries of AcroForm (text) fields, but I very doubt about the latter one.
Here is a view that combines both the top-down calls, and bottom-up execution with the 'substitution' side by side.
kustomize build k8s | kubectl apply -k .
https://stackoverflow.com/users/6110557/rohitcoder
TQ for the INFO above. You save me fro continue being attacked by any.
Dim sString As String
Dim arrString
Dim i As Integer
List1.Clear
List1.AddItem "Orignal string"
sString = "aaaa; bbb; ccccc ; ddd"
List1.AddItem sString
arrString = Split(sString, ";")
List1.AddItem "Split string"
For i = 0 To UBound(arrString)
List1.AddItem Trim(arrString(i))
Next
List1.AddItem "Back joined with " & Chr(34) & "," & Chr(34)
List1.AddItem (Join(arrString, ","))
As suggested here https://stackoverflow.com/a/73525890 you can let the database set the timestamp using the insertable
and updatable
Column options:
#[ORM\Column(insertable: false, updatable: false)]
private \DateTime $my_date;
Tried all of these answers, but none seemed to work for me. Switching to a different network did the trick though.
Maybe you use Virtual enviroment.
If you use this, see the install location.
Use a live distro which can boot from a cd or a USB stick.
Change the sudo rights for the root folder (/) back.
Then you should be able to use sudo as usual
$pass = substr(base64_encode(md5(str_shuffle(time()))),0,8);
Example output: N2UxYzZm
The original question only asked for letters and numbers, not special chars. So this approach takes the current time stamp, shuffles it and gets the first eight chars of the base64 encoded md5 hash from it. This should be pretty random, even if you knew the time stamp when the password was created it is still shuffled, just in case two people generate a password at the exact same timestamp. You can also shuffle the substring if you want or the md5 hash, as well. But for enough randomness, I guess it would do.
The problem was that I forgot to exclude my vitest.config.ts from tsconfig.build.json, as shown below.
It made vitest.config.ts get compiled into a vitest.config.js inside the dist folder:
Which made the extension think it should consider that file and locked it for some reason (I don't know why, to be honest).
Adding vitest.config.ts
to exclude solved my problem.
PowerAutomate is limited to watch only one Folder unfortunately.
You can setup mutiple trigger flows for each folder and then trigger a common "main" flow to add to the Microsoft List
I had the same issue. Turns out strict mode, in React/NextJs , made the session generate twice, which was triggering the validation of set Session Id.
I had the same issue on ubuntu 22.04 LTS.
For me the issue is I was using the jupyter as a system service(so I could just visit the url directly any time).
If I just start a new instance from command line, this issue goes away.
There is an alternative ferrum_pdf that is not based on wkhtmltopdf, which has not been developed for a long time and creates a number of problems for installation on most modern repositories. It's like a sip of water in the desert. But it's perfect for creating PDFs and screenshots of static pages.
Simply run this command : sudo npx expo start --tunnel
I know this won't help if you've already deleted your menu, but I created this plugin after making the same mistake myself: https://wordpress.org/plugins/menu-backup-restore/advanced/
Now, every time I save a menu, it automatically creates a backup. I can restore any previous version whenever I need to.
Finally i've managed to solve this by hiding the stack navigator header once and for all. Then i implemented the content of the drawer header based on the current route, hence showing a back button inside the [userid] route
If you're getting this error during YOLOv5 training:
tensorflow.python.framework.errors_impl.FailedPreconditionError: runs\train\<name> is not a directory
and you're using a folder path that contains non-ASCII characters, it's caused by TensorBoard (TensorFlow) failing to write logs in Unicode paths on Windows.
You can fix it by disabling TensorBoard logging in YOLOv5:
Open yolov5/utils/loggers/__init__.py
Find this line:
self.tb = SummaryWriter(str(s))
self.tb = None
This disables TensorBoard logging and prevents the crash.
Looks like this, right?
To make a child `div`
scrollable is to give it a fixed or constrained height. To achieve it, apply `
overflow: auto
or
overflow-y: scroll
Here's an example CSS:
.layout-container {
display: flex;
height: 100vh; /* => Fill the full screen */
}
.sidebar-scrollable {
width: 250px;
height: 100%; /* => Fill the parent height */
overflow-y: auto; /* => Enable vertical scrolling */
padding: 10px;
box-sizing: border-box;
background-color: #f9f9f9;
}
.main-content {
flex: 1;
padding: 20px;
}
Hopefully, this will help
The issue is likely caused by gdal2tiles.py
producing too much output, which fills up the Python subprocess output buffers and causes it to hang silently. Even with a timeout set, the process won’t exit if those buffers are full. To fix this, remove capture_output=True
from your subprocess.run
call so the output flows directly to the terminal and doesn't get stuck. This usually resolves the deadlock when running GDAL tools inside a Docker container.
In my case, changed wordpress fpm alpine version into fpm version solved this problem.
alpine version has some drawbacks(of course it's faster and lighter)
Found it: right click on MyInterface - find usages advanced - select scope current file and find "usages of members"
FYI I would convert to float16 (2x smaller, almost no loss).
But best practical answer (keeps float32 precision at read time, shrinks disk by ~4x, gives millisecond random row fetch):
quantize to float8
1 byte per value instead of 4 bytes -> 500gb -> 125gb
benchmarks (Naamán Huerga-Pérez et al.) shows smaller than 0.3 quality loss.
Store as a single memory-mapped binary file
If you later want even smaller, combine light pca drop to 384 dims + float8 -> 60~GB total. thats the simplest, fastest route to both goals.
Your code works fine with me TF2.12.0 however it does not print anything. Use tf.print instead of print if you want print statements in your tf.function.
For max_seq_length error use 'max_length' instead
in new version they changed it to max_length
ctrl + enter works on windows.
The issue is with how you're setting the context.fillStyle. You're using a template string inside single quotes, which doesn't interpolate the variables. This makes the color string invalid, so the canvas defaults to black.
Incorrect: context.fillStyle = 'rgba(${myColour[0]}, ${myColour[1]}, ${myColour[2]}, ${myColour[3]})';
This literally sets the string "rgba(${myColour[0]}, ...)" which is not a valid CSS color.
Fix: Use backticks instead of single quotes to enable string interpolation:
context.fillStyle = `rgba(${myColour[0]}, ${myColour[1]}, ${myColour[2]}, ${myColour[3] ?? 1})`;
You can also use destructuring:
const [r, g, b, a = 1] = myColour;
context.fillStyle = `rgba(${r}, ${g}, ${b}, ${a})`;
Change:
mkdir -p $deploydir
to
mkdir -p '$deploydir'
This solution worked for my case.
Restrict your workspace to just the folder you actually care about.
Change your devcontainer.json
so that VS Code’s workspace is /workspace
(location of the ode), not /
.
React is case sensitive. You have import { Navbar } from "./components/navbar";. The N on Nav should be capitalized.
It's easily feasible, but it depends if you are using a specific framework. In brief :
If You use a simple Java Application, you create a simple Java Application on NETBEANS IDE and you just need to copy and paste all the code you wrote previously to the NETBEANS IDE.
My previous code in Vs code :
After simple copy -paste operations in NETBEANS IDE :
Then you can create any GUI components (Jpanels, Jframes, etc..) and include them in your orginal code.
For example in the above screenshot, the Chat.java file corresponds to a Jpanel I just created through the NETBEANS IDE, and by writing some code I easily integrate it with the original code.
2. Similarly, If you are building a Maven or Gradle Java project, you just need to repeat the same process but choosing a different option when you create a project on the NETBEANS IDE :
For example for a Maven project :
For example for a Gradle project:
Dim myName As String
Dim outputstring() As String, OutArray() As Variant
Dim VarObj As Variant, K As Integer
myName = "Gur, singh, Mac, Math, Eng"
List1.Clear
outputstring = Split(myName, ",")
For K = LBound(outputstring) To UBound(outputstring)
List1.AddItem Trim(outputstring(K))
Next K
This is for DITA XML content. The specification states the element with the conref attribute gets replaced completely with the target element, so its current text is fully ignored in the published output. You can probably place the symbols before the data element.
I believe the problem to be propagation of changes for Private DNS.
Give it 15-20 minutes to stabilise and retry.
I encountered this error after a destroy and (impatient) redeploy. I am using private endpoints, and running terraform from inside the vnet.
A process can be terminated in ways other than signals, normal exits (exit()), or unhandled exceptions. Here are some additional mechanisms:
✅ 1. Killed by the Kernel (OOM Killer)
If the system runs out of memory, the Out-Of-Memory (OOM) killer may forcibly terminate a process: No signal from user space is sent manually.
The process is terminated by the kernel to free up memory.
💡 Detectable in logs via dmesg or system logs.
✅ 2. Killed by Parent Process Using ptrace or process_vm_writev
A parent or debugger can manipulate or terminate a child using ptrace:
Inject code or overwrite memory.
Can simulate a crash or exit by corrupting the instruction pointer.
✅ 3. Segmentation Fault or Illegal Instruction
If a process accesses invalid memory or executes an illegal instruction, it will terminate.
Although this results in a signal (e.g., SIGSEGV, SIGILL), it’s not from an external source—it's due to internal program behavior.
✅ 4. abort() or assert() Failures
abort() triggers abnormal termination and generates a core dump.
Common in libraries when internal errors are unrecoverable.
✅ 5. Kernel Panic or Hardware Failure
A system crash, hardware fault (e.g., CPU, memory failure), or disk corruption could kill processes without going through the usual exit routines.
✅ 6. Container or CGroup Restrictions
If a process exceeds CPU, memory, or I/O quotas in a container or control group, it may be killed.
These terminations are managed by the kernel or container runtime (e.g., Docker, Kubernetes).
✅ 7. Filesystem or I/O Errors
A blocked I/O operation, unmounted filesystem, or disk error might cause a process to be forcibly terminated by the kernel.
✅ 8. Dynamic Library Failures (e.g., dlopen/dlsym)
Failure in shared library loading or mislinked symbols during dynamic loading might crash the process.
✅ 9. Overwriting the Stack or Heap (Undefined Behavior)
A bug like buffer overflow may corrupt memory, leading to an unpredictable crash without an explicit signal or exit.
✅ 10. System Calls Returning Irrecoverable Errors
Some system calls (e.g., execve, fork) may result in fatal errors if misused or constrained by resource limits.
Conclusion:
Even when not terminated by an explicit exit(), signal, or exception, a process can still be terminated via:
Kernel interventions
Resource limits
Internal bugs or memory corruption
Debugger or parent manipulation
had same problem, Its happening because of unavailability of the python version
Here that worked for me.
create a virtual env using python 3.10
search for this file on Google "fasttext‑0.9.2‑cp310‑cp310‑win_amd64.whl"
pip install <location to the wheel file>
I fixed it by creating a separate keychain for building the app, imported the developer certificate into it. In my script that i run remotely, i unlock this keychain and voila the build now runs just like it does when i run it from the mac directly
The issue is that iOS development has a fundamental limitation: you cannot build and code-sign iOS apps from Windows, even remotely.
https://www.npmjs.com/package/react-native-dream-toast
A beautiful, customizable, and lightweight toast notification system for React Native. Supports theming, queueing, global config, icons, and full TypeScript support.
Use this for better an beautiful toasts
You can not directly run a .exe
as administrator via shell()
in R because it doesn't elevate privileges.
Use PowerShell to prompt UAC
shell('powershell Start-Process "C:\\Path\\To\\your.exe" -Verb RunAs')
I had the same issue, Though in my case i had earlier initialised a git repository but after a while it started behaving that way(Compressing for hours), re initializing git solved the issue but ended up loosing my track
Use
PreparedStatement.RETURN_GENERATED_KEYS
PreparedStatement.getGeneratedKeys();
may help get primary keys after executeBatch(), return whole data is not supposed.
to just www.Example.com.I have changed my internal links
None of the proposed solution work. It keeps creating a subfolder, or even worth, a 1Kb archive for each folders
the javascript looks fine but the html doesn't look right for a javascript function call.
also the purpose of functions is to write once and call many times, so using
<body onload="printBtn();"> defeats that purpose; so how do we call it again???
This is an old question but I have not seen an answer anywhere that does not use Xarray (which is overkill for this simple example). Since I recently made such a function using pandas and base Python alone, I thought I would share it here. It's pretty lengthy to handle all foreseeable cases, but please let me know if you find an edge case that Claude Code and I haven't anticipated.
import pandas as pd
from typing import Union, Optional
import calendar
def custom_year_averages(
data: pd.Series,
start_month: int,
end_month: int,
years: Optional[Union[int, list, range]] = None
) -> pd.Series:
"""
Compute weighted averages over custom year periods that may straddle calendar years.
Parameters
----------
data : pd.Series
Time series data with DatetimeIndex. Can be daily or monthly frequency.
start_month : int
Starting month of the custom year (1-12).
end_month : int
Ending month of the custom year (1-12).
years : int, list, range, or None
Year(s) for which to compute averages. If None, computes for all available years.
For straddling periods (e.g., Apr-Mar), year refers to the year of the end month.
Returns
-------
pd.Series
Series index by year, with weighted averages as values.
Examples
--------
.. jupyter-execute::
import pandas as pd
import numpy as np
# Create sample monthly data
dates = pd.date_range('2020-01-01', '2023-12-31', freq='M')
values = np.arange(len(dates)) # Sequential values for clarity
ts = pd.Series(values, index=dates, name='monthly_values')
# Example 1: Single year (int)
# Compute Jan-Mar average for 2021 only
avg_single = custom_year_averages(ts, 1, 3, years=2021)
print("Single year (2021):")
print(avg_single)
print()
# Example 2: List of specific years
# Compute Apr-Mar averages for selected years
avg_list = custom_year_averages(ts, 4, 3, years=[2021, 2023])
print("Specific years [2021, 2023]:")
print(avg_list)
print()
# Example 3: Range of years
# Compute Oct-Sep averages for consecutive years
avg_range = custom_year_averages(ts, 10, 9, years=range(2021, 2024))
print("Range of years (2021-2023):")
print(avg_range)
print()
# Example 4: All available years (None - default)
# Compute Jan-Dec averages for all years in data
avg_all = custom_year_averages(ts, 1, 12, years=None)
print("All available years (None):")
print(avg_all)
print()
# Example 5: Straddling periods with different year specifications
# Apr-Mar periods: year refers to the March year
avg_straddle = custom_year_averages(ts, 4, 3, years=range(2021, 2024))
print("Straddling periods (Apr-Mar), years 2021-2023:")
print(avg_straddle)
.. jupyter-execute::
# Daily data example with uneven spacing
daily_dates = pd.to_datetime([
'2021-01-01', '2021-01-05', '2021-01-20',
'2021-02-01', '2021-02-15', '2021-02-28',
'2021-03-05', '2021-03-25', '2021-03-31'
])
daily_values = [10, 15, 20, 25, 30, 35, 40, 45, 50]
daily_ts = pd.Series(daily_values, index=daily_dates, name='daily_data')
# Compute weighted average (accounts for uneven spacing)
daily_avg = custom_year_averages(daily_ts, 1, 3, years=2021)
print("Daily data with uneven spacing (Jan-Mar 2021):")
print(f"Weighted average: {daily_avg.iloc[0]:.2f}")
print(f"Simple mean: {daily_ts.mean():.2f}")
print("(Note: weighted average accounts for time intervals between observations)")
"""
if not isinstance(data.index, pd.DatetimeIndex):
raise ValueError("Data must have a DatetimeIndex")
if not (1 <= start_month <= 12 and 1 <= end_month <= 12):
raise ValueError("Months must be between 1 and 12")
# Determine if the period straddles calendar years
straddles_year = start_month > end_month
# Get available years from data
data_years = sorted(data.index.year.unique())
if years is None:
if straddles_year:
# For straddling periods, we need data from both years
years = [y for y in data_years if y > min(data_years)]
else:
years = data_years
elif isinstance(years, int):
years = [years]
results = {}
for year in years:
if straddles_year:
# Period spans two calendar years (e.g., Apr 2020 to Mar 2021)
start_date = pd.Timestamp(year=year-1, month=start_month, day=1)
end_date = pd.Timestamp(year=year, month=end_month, day=calendar.monthrange(year, end_month)[1])
else:
# Period within single calendar year
start_date = pd.Timestamp(year=year, month=start_month, day=1)
end_date = pd.Timestamp(year=year, month=end_month, day=calendar.monthrange(year, end_month)[1])
# Filter data for this period
mask = (data.index >= start_date) & (data.index <= end_date)
period_data = data[mask]
if len(period_data) == 0:
continue
# Calculate weighted average
weighted_avg = _calculate_weighted_average(period_data, start_date, end_date)
# Use the ending year as the index (standard for fiscal years)
results[year] = weighted_avg
# Return results only for years that have data
return pd.Series(list(results.values()), index=list(results.keys()), name=data.name or 'weighted_average')
def _calculate_weighted_average(
data: pd.Series,
period_start: pd.Timestamp,
period_end: pd.Timestamp
) -> float:
"""
Calculate weighted average where weights are based on time intervals.
For monthly data, each month gets equal weight regardless of days.
For other frequencies, weights are based on time intervals.
"""
if len(data) == 0:
return np.nan
if len(data) == 1:
return data.iloc[0]
# Sort data by index
data = data.sort_index()
timestamps = data.index.to_series()
# Check if this looks like monthly data (all timestamps are month-ends)
is_monthly = all(
ts.day == calendar.monthrange(ts.year, ts.month)[1]
for ts in timestamps
)
if is_monthly:
# For monthly data, give each month equal weight
return data.mean()
# For non-monthly data, use time-interval weighting
intervals = []
for i, ts in enumerate(timestamps):
if i == 0:
# First observation: from period start to midpoint with next
if len(timestamps) > 1:
interval_end = ts + (timestamps.iloc[i+1] - ts) / 2
else:
interval_end = period_end
interval_start = period_start
elif i == len(timestamps) - 1:
# Last observation: from midpoint with previous to period end
interval_start = timestamps.iloc[i-1] + (ts - timestamps.iloc[i-1]) / 2
interval_end = period_end
else:
# Middle observations: from midpoint with previous to midpoint with next
interval_start = timestamps.iloc[i-1] + (ts - timestamps.iloc[i-1]) / 2
interval_end = ts + (timestamps.iloc[i+1] - ts) / 2
# Ensure intervals don't extend beyond the period
interval_start = max(interval_start, period_start)
interval_end = min(interval_end, period_end)
interval_duration = (interval_end - interval_start).total_seconds()
intervals.append(max(interval_duration, 0)) # Ensure non-negative
weights = np.array(intervals)
# Handle case where all weights are zero
if weights.sum() == 0:
return data.mean()
# Calculate weighted average
weighted_sum = (data.values * weights).sum()
total_weight = weights.sum()
return weighted_sum / total_weight
Goal: Distribute requests across a dynamic set of nodes with minimal disruption when nodes are added/removed.
How: Hash the request (e.g., user ID or session ID) and place it on a ring. Then route it to the next clockwise node.
Goal: Route requests from the same client (usually with the same session) to the same backend worker (app server).
How:
Use cookies or IP address or session ID to identify clients.
Use a map/cache internally to remember which client is mapped to which worker.
Sticky sessions can use consistent hashing as a strategy, but they don’t have to. Typically, sticky sessions use a map or hashMap of session ID -> worker.
(Sorry if this post is useless, but in case it does help somebody I wanted to post.)
The answer put me on the right path. I wanted to resize the RectTransform of an image so that the size of the RT was close to the size of the rendered image (so only the image area was noticed by OnPointerClick). This StackOverflow post helped me size the width of the RT to the image, and I used a cross-multiply and divide to change the height when needed.
//getting the image
Image img = selectionRectTran.img;
//the initial/base size of the RT, resetting to it here
img.GetComponent<RectTransform>().sizeDelta = initialWidthHeightForSelectionImg;
float width = 0f;
float height = initialWidthHeightForSelectionImg.y; //default height
width = RectTranUtils.GetDesiredWidth(img); //from https://stackoverflow.com/questions/65385248/unity-get-the-actual-rendered-sprite-height-in-image-ui
width = Mathf.Clamp(width, 0f, img.GetComponent<RectTransform>().sizeDelta.x);
Debug.Log($"width diff: {Mathf.Abs(width - initialWidthHeightForSelectionImg.x)}");
//if the image is as wide as possible (ie, basically 0 diff between width between width and the default width)
//and the sprite - in pixels - is wider than it is tall, so there's some unwanted bounding box space on top and below the image
if (Mathf.Abs(width - initialWidthHeightForSelectionImg.x) < GameManager.TinyAmount
&& img.sprite.texture.width > img.sprite.texture.height)
{
//h = width * height of image in pixels / width of image in pixels
height = width * img.sprite.texture.height / img.sprite.texture.width;
}
img.GetComponent<RectTransform>().sizeDelta = new Vector2(width, height);
Great video solution , I still facing some problem
I have changed my splash-icon.png in ./assets/images/splash-icon.png
(deleted the default splash screen of react-native with expo) but still my app is showing the default splash screen,
i have cleared the cache : npx expo start -c
still the problem persist
I resolved the issue by moving the controller class declaration to the top of the controller file. It seems the previous structure was affecting how the framework recognized the controller. After the change, everything started working as expected.
As the error suggests, using the +
operator for concatenation is only valid if both sides are strings. Python uses string formatting instead of concatenation when mixing strings and variables. In modern Python (3.6+), your example can be simplified using f-strings:
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)
This format is easier to read, and avoids the TypeError
. Prior to Python 3.6, you would have needed to use the %
operator and sprintf
-style formatting:
name = "Alice"
age = 25
message = "My name is %s and I am %d years old." % (name, age)
print(message)
In addition to the official Python docs linked above, there is also a good tutorial at Real Python that discusses these techniques in more detail.
socket.reconnectStrategy
In the modern node‑redis client (v4 and later), you don’t use the old retry_strategy
option. Instead, you configure reconnection using the socket.reconnectStrategy
option when creating a client:
js
CopyEdit
import{ createClient } from 'redis'; const client = createClient({ socket: { reconnectStrategy: (retries, cause) => { if (retries >= MAX_ATTEMPTS) { return new Error('Too many reconnect attempts'); } // Return a delay in ms before next retry return calculateDelay(retries); } } }); client.on('error', err => console.error('Redis error', err)); await client.connect();
retries
is the count of attempts so far, starting at 0.
cause
is the Error that triggered this reconnect attempt.
If the function returns:
false
or new Error(…)
→ stop retrying.
a number (ms) → that’s the delay before the next attempt.
This gives full control—you can stop after a fixed number or vary delay. npm+12Redis+12Stack Overflow+12Stack OverflowUNPKG+4Redis Documentation+4Snyk+4
node-redis-retry-strategy
packageIf you're using legacy clients expecting retry_strategy
, or you need a drop‑in function:
The node-redis-retry-strategy
package provides a strategy where you can configure:
number_of_retry_attempts
(default 5)
delay_of_retry_attempts
(default 500 ms)
wait_time
(how long before quitting retries, default 300 000 ms) npm+2UNPKG+2Snyk+2
Example:
js
CopyEdit
constredis = require('redis'); const retryStrategy = require('node-redis-retry-strategy'); const client = redis.createClient({ host: '127.0.0.1', port: 6379, retry_strategy: retryStrategy({ number_of_retry_attempts: 7, delay_of_retry_attempts: 1000, wait_time: 600000 }) });
This is helpful if you’re migrating older code or using compatibility layers. UNPKGSnyk
In node‑redis v4+, retry_strategy
, max_attempts
, retry_max_delay
, and connect_timeout
are deprecated.
Instead, custom reconnect logic is done via socket.reconnectStrategy
. By default, reconnection is disabled unless you specify a strategy. Redis+8Stack Overflow+8Snyk+8
Default behavior without configuration is: no reconnection, so if you don’t provide reconnectStrategy
, the client won’t retry.
ScenarioHow to set retry countExample
behaviorNew node‑redis (v4+)Use socket.reconnectStrategyYour custom function handles limits and delayLegacy code expecting retry_strategyUse node-redis-retry-strategy packageConfigure with number_of_retry_attempts etc.
Imagine Redis connection drops. You want it to try reconnecting a few times—say 5 attempts—with increasing wait times. In modern node‑redis, you hand it a little function:
js
CopyEdit
reconnectStrategy: (retries, err) => { if (retries >= 5) return new Error('Reached retry limit'); return retries * 500 + Math.random() * 100; }
That way, if Redis goes offline, your app will give it up after the 5th try. Before then, it’s patiently trying again with a touch of randomness (jitter).
from docx2pdf import convert
# Convert the Word document to PDF
pdf_path = "/mnt/data/Theoretical_and_Conceptual_Framework_Formatted.pdf"
convert("/mnt/data/Theoretical_and_Conceptual_Framework_Formatted.docx", pdf_path)
pdf_path
Mỗi dịp năm học mới đến, việc chuẩn bị đầy đủ đồ dùng học tập là điều vô cùng quan trọng để học sinh bước vào một hành trình học tập hiệu quả và tự tin. Dưới đây là danh sách những món đồ học sinh nào cũng nên có trong cặp sách của mình.
Bút bi, bút máy, bút chì là những vật dụng quen thuộc trong mỗi giờ học. Việc chọn bút phù hợp với tay cầm, mực đều và không lem sẽ giúp nét chữ đẹp hơn, viết lâu không bị mỏi tay. Những thương hiệu như Thiên Long, Pentel hay Deli luôn được phụ huynh tin tưởng lựa chọn.
Tập vở nên được chọn theo từng môn học, có dòng kẻ rõ ràng, giấy trắng, dày và không thấm mực. Việc phân loại vở theo từng môn giúp học sinh ghi chép gọn gàng và dễ dàng ôn tập khi cần.
Đối với học sinh cấp 2, cấp 3, bộ thước kẻ, eke, compa là những đồ dùng học tập cần thiết. Các sản phẩm nên có độ chính xác cao, làm từ nhựa tốt, không dễ gãy và không có cạnh sắc nhọn.
Một chiếc balo nhẹ, chống gù, nhiều ngăn sẽ giúp các em mang theo đầy đủ sách vở mà vẫn bảo vệ cột sống tốt. Hộp bút giúp sắp xếp dụng cụ viết một cách gọn gàng, tránh thất lạc.
Không chỉ phục vụ học tập, những món như màu nước, bút highlight, giấy màu… còn giúp học sinh phát triển tư duy sáng tạo, đặc biệt quan trọng ở bậc tiểu học và mầm non.
Hiện nay, các bậc phụ huynh có thể dễ dàng mua đồ dùng học tập học sinh chính hãng, an toàn và giá cả hợp lý tại Tên website của bạn – nơi cung cấp đầy đủ các sản phẩm từ bút viết, vở, balo, hộp bút đến đồ dùng mỹ thuật. Các sản phẩm đều được chọn lọc kỹ càng, phù hợp với từng độ tuổi và cấp học.
Chuẩn bị đầy đủ đồ dùng học tập không chỉ giúp học sinh học tốt mà còn rèn luyện tính ngăn nắp, chủ động. Đầu tư vào những món đồ học tập chất lượng là cách thiết thực để đồng hành cùng con trên chặng đường học vấn.
1. Check Your Redirect URIEnsure the redirect URI you specify in your code exactly matches (character by character) the one registered in your Instagram App settings.
The URI must use https (not http). Instagram does not allow non-HTTPS redirect URIs for security reasons.
Avoid using localhost unless it’s explicitly allowed in your app settings.
2. Validate Instagram App Configuration
Make sure you are using the correct Instagram App ID, not a Facebook App ID.
Double-check your Instagram Developer Dashboard that:
The redirect URI is whitelisted under “Valid OAuth Redirect URIs”.
Your app is in “Live” or “Development” mode as needed and the test users are assigned if in “Development”.
3. Initiate the OAuth Flow Correctly
When the user clicks “Login with Instagram”, redirect them to the Instagram OAuth endpoint (example URL structure):
[
https://api.instagram.com/oauth/authorize
?client_id=YOUR_APP_ID
&redirect_uri=YOUR_REGISTERED_URL
&scope=user_profile,user_media
&response_type=code
]
Use window.location.href = authUrl; in your front-end code to perform the redirect.
4. Handling the Redirect
After the user logs in on Instagram and authorizes, Instagram will redirect to your URI with a code parameter:
[ YOUR_REGISTERED_URL?code=AUTHORIZATION_CODE ]
Capture this authorization code from the URL.
5. Exchange Code for Access Token
In your backend, POST to https://api.instagram.com/oauth/access_token including:
client_id
client_secret
grant_type (set to authorization_code)
redirect_uri (same one)
codee (the one from Instagram)
Make sure the backend endpoint is reachable and working properly.
6. Common Pitfalls
Invalid redirect_uri: This is the most frequent error. Triple-check the matching and HTTPS requirement.
Wrong environment: If the app is not Live, only registered test users can log in.
Cache/cookies: Sometimes, browser caching or cookies can cause old values (clear them if issues persist).
App Secret/PKCE: Instagram Basic Display does NOT support PKCE, and requires you to send the app secret in the token request.
Get-MailboxStatistics -Database 'Mailbox Database 123' |
Where-Object {$_.TotalItemSize.Value.ToMB() -le 5} |
Sort-Object TotalItemSize -Descending |
Select-Object DisplayName,TotalItemSize
You don’t need a domain, but having one gives you credibility and makes registration easier.
technically you can register an app for OAuth2 with most providers like Google without owning a custom domain. But it's often smoother with a domain, because:
Providers like Google might treat domain-less apps as “less trustworthy”
Users get warned with scary security messages
You may not be able to set up branded consent screens
So, you can go domain-free... it just means you might have to live with a few restrictions or workarounds.
Will app registration work for others using your app?
It depends on the provider and how you register:
If you register your app and embed client ID/secret in your code, you could allow others to use your app's credentials to send emails.
However, that's usually not safe—those credentials could get abused or leaked.
A better model: build the app so users authorize it themselves (via OAuth2), and store their tokens securely.
Apps like Thunderbird do this: they register themselves as a trusted application with providers like Google, then walk users through OAuth login. Each user gets their own token, and the app doesn’t need to know your password.
In your gradle.properties
, add this:
android.aapt2Version=8.6.1-11315950
Turns out I forgot to import hdf5plugin
in the separate ipynb that I used to read in the h5 file. It works now.
You use libx264rgb, however mileage may vary depending on how you plan to play it (for instance if I watch it in mpv it looks correct, but in chromium the colors looked very much wrong). libaom-av1, libvpx-vp9 and libx265 also support this via the gbrp pixel format.
ok, apparently this is just a bug
https://github.com/golang/go/issues/71497?issue=golang%7Cgo%7C74835
You can add a named range for each section, and use the Named ranges sidebar as a clickable jump pad.
So, this issue will appear any time your package.json's dependencies field is in an invalid state. Mordy's comment is one way to get this to happen, Raja Uzair Zia's answer is another way, and one more is if external tooling directly edits the package.json file. (Expo is especially bad about this. If you try to npx expo install any invalid package, it'll happily break your package.json trying to install it.)
A fix is to go into your package.json and ensure that all packages A) exist on npm with the exact name seen in your package.json, and B) have valid names and version numbers.
This usually means there's a naming conflict in your environment most likely you have a file or folder named google.py or a directory named google/ in your current working directory or Python path which conflicts with the actual google package