instruction stringlengths 0 30k ⌀ |
|---|
|python|variables|math|scipy|numerical-integration| |
I prepare my own legend with checkboxes for echarts. When a checkbox is clicked, it invokes a special function to remove data from the chart. I remove or add this data from series and reload chart.
However eCharts has own legend with events like legendToggleSelect and select etc. Maybe can I use some functions or maybe dispatchAction to show/hide data instead of add/removing?
I try to use dispatchAction, but it doesnt show/hide, it only start animations.
I use dispatchAction like that:
```
myChart.dispatchAction({
type: "legendToggleSelect",
name: id,
});
```
But in only start animations, not hide/show series.
|
Calling `await` blocks until the promise is resolved or rejected, so that means that calling `controller.abort()` rigth after the loop has started won't be effective until the promise has resolved and the loop starts over.
Adding an event listener (if you're working with nodejs you can use event emitters) to your cancellable async function might do the trick, maybe this example helps you to achieve what you want:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function myCancellableFunction (signal) {
return new Promise((res,rej) => {
if (signal.aborted) return rej();
const cancellableHandler = () => {
// you may also want to perform a clean up here
// like removing the timeout from your timeouts list
signal.removeEventListener("abort",cancellableHandler);
rej();
}
signal.addEventListener("abort",cancellableHandler);
setTimeout(res,2000);
})
}
async function myLoopSignalFunction (signal) {
while (true) {
console.log("While loop beginning");
try {
console.time("Cancellable elapsed time");
await myCancellableFunction(signal);
console.log("Cancellable function has been executed");
console.timeEnd("Cancellable elapsed time");
} catch(e) {
console.log("Function has been canceled");
break;
}
}
}
async function main () {
let controller = new AbortController();
myLoopSignalFunction(controller.signal);
setTimeout(() => {
controller.abort();
setTimeout(() => {
controller = new AbortController()
controller.abort()
myLoopSignalFunction(controller.signal); // The controller is already aborted, nothing to do
},1000);
},10000);
}
main()
<!-- end snippet -->
|
I was solving this problem on Leetcode but I am unable to understand why my solution is wrong I am using the hash map approach to solve this, the time complexity is O(n) but the error is not something related to time exceeding
**Question:**
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
```txt
Example 1:
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.
Example 2:
Input: s = "", t = "y"
Output: "y"
Constraints:
0 <= s.length <= 1000
```
**my Solution**
```
var findTheDifference = function (s, t) {
let mapSet = {}
let final = ""
s.split('').forEach((elem) => {
mapSet[elem] === undefined ? mapSet[elem] = 1 : mapSet[elem]++
})
console.log(mapSet)
t.split('').forEach((elem) => {
mapSet[elem] === undefined ? mapSet[elem] = 1 : mapSet[elem]--
if (mapSet[elem] != 0) {
console.log(mapSet, mapSet[elem])
final = elem
}
})
console.log(mapSet)
return final
};
``` |
I have made an android app (using MIT app inventor) that runs a service in the background using the Itoo extension. This means that I have no access to the android code behind it. The service is supposed to run even if the app is closed which it does in mobile phones like the Xiaomi Redmi and Samsung Galaxy but in **Realme 8i (Android 13)** it stops after 5-6 minutes.
I realized that this is because the phone goes into "doze mode".
I have disabled every battery optimization setting I could find (like I did in the other phones and worked) but the service is still killed after 5-6 minutes.
What I found out was that if the service sends a notification for example every 1 sec AND the notification sound is **not** silenced, then the service stays alive ! But **if the notifications sound is silenced** the it gets killed.
I would upload a simple .apk to demonstrate this but I can't.
Can someone tell me how to overcome this problem ?
I have been contacting with Realme support team about 1-2 months now and exchanged around 40 e-mails. They have an automated system that every time forwards your msg to another person and they actually don't keep the history of the previous ones, so the guy asks things that I have already answered before. You can imagine how frustrating that was.
Thanks in advance
Jim
In detail I have tried the following:
1. Setting > Apps > App management > click "settings" > show system > search "battery" > Manage notifications > Disable all the notification option
2. enabled the permission in :
a. settings > battery > more settings > optimize battery use > find the app and choose do not optimize.
b. settings > battery > more settings > optimized standby > off.
c. settings > battery > more settings > app battery management > find the app choose allow background activity.
3. Lock the app to run in the background |
Problem with Android App background service stoping |
|android|service|background| |
null |
{"Voters":[{"Id":3776927,"DisplayName":"derpirscher"},{"Id":476,"DisplayName":"deceze"}],"SiteSpecificCloseReasonIds":[13]} |
Jetpack compose - how I can hookup LiveData property from ViewModel with TextField in activity? |
|android|kotlin|mvvm|android-jetpack-compose| |
I have imported the .less file to the vue component, but it still gives me an error.
I define the variables in `base.less` under `assets/less`.
[enter image description here](https://i.stack.imgur.com/rMSZP.jpg)
And import it to `App.vue`.
[enter image description here](https://i.stack.imgur.com/2eaJ3.jpg)
The error message in VScode is property value expected.
I installed less, and variables are able to use in main.less.
There's others who encounter the same problem just add an import statement and solved, but it didn't work for me. |
We can solve this by enabling **notifications** of app on the **emulator's settings**.
- In your Emulator go to:
> Settings -> Notifications -> App Notifications
- Toggle the switch on. ( if you cannot find your app select "All Apps" on the drop downs).
- Go to Notification History in your Emulators Notification settings and toggle the switch on. |
null |
I am using the `pins` R package and the `board_gdrive()` function to create a hosted board on my Google Drive. My goal is to have a hosted shiny app that pulls pin data from the Google Drive board. However, it appears that Google Drive requires authentication verification each time. Is there a way to not require, or have the authentication stored with the board so that manual interaction is not required? Here is the code I have been using
```
# Google Drive board
board <- pins::board_gdrive(googledrive::as_id("https://drive.google.com/drive/folders/my-folder-abc123"))
```
|
Write R pin to Google Drive without authentication |
null |
null |
{"Voters":[{"Id":18519921,"DisplayName":"wohlstad"},{"Id":7733418,"DisplayName":"Yunnosch"},{"Id":3966456,"DisplayName":"Weijun Zhou"}]} |
|nginx|keycloak| |
I'm getting this error when trying to read an Env Variable from the .env file.
Things to know: my .env is in the root directory, the variable is prefixed by **VITE_**, and I'm trying to import it doing
```const apiKey = import.meta.env.VITE_YOUTUBE_API_KEY;```
I've scoured the web, but most of the answers were either *"use VITE prefix"* or *"use import.meta.env"*. I also tried using **loadEnv** like this https://vitejs.dev/config/#using-environment-variables-in-config, but I get "process is not defined" at ```const env = loadEnv(mode, process.cwd(), '')```.
Here's my .env (I've also tried removing the quotes from the variables, same thing):
```js
MONGODB_URI="mongodb+srv://USER:PASS@cluster0.f2tb4tn.mongodb.net/tutorialsApp?retryWrites=true&w=majority&appName=Cluster0"
JWT_SECRET="JWT_SECRET"
VITE_YOUTUBE_API_KEY="YOUTUBE_API_KEY"
VITE_CHANNEL_ID="CHANNEL_ID"
VITE_CLIENT_ID="CLIENT_ID"
```
Any help would be appreciated!
|
After going through the replies and reading the official documentation extensively, I found that the @annotation value requires the custom annotation's object rather than class.
Ref - https://docs.spring.io/spring-framework/docs/2.5.x/reference/aop.html#aop-ataspectj-around-advice (Heading 6.2.4)
so my Aspect class becomes ->
@Aspect
@Component
public class AuthAspect {
private static final Logger logger = LoggerFactory.getLogger(AuthAspect.class);
@Autowired
PtbUtils ptbUtils;
@Around("@annotation(validateUser)")
public Object authValidation(ProceedingJoinPoint joinPoint, ValidateUser validateUser) throws Throwable
{
logger.info("Inside authValidation class");
String headerName = validateUser.headerName().isEmpty() ? HttpHeaders.AUTHORIZATION : validateUser.headerName();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
logger.info("headerName = " + headerName);
logger.info("request = " + request);
String token = request.getHeader(headerName);
logger.info("token = " + token);
Boolean value = ptbUtils.validateJwtToken(token);
System.out.println("value = " + value);
return joinPoint.proceed();
}
} |
I am trying to use a code for a dji tello drone for face tracking, which I got from https://github.com/Shreyas-dotcom/DJITello_FaceTracking/blob/main/Code%3A%20V2. I had modified it for my needs and the drone flies, streams and everything expect it does not follow mw as I need it to do. Can anyone see why the code is not working for me?
This is the code:
import cv2
import numpy as np
from djitellopy import tello
import time
me = tello.Tello()
me.connect()
# Getting the drones battery
print(me.get_battery())
me.streamon()
me.takeoff()
me.send_rc_control(0, 0, 0, 0)
time.sleep(4.6)
w, h = 360, 240
fbRange = [6200, 6800]
pid = [0.4, 0.4, 0]
pError = 0
def findFace(img):
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(imgGray, 1.2, 8)
myFaceListC = []
myFaceListArea = []
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cx = x + w // 2
cy = y + h // 2
area = w * h
cv2.circle(img, (cx, cy), 5, (255, 0, 0), cv2.FILLED)
myFaceListC.append([cx, cy])
myFaceListArea.append(area)
command1 = x
command2 = y
command3 = w
command4 = h
if command1 > 0:
print("Drone Movement: Right")
else:
print("Drone Movement: Left")
if command2 > 0:
print("Drone Movement: Forward")
else:
print("Drone Movement: Backward")
if command3 > 0:
print(" Drone Movement: Up")
else:
print("Drone Movement: Down")
if command4 > 0:
print("Drone Movement: Yaw Right")
else:
print("Drone Movement: Yaw Left")
if len(myFaceListArea) != 0:
i = myFaceListArea.index(max(myFaceListArea))
return img, [myFaceListC[i], myFaceListArea[i]]
else:
return img, [[0, 0], 0]
def trackFace( info, w, pid, pError):
area = info[1]
x, y = info[0]
fb = 0
error = x - w // 2
speed = pid[0] * error + pid[1] * (error - pError)
speed = int(np.clip(speed, -100, 100))
if area > fbRange[0] and area < fbRange[1]:
fb = 0
elif area > fbRange[1]:
fb = -20
elif area < fbRange[0] and area != 0:
fb = 20
if x == 0:
speed = 0
error = 0
print(speed, fb)
me.send_rc_control(0, fb, 0, speed)
return error
cap = cv2.VideoCapture(1)
while True:
_, img = cap.read()
img = me.get_frame_read().frame
img = cv2.resize(img, (w, h))
img, info = findFace(img)
pError = trackFace( info, w, pid, pError)
#print(“Center”, info[0], “Area”, info[1])
cv2.imshow('person', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
me.land()
break
|
{"OriginalQuestionIds":[3029321],"Voters":[{"Id":5389997,"DisplayName":"Shadow","BindingReason":{"GoldTagBadge":"mysql"}}]} |
{"Voters":[{"Id":213269,"DisplayName":"Jonas"},{"Id":10008173,"DisplayName":"David Maze"},{"Id":1030169,"DisplayName":"jmoerdyk"}],"SiteSpecificCloseReasonIds":[18]} |
|sql|node.js|typeorm|planetscale| |
I have a Windows server running a MySQL server. There are two databases for different applications on the MySQL server.
In total, around 25 users access the database server every day.
The database server is not in the user's local network (sometimes not even in the same country).
Unfortunately, we often have problems with users not being able to connect to the server despite a stable internet connection. Only after several attempts does the user manage to connect.
When I look in the log files on the database server, I see a lot of entries like this:
**1. 2024-03-19 14:08:42 2378 \[Warning\] Aborted connection 2378 to db: 'CMS_DB' user: 'JOHN' host: 'bba-83-130-102-145.alshamil.net.ae' ( Got an error reading communication packets)**
**2. 2024-03-19 13:44:45 1803 \[Warning\] Aborted connection 1803 to db: 'CMS_DB' user: 'REMA' host: '188.137.160.92' (Got timeout reading communication packets)**
**3. 2024-03-19 11:51:08 1526 \[Warning\] Aborted connection 1526 to db: 'unconnected' user: 'unauthenticated' host: '92.216.164.102' (Got an error reading packet communications)**
**4. 2024-03-19 11:51:08 1526 \[Warning\] Aborted connection 1526 to db: 'unconnected' user: 'unauthenticated' host: '92.216.164.102' (This connection closed normally without authentication)**
**5. 2024-03-19 11:55:26 1545 \[Warning\] IP address '94.202.229.78' could not be resolved: No such host is known.**
My my.ini file looks like this:
```
[mysqld]
datadir = C:/Program Files/MariaDB 10.5/data
port = 3306
max_allowed_packet=1024M
net_read_timeout=3600
net_write_timeout=3600
# The maximum amount of concurrent sessions the MySQL server will
# allow. One of these connections will be reserved for a user with
# SUPER privileges to allow the administrator to login even if the
# connection limit has been reached.
max_connections = 600
wait_timeout = 3600
interactive_timeout = 3600
# The default character set that will be used when a new schema or table is
# created and no character set is defined
character-set-server = utf8
# Query cache is used to cache SELECT results and later return them
# without actual executing the same query once again. Having the query
# cache enabled may result in significant speed improvements, if your
# have a lot of identical queries and rarely changing tables. See the
# "Qcache_lowmem_prunes" status variable to check if the current value
# is high enough for your load.
# Note: In case your tables change very often or if your queries are
# textually different every time, the query cache may result in a
# slowdown instead of a performance improvement.
query_cache_size=50M
# Maximum size for internal (in-memory) temporary tables. If a table
# grows larger than this value, it is automatically converted to disk
# based table This limitation is for a single table. There can be many
# of them.
tmp_table_size=256M
slow_query_log = ON
slow_query_log_file = C:/Program Files/MariaDB 10.5/data/slow_query_log.log
general_log = ON
general_log_file = C:/Program Files/MariaDB 10.5/data/general_log.log
log_error = C:/Program Files/MariaDB 10.5/data/error_log.log
innodb_page_size = 65536
innodb_buffer_pool_size = 4085M
innodb_log_buffer_size = 32M
innodb_log_file_size = 2047M
[client]
port = 3306
plugin-dir = C:/Program Files/MariaDB 10.5/lib/plugin
```
My c3p0 settings in the hibernate.cfg.xml looks like this:
```
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_size">7</property>
<property name="hibernate.c3p0.timeout">120</property>
<property name="hibernate.c3p0.max_statements">20</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">20</property>
```
It was difficult for me to see through all the settings.
I want users to be able to connect to the database server easily without annoying me every time :D
What could be the problem? Do my settings match? Can someone who knows about this help me?
I am very grateful for any helpful answer, as I have been struggling with this for almost 5 weeks, but to no avail. Thanks in advance
If I should post any other settings like server variables, let me know.
Additional information
- OS Version --> Microsoft Windows Server 2022 Standard (version
10.0.20348)
- RAM --> 32 GB
- CPU --> Intel(R) Xeon(R) E-2314 CPU @ 2.80GHz 4 Cores
- Disk --> 1 TB SSD
Link of the my.ini file : https://jpst.it/3DRYr
I should also note that last night around 9:00 p.m. One user was no longer able to connect at all.
I simply restarted the Windows server and after that it worked. After the restart, no users complained about connection problems (yet). |
I created my token on BSC and I am currently trying to verify the code on BSCScan:
> SPDX-License-Identifier: MIT
> pragma solidity ^0.8.20;
>
> import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol";
>
> contract Token is ERC20 {
> constructor(uint256 initialSupply) ERC20 ("Token", "TKN"){
> _mint(msg.sender,initialSupply);
> }
> }
But, when I try to verify, this error pops out:
> Error! Unable to generate Contract Bytecode and ABI (General Exception, unable to get compiled [bytecode]) |
How Do I Solve This BSCScan Verification Error? |
|token|bscscan| |
null |
I am currently learning Laravel by watching [this course](https://www.youtube.com/watch?v=Wn3IPX_ax-0&list=WL&index=8&t=11429s&ab_channel=freeCodeCamp.org). I attempted to install Laravel 10 using the following command:
```
curl -s "https://laravel.build/example-app" | bash
```
However, this command installs Laravel 11 instead. I specifically need Laravel 10 because the dependency [laravel-nestedset](https://github.com/lazychaser/laravel-nestedset) does not support Laravel 11. How can I install Laravel 10? |
Docker Laravel 11 issue: How to switch Laravel versions |
I thank anyone who can give me a hand!
Basically, I have a WordPress site created with AWS Lightsail. So, I have an Apache server that exposes the WordPress site on my public address.
On a specific path, I would like to expose an application, for example, on the path TEST PUBLIC_ADDRESS/TEST, I would like to access the application.
The application is a React project available on localhost:3000 via a Next server. The application works correctly on localhost:3000, and as mentioned, I would like to first expose this application on PUBLIC_ADDRESS/TEST. How can I do it? I tried creating a virtual host first, then opening ports, etc. but to no avail.
**Thank you in advance.**
I tried creating a virtual host first, then opening ports, etc. but to no avail. |
Need Help: Integrating React App with AWS Lightsail WordPress Site |
|reactjs|next.js|amazon-lightsail| |
null |
In order for **Merge** to work you need to set a range of cells that you need merged.
In the code below, I've added a new **OLEVariant** variable named **MegredRange**. I'm using it to get the needed range of the start and end cells and then I merge them together.
```
var
ExcelObj, StartCell, EndCell, MergedRange: OLEVariant;
begin application
StartCell := ExcelObj.ActiveSheet.Cells[Row, ColQty];
EndCell := ExcelObj.ActiveSheet.Cells[Row, ColItemDescr];
MergedRange := ExcelObj.ActiveSheet.Range[StartCell, EndCell];
MergedRange.Merge();
MergedRange.Value := 'this is an item description';
MergedRange.HorizontalAlignment := xlCenter;
MergedRange.Font.Bold := true;
MergedRange.Interior.Color := clSkyBlue;
end;
``` |
I arrived here from a VERY different reason, but hope can help others (so don't downvote)
As per march 2024:
1) suppose You need to use an SPM for VisionPro, too
2) reading docs not support, but seems useful use:
.visionOS(.v10),
but You get:
Reference to member 'v10' cannot be resolved without a contextual type
3) seems the only way is (taken "furtively" from apple samples...)
platforms: [
.macOS(.v13),
.iOS(.v15),
.custom("xros", versionString: "1.0")
],
Hope can help others.
|
**Requirement**: Based on the code provided below, implement the merge sort algorithm to rearrange an array with N elements. While running the algorithm, print array A after each merge of two subarrays.
Input
- The first line is a positive integer N (0 \< N \< 20)
- The next line contains N integers Who are the elements of the array
Output
- The next lines print out the configuration of array A.
# Example:
Input
10
800 728 703 671 628 625 518 508 392 331
Output
\[ 728 800 \] 703 671 628 625 518 508 392 331
\[ 703 728 800 \] 671 628 625 518 508 392 331
703 728 800 \[ 628 671 \] 625 518 508 392 331
\[ 628 671 703 728 800 \] 625 518 508 392 331
628 671 703 728 800 \[ 518 625 \] 508 392 331
628 671 703 728 800 \[ 508 518 625 \] 392 331
628 671 703 728 800 508 518 625 \[ 331 392 \]
628 671 703 728 800 \[ 331 392 508 518 625 \]
\[ 331 392 508 518 625 628 671 703 728 800 \]
I'm having trouble finding a way to print out the remaining elements of the array after each merge.
this is my code, hope any one can help me:
```
#include <iostream>
using namespace std;
void printArray(int arr[], int start, int end) {
cout << "[ ";
for (int i = start; i <= end; ++i) {
cout << arr[i];
if (i < end) {
cout << " ";
}
}
cout << " ] ";
}
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int* L = new int[n1];
int* R = new int[n2];
for (int i = 0; i < n1; ++i)
L[i] = arr[left + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
++i;
} else {
arr[k] = R[j];
++j;
}
++k;
}
while (i < n1) {
arr[k] = L[i];
++i;
++k;
}
while (j < n2) {
arr[k] = R[j];
++j;
++k;
}
// In ra mảng sau mỗi lần trộn hai mảng con
printArray(arr, left, right);
cout << endl;
delete[] L;
delete[] R;
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
int N;
cin >> N;
int* arr = new int[N];
for (int i = 0; i < N; ++i)
cin >> arr[i];
mergeSort(arr, 0, N - 1);
delete[] arr;
return 0;
}
```
After running my code, this is the output of example :
[ 728 800 ]
[ 703 728 800 ]
[ 628 671 ]
[ 628 671 703 728 800 ]
[ 518 625 ]
[ 508 518 625 ]
[ 331 392 ]
[ 331 392 508 518 625 ]
[ 331 392 508 518 625 628 671 703 728 800 ]
As you can see, this is not contain the entire array but only print the elements already be merged, i want it look like the output example. |
As a normal user, how would I know how many arguments and what arguments I need to pass in a command line arguments program? |
|python|arguments|command|line| |
null |
From [\[bit.cast\]/2](https://timsong-cpp.github.io/cppwp/n4950/bit.cast#2):
> [...] A bit in the value representation of the result is indeterminate if it does not correspond to a bit in the value representation of _from_ [...].
For each bit in the value representation of the result that is indeterminate, the smallest object containing that bit has an indeterminate value; the behavior is undefined unless that object is of unsigned ordinary character type or std::byte type. [...]
So, in your case, the behavior is undefined, but not because of the `std::bit_cast` itself.
Because the bits of `b` do not correspond to any bit of the value representation of `A{}`, they are indeterminate and the value of `b` itself is consequently indeterminate. Only because `b` has type `unsigned char`, this is not immediately undefined behavior.
However, for the comparison with `0 ==`, you then read the value of `b`, which causes undefined behavior because its value is indeterminate.
Of course, because you are using the comparison as the condition in a `static_cast`, the program will be ill-formed, not have undefined behavior. The compiler needs to diagnose this. |
You should include this file into assets to make it being copied to __/dist__ folder at the build time. Look into __angular.json__ at the root of your project, by the path:
projects -> <app_name> -> architect -> build -> options -> assets |
SCons does support generating the PDB files, however you must enable it by setting env['PDB']
`env['PDB'] = "${TARGET.base}.pdb"`
Should likely do the job (I've not tried this)
From the SCons manpage:
> The Microsoft Visual C++ PDB file that will store debugging
> information for object files, shared libraries, and programs. This
> variable is ignored by tools other than Microsoft Visual C++. When
> this variable is defined SCons will add options to the compiler and
> linker command line to cause them to generate external debugging
> information, and will also set up the dependencies for the PDB file.
> Example:
>
> env['PDB'] = 'hello.pdb' The Microsoft Visual C++ compiler switch that
> SCons uses by default to generate PDB information is /Z7. This works
> correctly with parallel (-j) builds because it embeds the debug
> information in the intermediate object files, as opposed to sharing a
> single PDB file between multiple object files. This is also the only
> way to get debug information embedded into a static library. Using the
> /Zi instead may yield improved link-time performance, although
> parallel builds will no longer work. You can generate PDB files with
> the /Zi switch by overriding the default $CCPDBFLAGS variable; see the
> entry for that variable for specific examples.
See:
* https://scons.org/doc/production/HTML/scons-man.html#cv-PDB
* https://scons.org/doc/production/HTML/scons-man.html#cv-CCPDBFLAGS
|
I make a site using reactjs, I want it to be more Google search friendly. So I optimize the download speed, lcp.....
But I'm having a problem with Total Blocking Time & Largest Contentful Paint. Anyone with experience, please guide me on how to optimize LCP when downloading data from the api.
This is my site: [https://coolxgame.com](https://coolxgame.com).
I using preload image, but it not reduce Total Blocking Time & Largest Contentful Paint.
|
I'm making an Aqua button (from Mac OS X) and one of the many things I must fix is the button pulse, which seems to be very hard to find one to implement that actually (kinda) works
However, I found a (quarter-working) fix that "technically" pulses, but that doesn't fix the new problem of making the entire background pulse instead of the background size. It moves the color of choice (specifically the `background`) of the `@keyframe` up and down. So I want the entire background of the button to pulse instead of `background-size`. [The background keyframe for clarity here (focus on the top one).][1]
Here's the CSS code:
```css
@keyframes color {
from {
background-size:50% 50%;
}
to {
background-size:100% 100%;
}
}
:root {
--confirm: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207));
--cancel: linear-gradient(#AAAAAA,#FFFFFF);
--altconfirm: linear-gradient(rgb(0, 100, 240),rgb(200, 200, 210))
}
button {
-webkit-appearance: none;
-moz-appearance: none;
border: 1px solid #ccc;
border-radius: 125px;
box-shadow: inset 0 13px 25px rgba(255,255,255,0.5), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.1);
cursor: pointer;
font-family: 'Lucida Sans Unicode', Helvetica, Arial, sans-serif;
font-size: 1.5rem;
margin: 1rem 1rem;
padding: .8rem 2rem;
position: relative;
transition: all ease .3s;
}
button:hover {
box-shadow: inset 0 13px 25px rgba(255,255,255,.7), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.2);
transform: scale(1.001);
}
button::before {
background: linear-gradient(rgba(255,255,255,.8) 7%, rgba(255,255,255,0) 50%);
border-radius: 125px;
content:'';
height: 97.5%;
left: 5%;
position: absolute;
top: 1px;
transition: all ease .3s;
width: 90%;
}
button:active{
box-shadow: inset 0 13px 25px rgba(255, 255, 255, 0.2), 0 3px 5px rgba(0,0,0,0.2), 0 10px 13px rgba(0,0,0,0.2);
transform: scale(1);
}
button::before:active{
box-shadow: inset 0 13px 25px rgba(255, 255, 255, 0.01), 0 3px 5px rgba(0,0,0,0.418), 0 10px 13px rgba(0, 0, 0, 0.418);
transform: scale(1);
}
button.confirm {
background: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207));
animation-name: color;
animation-duration: 2s;
animation-iteration-count: infinite;
animation-direction: alternate-reverse;
animation-timing-function: ease;
}
button.cancel {
background: var(--cancel);
border: 1.7px solid #AAA;
color: #000;
}
```
And the HTML code:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./Test.css">
</head>
<body>
<button class="confirm" style="background-color: linear-gradient(rgb(0, 36, 197),rgb(196, 201, 207))">Push Button</button><br>
<button class="cancel">Push Button</button><br>
<p>EEE</p>
</body>
</html>
```
[1]: https://i.stack.imgur.com/k3RJZ.gif |
I don't think JavaScript works like that. A JavaScript script doesn't work when you place it in some kind of object (div in this case). Instead it is always supposed to be put at the end of the HTML page (before the body ending tag usually) and it works accordingly what you have written inside it.
Here you are considering JavaScript as a HTML object (just live divs, paragraphs, header tags etc.) but it isn't like that.
|
I am running into an issue where I have tested my Apple Watch app on many simulators in Xcode and on my personal devices, but When I submitted to apple for review they are telling me that it will not run and to check my plist folder. I cannot find my Plist folder as I accidentally removed it, which led me to the settings possibly being the issue. The app is set to be run only on the watch without a companion app. inserting pictures of my settings.[[enter image description here](https://i.stack.imgur.com/Pwlfr.png)](https://i.stack.imgur.com/5dR6j.png)[enter image description here](https://i.stack.imgur.com/Ckk1u.png)
I have tried adjusting the settings to only have the watch shown in supported devices as well as just IOS and that gave me an error saying that I could not build for a simulator for a watch only app |
Issue with Xcode Target and settings for Apple Watch App |
|ios|swift|xcode|settings|apple-watch| |
null |
Statement 1 counts all the equal courses. E.g. for student A having a `'Math'` course, it counts all the `'Math'` courses because of the condition in the sub-select `c.class = Courses.class`, where `Courses` denotes the current record of the parent select.
Statement 2 counts all the courses because there is no condition. Worse, since you have two un-joined tales in the FROM clause (`FROM Courses AS c, Courses`), this will create a [Cartesian product][1], i.e.,
it will create all possible pairings of all the records in the two tables. Because the tables have 9 records, `count(*)` will always yield 9 * 9 = 81. It doesn't matter that the "two" tables are the same physical table.
But there is a better way to do this (at least when you don't need to return the `student` column):
``` sql
SELECT class
FROM Courses
GROUP BY class
HAVING count(*) >= 5;
```
It will return at most one record per class type instead of one per student. Note that the HAVING clause acts on the grouped result. A WHERE clause would have to be placed before the GROUP BY.
[1]: https://stackoverflow.com/q/30955338/880990 |
{"OriginalQuestionIds":[218384],"Voters":[{"Id":522444,"DisplayName":"Hovercraft Full Of Eels","BindingReason":{"GoldTagBadge":"java"}}]} |
> How am I supposed to do this?
To some extent, the answer is: hope the user does not uninstall and reinstall the app. If you are anticipating that this will happen a lot, that seems like a problem to try to solve.
The `Uri` values are useless except for this app installation. Once the app is uninstalled, any permissions associated with those `Uri` values go "poof".
Storing such `Uri` values is fine for a "link" sort of operation, where you are in position to deal with broken links for any reason. For example, the user could delete the image; my assumption is that your app will similarly break for that scenario, if you try to use a `Uri` that points to the now-deleted image. Once you figure out what sort of UX you want to have for this scenario, you can decide if it could be extended for the uninstall/reinstall scenario.
If you determine that you cannot cope with the deleted-image case, then you have more of an "import" operation, where you need to make your own copy of the content and work with that copy that you control. And, if you want to extend that approach to handle uninstall/reinstall, you will need to "make copies of the images and ship them to my BE".
> only to download them every time I want to show them
So, cache them:
- When the user imports an image into your app, copy it to your cache and arrange to upload it to your BE
- If you have a reference to an image that is not cached locally (uninstall/reinstall, cache eviction policy, "clear data" in Settings, etc.), download it from the BE into the cache
In the ideal case, the user *never* downloads the image, as they just use the cached copy.
|
Not having `ninja.build` present is a symptom of ninja not being built, which could be caused by several things. For me this happened after I ran the commands:
```
git clone https://github.com/microsoft/vcpkg
cd vcpkg
.\bootstrap-vcpkg.bat
.\vcpkg install openblas:x64-windows
```
```
Computing installation plan...
A suitable version of cmake was not found (required v3.29.0) Downloading portable cmake 3.29.0...
Downloading cmake...
https://github.com/Kitware/CMake/releases/download/v3.29.0/cmake-3.29.0-windows-i386.zip->C:\Users\Michael Currie\Desktop\GitHub\vcpkg\downloads\cmake-3.29.0-windows-i386.zip
Downloading https://github.com/Kitware/CMake/releases/download/v3.29.0/cmake-3.29.0-windows-i386.zip
Extracting cmake..
```
**Problem 1**: It's downloading an i386 version of cmake! But my computer is 64-bit!
```
PS C:\Users\Michael Currie> wmic os get osarchitecture
OSArchitecture
64-bit
```
Oh, `vcpkg`, you sweet summer child, please check the architecture of the computer before downloading `cmake` - you grabbed the wrong version!!
**Problem 2**: the version of cmake I had in my path was 3.26, which was still being used even after the above attempt at installing 3.29. So to fix these two issues:
- I uninstalled my old `cmake` 3.26, and
- manually installed the correct one at https://cmake.org/download/: https://github.com/Kitware/CMake/releases/download/v3.29.0/cmake-3.29.0-windows-x86_64.zip
**Problem 3**: I needed to run the above commands in a PowerShell 7.0 or above. So I needed to:
- install Powershell from https://github.com/PowerShell/PowerShell/releases/download/v7.2.16/PowerShell-7.2.16-win-x64.msi and then
- manually run it from Start -> Run -> Powershell 7
- Check your version has Major >= 7 via the command `$PSVersionTable.PSVersion`
- (note that you CANNOT uninstall Powershell 1.0 at C:\Windows\System32\WindowsPowerShell\v1.0 (it's not in Add or Remove Programs!), see https://superuser.com/questions/1503460/how-to-reinstall-powershell-on-windows-10)
**Problem 4** The problem still persisted, but according to https://github.com/microsoft/vcpkg/issues/29702 I need to install Visual Studio Desktop development with C++ and also Windows 10 SDK. So I did this.
After fixing the 4 problems above, I completely deleted the vcpkg folder from my computer, then ran the first commands listed above, and building openblas worked! Yay. |
{"Voters":[{"Id":354577,"DisplayName":"Chris"},{"Id":10867454,"DisplayName":"A Haworth"},{"Id":466862,"DisplayName":"Mark Rotteveel"}]} |
I'm currently working on an app(basically a todo list), it has to push a notification at a specific time of how many tasks are remaining. But its not pushing any notification. I'm new to android.
here is the MainActivity
```
package dev.amanraj.ListUp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import dev.amanraj.ListUp.Adapter.ToDoAdapter;
import dev.amanraj.ListUp.Model.ToDoModel;
import dev.amanraj.ListUp.Utils.DatabaseHandler;
public class MainActivity extends AppCompatActivity implements DialogCloseListener{
private RecyclerView tasksRecyclerView;
private ToDoAdapter tasksAdapter;
private FloatingActionButton fab;
private List<ToDoModel> taskList;
private DatabaseHandler db;
private ProgressBar progressBar;
private TextView progressText;
private ImageView hint_tap, hint_right, hint_left;
private static final String TAG = "Alarm";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hint_tap = findViewById(R.id.tap_hint);
hint_left = findViewById(R.id.left_hint);
hint_right = findViewById(R.id.right_hint);
hint_tap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hint_tap.setVisibility(View.GONE);
hint_right.setVisibility(View.VISIBLE);
}
});
hint_right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hint_right.setVisibility(View.GONE);
hint_left.setVisibility(View.VISIBLE);
}
});
hint_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hint_left.setVisibility(View.GONE);
}
});
// getSupportActionBar().hide();
db = new DatabaseHandler(this);
db.openDatabase();
// taskList = new ArrayList<>();
tasksRecyclerView = findViewById(R.id.tasksRecyclerView);
tasksRecyclerView.setLayoutManager(new LinearLayoutManager(this));
tasksAdapter = new ToDoAdapter(db,MainActivity.this);
tasksRecyclerView.setAdapter(tasksAdapter);
fab=findViewById(R.id.fab);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new RecyclerItemTouchHelper(tasksAdapter));
itemTouchHelper.attachToRecyclerView(tasksRecyclerView);
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
progressBar = findViewById(R.id.progressBar);
progressText = findViewById(R.id.progressText);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AddNewTask.newInstance().show(getSupportFragmentManager(),AddNewTask.TAG);
}
});
updateProgress();
setAlarm();
}
//update progress method
private void updateProgress(){
int totalTasks = taskList.size();
int completedTasks = 0;
for (ToDoModel task : taskList){
if (task.getStatus() == 1){
completedTasks++;
}
}
if (totalTasks > 0){
int progress = (completedTasks*100)/totalTasks;
progressBar.setProgress(progress);
progressText.setText(progress + "%");
}
}
@Override
public void handleDialogClose(DialogInterface dialog){
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
tasksAdapter.notifyDataSetChanged();
//updating progress when task changes
updateProgress();
}
@Override
public void onTaskStatusChanged(){
updateProgress();
}
private void setAlarm(){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_IMMUTABLE);
//setting the alarm to start at 8pm
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,12);
calendar.set(Calendar.MINUTE,56);
Log.d(TAG,"Alarm set");
//scheduling the alarm to repeat daily
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
}
```
and here is the AlarmReceiver that I've made
```
package dev.amanraj.ListUp;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import java.util.List;
import dev.amanraj.ListUp.Model.ToDoModel;
import dev.amanraj.ListUp.Utils.DatabaseHandler;
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = "AlarmReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"Alarm received");
//getting the remaining tasks
DatabaseHandler db = new DatabaseHandler(context);
db.openDatabase();
List<ToDoModel> tasks = db.getAllTasks();
int remainingTasks = 0;
for (ToDoModel task : tasks){
if (task.getStatus() == 0){
//assuming 0 represents unchecked tasks
remainingTasks++;
}
}
db.close();
//sending Notification
sendNotification(context ,remainingTasks);
}
private void sendNotification(Context context, int remainingTasks){
Log.d(TAG,"Sending notification");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//creating a notification channel if the device is running Android 8 or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
Log.d(TAG,"creating notification channel");
NotificationChannel channel = new NotificationChannel("task_notification_channel", "Task Notification Channel", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
//creating the notification
Notification.Builder builder = new Notification.Builder(context,"task_notification_channel")
.setContentTitle("Remaining tasks")
.setContentText("You have " + remainingTasks + " tasks remaining.")
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true);
//showing the notification
notificationManager.notify(1,builder.build());
}
}
```
I've added multiple logs in both the code, The Log in MainActivity does appear in the logcat, but logs from AlarmReceiver doen't shows up.
need help |
I'm working on an app, the app has to push a notification at a specific time but its not working |
|java|android| |
null |
I had the same problem developing a new extension for manifest v3.
Like has been said, a cors error can be linked to a missing `host_permissions` entry.
But it can also been related to the global site setting of your extension.
If the extension is not configured to work on all sites, you have to add the url of the api in the `matches` entry of the `content_scripts`
This is not logical at all, since it is supposed to set the permission for the content scripts, but it is also setting the permission to use the whole extension on other sites.
|
This seems to work on jQXWidgets v19.
The values of `const ex`, `const ex1` are different.
This is probably a bug in the jqxWidgets library (v12) that I was using.
I think the bug is related to:-
https://www.jqwidgets.com/community/topic/filtering-issues-when-mixing-addfilter-and-filter-row/
|
How can I insert a regularization parameter in `tidymodels` for `boost_tree()`? In the normal `lightgbm` package there is the tuning parameter `lambda_l1`. I would like to use this in `tidymodels` as well.
I tried to code it like this, but I am unsure if I am doing right:
```
lgbm_model <-
boost_tree(
mode = "regression",
# mtry = 1,
trees = tune(),
min_n = tune(),
tree_depth = tune(),
learn_rate = tune(),
loss_reduction = tune()
) %>%
set_engine("lightgbm", lambda = 1)
```
|
Why are landscape pages causing issues with page numbers/section headers/footers in officeverse? |
I would like to be able to debug an application through VSCode via SSH. So far I have create the debug configuration in VSCode and I have created a SSH tunnel on the correct port.
So far, this works fine. I can connect to the remote application using `node inspect <host>:<port>` and I can attach via VSCode. I have veryfied both using the `Dabugger attached.` log line in the remote application.
However, things start to break when I actually use the VSCode debugger. I.e. if a breakpoint should be triggered, I get an error instead. This is because the application tries to require a module that is anly available on my local machine and not the remote one:
[![enter image description here][1]][1]
My guess is that this is because VSCode does not even know that it is being tunnled to a different machine and still assumes that it is on my local machine. Are there any ways to solve this?
By the way, this is my launch configuration:
```json
{
"name": "Debug Docker",
"type": "node",
"request": "attach",
"address": "localhost",
"restart": true,
"port": 9228,
"localRoot": "${workspaceFolder}/dist",
"remoteRoot": "/app/dist",
"presentation": {
"order": 1
},
"skipFiles": ["<node_internals>/**/*.js"]
}
```
And this is the SSH Tunnel command:
```bash
ssh -nNT -L 9228:localhost:9229 remote-system.example.org
```
[1]: https://i.stack.imgur.com/6PDl5.png |
Remote debugging via SSH Tunnel |
|visual-studio-code|ssh| |
I am a beginner in testing. I have some problems. I develop the APIs according on three layer:
this is repo [enter image description here](https://i.stack.imgur.com/PwvA2.png) [enter image description here](https://i.stack.imgur.com/9Vk8U.png) this is a function in a service : [enter image description here](https://i.stack.imgur.com/4BnLm.png) An I write test [enter image description here](https://i.stack.imgur.com/BkYfU.png) It causes [enter image description here](https://i.stack.imgur.com/VQc54.png) please help me. thank you for reading
The ways to resolve this problem |
The problem related to unit test CSharp , Moq |
Optimize LCP ReactJs |
|reactjs|optimization| |
null |
How to dismiss the first scene in UIKit Application? |
|ios|swift|uikit| |
null |
I am developing an iOS application with Swift in Xcode (14.5) environment.
There are two different scenes named ViewController.swift and XYZViewController.swift in the Main (Base) storyboard.
First of all, the ViewController.swift file runs on the screen. Because a SpeechScreen screen appears here. Then, redirection is made to the XYZViewController.swift file.
The problem starts here. Yes, redirection to XYZViewController.swift occurs. However, the ViewController.swift file still runs in the background. So, onboardingLottieView, the animation still runs in the background.
After redirecting to the XYZViewController.swift file, I want to close the ViewController.swift scene. But the code below does not work correctly. The animation still works in the background.
I took a look at the iOS [documentation][1]
I also reviewed [this page][2].
Actually, it is a problem like the one on this page. Here it closes the Second View Controller. I am trying to close the First view controller.
I tried navigate XYZViewController from the navigation controller. But I couldn't achieve this either.
I'm not a professional in iOS development. I'm learning some new things. I would be glad if you help.
ViewController.swift file as follows:
```swift
import UIKit
import Lottie
class ViewController: UIViewController {
@IBOutlet weak var onboardingLottieView: LottieAnimationView!
//...
override func viewDidLoad() {
super.viewDidLoad()
self.showSpeechScreen()
}
func showSpeechScreen() {
// onboardingLottieView...
onboardingLottieView.play()
Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(presentNextViewController), userInfo: nil, repeats: false)
}
@objc func presentNextViewController() {
// Dismiss the current view controller
self.dismiss(animated: true) {
// Redirect to XYZViewController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let vc = storyboard.instantiateViewController(withIdentifier: "XYZViewController") as? XYZViewController {
vc.modalPresentationStyle = .automatic
vc.modalTransitionStyle = .crossDissolve
self.present(vc, animated: true)
}
}
}
}
```
[1]: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621505-dismiss
[2]: https://www.tutorialspoint.com/how-to-dismiss-viewcontroller-in-swift |
the whole observation capability around spring boot 3 is a bit of confusing.
We have pure spring framework capabilities, micrometer ones and spring boot 3 on top to auto-configure stuff for us.
Considering a standard @RestController application with prometheus dependency added for example, by doing absolutely nothing about observation, we already have metrics for:
- http.server.requests // incoming http requests
- http.client.requests // outgoing http requests (for RestTemplate, RestClient, etc.)
- spring.data.repository.invocations
- mongodb.driver.commands / pool
- tasks.scheduled.execution
According to docu, by overriding the corresponding default convention, we can add custom tags in runtime:
@Component
public class ServerRequestMetricsCustomizer
extends DefaultServerRequestObservationConvention { ... }
Though, this works only for the **http.server** and **client requests**, because they rely on a `@Bean` to inject their default convention, but the others (**mongodb.driver** and **scheduled**) metrics are instantiating their default convention straight away with `new` in `MongoObservationCommandListener` resp. in `ScheduledMethodRunnable` and for the **mongodb.driver.commands** metric I dont even see a default convention, which I could override to add custom tags.
Do you know the way how to add custom tags also to the other ones?
And second general question: instead of overriding these conventions, can I not inject in my production code the observation registry and somehow access the right context and add my tags? I tried it within the rest controller method, but there it does not access the **http.server.requests** context, rather some **spring.security.http.secured.requests** one
**UPDATE**:
found a way to configure the **spring.data.repository.invocations**, the **mongodb.driver.commands/pool** and the **scheduled** ones:
@Component
public class SpringDataRepositoryMetricsCustomizer
extends DefaultRepositoryTagsProvider { ... }
resp.
@Component
public class MongoDBCommandMetricsCustomizer
extends DefaultMongoCommandTagsProvider { ... }
@Component
public class MongoDBConnectionPoolMetricsCustomizer
extends DefaultMongoConnectionPoolTagsProvider { ... }
resp.
@Component
public class ScheduledTaskMetricsCustomizer
implements GlobalObservationConvention<ScheduledTaskObservationContext>
{ ... }
But now I am wondering, how can I access the data that these observations are wrapping. For example the object that is fetched by the repository methods or the one that is saved, etc. or there is no way?
Btw. the general question is still valid, cause if I could add the custom tags inside my business code, I could have an easy access to my business data and produce the custom tags without relying on access via the context objects or mongodb events
**UPDATE2**:
For the **http.server.requests** metrics I could re-use the http servlet request (which is the context carrier) attributes
For the **http.client.requests** metrics I could inject the http servlet request (since the context carrier is not anymore the http servlet request) and do the above, but I also could use the context to reach out to the parentObservation and read out from its map, which could be filled before hand
For the other metrics (**mongodb driver** and **repository**) I could do same as above, inject http servlet request and/or ObservationRegistry and read out from their attributes resp. map, which should be filled before hand.
The **tasks scheduled** metric seems to not be able to use above concept as http servlet requests is not applicable and observation registry injection here causes spring startup to report a cycle from the **WebMvcObservationAutoConfiguration**, so here it appears I have to rely on the **ScheduledTaskObservationContext** map, which should be filled before hand in the `@Scheduled` method by injecting there the observation registry and filling the current observation's context's map
After all, all appears working, but I am not sure how fragile this might be and whether there is no general consistent way.
Maybe the consistency comes from:
- first try to use the context's map resp. context's parent observation's map (if provided), by making sure before hand it is filled
- if not, try to workaround via injecting the observation registry to reach out to the map, which again has to be pre-filled beforehand
- if not, try to workaround via injecting the http servlet request to reach out to the attributes, by making sure they were pre-filled beforehand
**UPDATE3**:
[Here is a description of how I solved it so far, hitting a limit in the micrometer framework, but still doable in an encapsulated way][1].
Btw. why is it so different to customize the tags for the different metrics:
- extending `DefaultServerRequestObservationConvention` // works like a charm
- extending `DefaultClientRequestObservationConvention` // works like a charm
- extending `DefaultRepositoryTagsProvider` // works like a charm though differs from first two ones
- extending `DefaultMongoCommandTagsProvider` // works like a charm though differs from first two ones
- implementing `GlobalObservationConvention<ScheduledTaskObservationContext>` // work only after manually adding it as part of a custom bean configuration of the `ObservationRegistryCustomizer<ObservationRegistry>`...observationRegistry.observationConfig().observationConvention(...)
[1]: https://github.com/micrometer-metrics/micrometer/issues/4879 |
Adding `ASSET_URL` (with https) fixed the issue. It wasn't set at all in `.env` and Vite decided to pull through `http://`.
|
I have CSV files for 167 patients, they have the same number and type of columns but the number of rows in each CSV file varies. I want to train a CNN or LSTM but without combining all the CSVs. I want to train the model using each file separately because it's important for me to distinguish between each patient, so I don't combine all the files. Each file has a target column which is the values of a signal that I need to predict. It's a regression problem. Each file has about 50 columns, meaning 50 features. Could you help me? I don't know how to do this in python.
I combined all the files and trained my model with 80% of the data, but then I realized that it's incorrect to combine the data from all the patients. Each patient has a unique behavior in their characteristics. |
Check your htaccess files in moodle data folder. It might overwritten by a malware program. Further, some external scripts might insert into all index.php filesin each folder in lms folder in your server. |
I'm currently working on an app(basically a todo list), it has to push a notification at a specific time of how many tasks are remaining. But its not pushing any notification. I'm new to android.
here is the MainActivity
```
package dev.amanraj.ListUp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import dev.amanraj.ListUp.Adapter.ToDoAdapter;
import dev.amanraj.ListUp.Model.ToDoModel;
import dev.amanraj.ListUp.Utils.DatabaseHandler;
public class MainActivity extends AppCompatActivity implements DialogCloseListener{
private RecyclerView tasksRecyclerView;
private ToDoAdapter tasksAdapter;
private FloatingActionButton fab;
private List<ToDoModel> taskList;
private DatabaseHandler db;
private ProgressBar progressBar;
private TextView progressText;
private ImageView hint_tap, hint_right, hint_left;
private static final String TAG = "Alarm";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hint_tap = findViewById(R.id.tap_hint);
hint_left = findViewById(R.id.left_hint);
hint_right = findViewById(R.id.right_hint);
hint_tap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hint_tap.setVisibility(View.GONE);
hint_right.setVisibility(View.VISIBLE);
}
});
hint_right.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hint_right.setVisibility(View.GONE);
hint_left.setVisibility(View.VISIBLE);
}
});
hint_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
hint_left.setVisibility(View.GONE);
}
});
// getSupportActionBar().hide();
db = new DatabaseHandler(this);
db.openDatabase();
// taskList = new ArrayList<>();
tasksRecyclerView = findViewById(R.id.tasksRecyclerView);
tasksRecyclerView.setLayoutManager(new LinearLayoutManager(this));
tasksAdapter = new ToDoAdapter(db,MainActivity.this);
tasksRecyclerView.setAdapter(tasksAdapter);
fab=findViewById(R.id.fab);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new RecyclerItemTouchHelper(tasksAdapter));
itemTouchHelper.attachToRecyclerView(tasksRecyclerView);
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
progressBar = findViewById(R.id.progressBar);
progressText = findViewById(R.id.progressText);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AddNewTask.newInstance().show(getSupportFragmentManager(),AddNewTask.TAG);
}
});
updateProgress();
setAlarm();
}
//update progress method
private void updateProgress(){
int totalTasks = taskList.size();
int completedTasks = 0;
for (ToDoModel task : taskList){
if (task.getStatus() == 1){
completedTasks++;
}
}
if (totalTasks > 0){
int progress = (completedTasks*100)/totalTasks;
progressBar.setProgress(progress);
progressText.setText(progress + "%");
}
}
@Override
public void handleDialogClose(DialogInterface dialog){
taskList = db.getAllTasks();
Collections.reverse(taskList);
tasksAdapter.setTasks(taskList);
tasksAdapter.notifyDataSetChanged();
//updating progress when task changes
updateProgress();
}
@Override
public void onTaskStatusChanged(){
updateProgress();
}
private void setAlarm(){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_IMMUTABLE);
//setting the alarm to start at 8pm
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,20);
calendar.set(Calendar.MINUTE,00);
Log.d(TAG,"Alarm set");
//scheduling the alarm to repeat daily
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
}
}
```
and here is the AlarmReceiver that I've made
```
package dev.amanraj.ListUp;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import java.util.List;
import dev.amanraj.ListUp.Model.ToDoModel;
import dev.amanraj.ListUp.Utils.DatabaseHandler;
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = "AlarmReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"Alarm received");
//getting the remaining tasks
DatabaseHandler db = new DatabaseHandler(context);
db.openDatabase();
List<ToDoModel> tasks = db.getAllTasks();
int remainingTasks = 0;
for (ToDoModel task : tasks){
if (task.getStatus() == 0){
//assuming 0 represents unchecked tasks
remainingTasks++;
}
}
db.close();
//sending Notification
sendNotification(context ,remainingTasks);
}
private void sendNotification(Context context, int remainingTasks){
Log.d(TAG,"Sending notification");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//creating a notification channel if the device is running Android 8 or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
Log.d(TAG,"creating notification channel");
NotificationChannel channel = new NotificationChannel("task_notification_channel", "Task Notification Channel", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
//creating the notification
Notification.Builder builder = new Notification.Builder(context,"task_notification_channel")
.setContentTitle("Remaining tasks")
.setContentText("You have " + remainingTasks + " tasks remaining.")
.setSmallIcon(R.drawable.icon)
.setAutoCancel(true);
//showing the notification
notificationManager.notify(1,builder.build());
}
}
```
I've added multiple logs in both the code, The Log in MainActivity does appear in the logcat, but logs from AlarmReceiver doen't shows up.
need help |
I am quite new to stripe integration, and due to the country I am from, I cannot access the checkout session page due to account activation requirements.
So, I am not able to see what all details are visible in the checkout page, and cannot debug it. (I am in test mode)
I am quite confused about how I can sent the price id of the product I select.
I have created two products in my dashboard, and I am displaying then on the frontend with a pay button that calls the ```checkout-session``` endpoint.
this is my checkoutSession view
```
class CreateCheckoutSession(APIView):
def post(self, request):
if request.method == 'POST':
try:
if request.user.is_authenticated:
print(request.user)
print(request.user.id)
checkout_session = stripe.checkout.Session.create(
client_reference_id=request.user.id,
payment_method_types=['card'],
line_items=[
{
'price': "",
'quantity': 1,
},
],
mode='subscription',
success_url=os.environ['DOMAIN_URL']+'/dashboard',
cancel_url=os.environ['DOMAIN_URL'],
)
return Response({'sessionId': checkout_session.id})
else:
return Response({'message': 'You need to register first.'}, status=403)
except InvalidRequestError as e:
error_message = str(e)
return Response({'error': error_message}, status=400)
else:
return Response({'error': 'Method not allowed'}, status=405)
```
I think I should only send the price id or product id (which one am I supposed to send?) of the subscription I want to buy. I am not sure how can I do that. Could anyone please help me here?
My frontend is NEXTJS and backend is django with DRF
```
const handleSubscription = async () => {
try {
const response = await AxiosInstance.post("/checkout-session", {
});
const sessionId = response.data.sessionId;
const stripe = await loadStripe(
process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY
);
const { error } = await stripe.redirectToCheckout({
sessionId: sessionId,
});
if (error) {
console.error("Error:", error);
}
```
When calling the product api, it gives me two arrays, one for each product.
I need your help to understand, what are the parameters that I need to send of the product I subscribe to?
and how can I sent it?
I tried implementing the stripe code implementation using stripe elements, and now switching to stripe low code, as it best suits my current use case.
I cannot check if my payment is going through successfully, as I cannot make any payment from my country before account activation due to stripe policies.
|
How to send Stripe session checkout parameters in subscription mode |
Vite TypeError: Cannot read properties of undefined (reading 'VITE_YOUTUBE_API_KEY') |
|javascript|reactjs|environment-variables|backend|vite| |
[![Graph of smoothed and unsmoothed data example][1]][1]```
def smooth_data_mp(data_frame, n): # dataframe is the data and n is number of data points to look at
num_processes = os.cpu_count() + 2
chunk_size = len(data_frame.index) // num_processes
print(chunk_size)
end_chunk = len(data_frame) // chunk_size - 1 # have to subtract 1 cuz indexing by 0 this line took an hour to debug holy shite
with Pool(processes=num_processes) as pool:
results = pool.starmap(process_data, [(data_frame, i, chunk_size, n, end_chunk) for i in
range(len(data_frame) // chunk_size)])
return pd.concat(results)
```
```
def process_data(dataframe, i, chunk_size, n, end_chunk):
fraction = n / chunk_size # n is number of data points to look at in the smoothing func
if i == 0:
start_frame = 0
else:
start_frame = chunk_size * i - n
if i == end_chunk:
end_frame = len(dataframe) # Ensure end_frame doesn't exceed length of sampleData
else:
end_frame = chunk_size * (i + 1) + n
new_data_frame = calculate_loess_on_subset(dataframe[start_frame:end_frame], fraction, i, n, end_chunk)
start_index = chunk_size * i
if i == end_chunk:
end_index = len(dataframe)
else:
end_index = chunk_size * (i + 1)
new_data_frame.index = pd.RangeIndex(start_index, end_index)
return new_data_frame
```
How can I chop up the data as I want to inside the process_data function prior to sending it to each process? I'm running into scaling issues with more processes and larger dataframes due to the memory overhead.
The reason I'm padding the data is because I'm running a smoothing function and if I dont add the extra 'n' datapoints to each side of the chunk (can't do that for start and end chunks but that's ok) I end up with gaps where the smoothing doesn't match up because the loess doesn't take into account the points prior to the ones in its own chunk.
[1]: https://i.stack.imgur.com/0znn1.png |
I am trying to learn how to use Room in an Android application to store local data. I have tried to follow the instructions from: https://developer.android.com/training/data-storage/room
I managed to get a simple application working, where the database was defined as:
```
@Database(entities = [Location::class], version = 1, exportSchema = true)
abstract class LocationDatabase : RoomDatabase() {
abstract fun locationDAO(): LocationDAO
companion object {
@Volatile
private var INSTANCE: LocationDatabase? = null
fun getDatabase(context: Context): LocationDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
LocationDatabase::class.java,
"location_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
instance
}
}
}
}
```
By including the following in the App level build.gradle.kts file, I could extract the schema of the database when the project was built.
```
ksp {
arg("room.schemaLocation", "$projectDir/schemas")
}
```
I wanted to ask how I can use this schema to create a database file and prepopulate it and if can then be used as the content source when creating the application. What I'm trying to accomplish is to pre-populate the Room database with some data, which will be accessed while the application is running.
I attempted to locate some guidance on how to proceed on this, but failed to locate a resource that I could follow. |
null |
Here is a possible version of the correct code:
import random
print('Welcome to the Higher or Lower game!')
while True:
lowr = int(input('\nWhat would you like for your lower bound to be?: '))
upr = int(input('And your highest?: '))
x = (random.randint(lowr, upr))
if lowr >= upr:
print('The lowest bound must not be higher than highest bound. Try again.')
if lowr < upr:
g = int(input(f"""Great now guess a number between
{lowr} and {upr}:"""))
while True:
if g < x:
g = int(input('Nope. Too low, Guess another number: '))
elif g > x:
g = int(input('Nope. Too high, Guess another number: '))
if g == x:
print('You got it!')
break
There were some errors with: the use of the input method and the event lagestine.
|
I am learning Spark, so as a task we had to create a wheel locally and later install it in Databricks (I am using Azure Databricks), and test it by running it from a Databrick Notebook. This program involves reading a CSV file (timezones.csv) included inside the wheel file. The file *is* inside the wheel (I checked it) and also the wheel works properly when I install it and run it from a local PC Jupyter Notebook. However, when I install it in Databricks Notebook it gives this error, as you can see below in the snapshot:
```lang-py
[PATH_NOT_FOUND] Path does not exist: dbfs:/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/motor_ingesta/resources/timezones.csv. SQLSTATE: 42K03
File <command-3771510969632751>, line 7
3 from pyspark.sql import SparkSession
5 spark = SparkSession.builder.getOrCreate()
----> 7 flights_with_utc = aniade_hora_utc(spark, flights_df)
File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/motor_ingesta/agregaciones.py:25, in aniade_hora_utc(spark, df)
23 path_timezones = str(Path(__file__).parent) + "/resources/timezones.csv"
24 #path_timezones = str(Path("resources") / "timezones.csv")
---> 25 timezones_df = spark.read.options(header="true", inferSchema="true").csv(path_timezones)
27 # Concateno los datos de las columnas del timezones_df ("iata_code","iana_tz","windows_tz"), a la derecha de
28 # las columnas del df original, copiando solo en las filas donde coincida el aeropuerto de origen (Origin) con
29 # el valor de la columna iata_code de timezones.df. Si algun aeropuerto de Origin no apareciera en timezones_df,
30 # las 3 columnas quedarán con valor nulo (NULL)
32 df_with_tz = df.join(timezones_df, df["Origin"] == timezones_df["iata_code"], "left_outer")
File /databricks/spark/python/pyspark/instrumentation_utils.py:47, in _wrap_function.<locals>.wrapper(*args, **kwargs)
45 start = time.perf_counter()
46 try:
---> 47 res = func(*args, **kwargs)
48 logger.log_success(
49 module_name, class_name, function_name, time.perf_counter() - start, signature
50 )
51 return res
File /databricks/spark/python/pyspark/sql/readwriter.py:830, in DataFrameReader.csv(self, path, schema, sep, encoding, quote, escape, comment, header, inferSchema, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, nullValue, nanValue, positiveInf, negativeInf, dateFormat, timestampFormat, maxColumns, maxCharsPerColumn, maxMalformedLogPerPartition, mode, columnNameOfCorruptRecord, multiLine, charToEscapeQuoteEscaping, samplingRatio, enforceSchema, emptyValue, locale, lineSep, pathGlobFilter, recursiveFileLookup, modifiedBefore, modifiedAfter, unescapedQuoteHandling)
828 if type(path) == list:
829 assert self._spark._sc._jvm is not None
--> 830 return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path)))
831 elif isinstance(path, RDD):
833 def func(iterator):
File /databricks/spark/python/lib/py4j-0.10.9.7-src.zip/py4j/java_gateway.py:1322, in JavaMember.__call__(self, *args)
1316 command = proto.CALL_COMMAND_NAME +\
1317 self.command_header +\
1318 args_command +\
1319 proto.END_COMMAND_PART
1321 answer = self.gateway_client.send_command(command)
-> 1322 return_value = get_return_value(
1323 answer, self.gateway_client, self.target_id, self.name)
1325 for temp_arg in temp_args:
1326 if hasattr(temp_arg, "_detach"):
File /databricks/spark/python/pyspark/errors/exceptions/captured.py:230, in capture_sql_exception.<locals>.deco(*a, **kw)
226 converted = convert_exception(e.java_exception)
227 if not isinstance(converted, UnknownException):
228 # Hide where the exception came from that shows a non-Pythonic
229 # JVM exception message.
--> 230 raise converted from None
231 else:
232 raise
```
Databricks Error Snapshot 1:

Databricks Error Snapshot 2:

Has anyone experienced this problem before? Is there any solution?
I tried installing the file both with pip and from Library, and I got the same error, also rebooted the cluster several times.
Thanks in advance for your help.
I am using Python 3.11, Pyspark 3.5 and Java 8 and created the wheel locally from PyCharm. If you need more details to answer, just ask and I'll provide them.
I explained all the details above. I was expecting to be able to use the wheel I created locally from a Databricks Notebook.
Sorry about my English is not my native tongue and I am a bit rusty.
> Can u navigate to %sh ls
> /dbfs/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/motor_ingesta/resources and share the folder content as image? – Samuel Demir 11 hours ago
I just did what you asked for and I got this result (The file is actually there even if Databricks says it can't find it...
[Snapshot of suggestion result][1]
[1]: https://i.stack.imgur.com/SnJ6M.png |
How about trying this one?
```xml
<p class="post-date">
<time datetime="2023-01-01" th:text="${#dates.format(item.getCreatedDate(), 'dd-MM-yyyy HH:mm')}">Oct 5, 2023</time>
</p>
``` |
I am using react-bootstrap and have a `<Carousel>` that I am using to display images. I'd like for them to be contained within the container, such that the entire image is visible, except for in the case that the aspect ratio is greater than 2:1 (ie really tall images), in which case you can scroll to see the rest of the image. Here is the markup for the carousel:
```JSX
<Col xs="6" className="image-carousel-container">
<Carousel
activeIndex={activeIndex}
onSelect={handleSelect}
interval={null}
className="image-carousel"
>
{orderItem.imageNames.map((imageName, index) => (
<Carousel.Item key={index}>
<div className="image-container">
<img
className="image-carousel-image"
src={apiEndpoint + PATH.TEMP_IMAGES + imageName}
alt={imageName}
/>
</div>
</Carousel.Item>
))}
</Carousel>
<p className="image-count-text">{`Total Images: ${orderItem.imageNames.length}`}</p>
</Col>
```
And the CSS I have defined:
```CSS
.image-carousel-container {
display: grid;
flex-direction: column;
margin: auto;
min-height: 100%;
height: auto;
}
.image-carousel {
max-width: 100%;
max-height: 60vh;
display: flex;
align-items: center;
}
.image-container {
min-height: 60vh;
width: auto;
margin: auto;
overflow-y: auto;
}
.image-carousel-image {
max-width: 100%;
min-width: 50% !important;
height: 60vh;
object-fit: contain;
}
```
So you can see I am attempting to make these "tall images" take up half the width of the container, and then scroll to see the rest of the image.
With this configuration, everything works except for the scroll. The `min-width` appears to be ignored, and the tall images are just shrunk to fit the container.
If I switch `object-fit: cover`, then the tall images take up half the width, but I have 2 issues:
1. my "wide" images expand to fill the container vertically (I want a max width of 100%).
2. the top and bottom are just truncated, there is no scroll available.
Is there a way to get the images to just fit the container and only scroll when necessary (while still taking up half the width of the container)? I have been struggling with this for a while now and none of the existing SO questions appear to address this specific case. |
|django|django-rest-framework|stripe-payments|payment-gateway| |
null |
How to auto login to microsoft store? |
|c#|store|autologin| |
Under Linux and other Unix-related systems, there were traditionally only two characters that could not appear in the name of a file or directory, and those are NUL `'\0'` and slash `'/'`. The slash, of course, can appear in a pathname, separating directory components.
Rumour<sup>1</sup> has it that Steven Bourne (of 'shell' fame) had a directory containing 254 files, one for every single character that can appear in a file name (excluding `/`, `'\0'`; the name `.` was the current directory, of course). It was used to test the Bourne shell and routinely wrought havoc on unwary programs such as backup programs.
[Other](https://stackoverflow.com/a/31976060/15168) [people](https://stackoverflow.com/a/1976050/15168) have covered the rules for Windows filenames, with links to [Microsoft](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file) and [Wikipedia](http://en.wikipedia.org/wiki/Filename) on the topic.
Note that MacOS X has a case-insensitive file system. Current versions of it appear to allow colon `:` in file names, though historically, that was not necessarily always the case:
```sh
$ echo a:b > a:b
$ ls -l a:b
-rw-r--r-- 1 jonathanleffler staff 4 Nov 12 07:38 a:b
$
```
However, at least with macOS Big Sur 11.7, the file system does not allow file names that are not valid UTF-8 strings. That means the file name cannot consist of the bytes that are always invalid in UTF-8 (0xC0, 0xC1, 0xF5-0xFF), and you can't use the continuation bytes 0x80..0xBF as the only byte in a file name. The error given is 92 Illegal byte sequence.
POSIX defines a [Portable Filename Character Set](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_282) consisting of:
```none
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 . _ -
```
Sticking with names formed solely from those characters avoids most of the problems, though Windows still adds some complications.
<hr>
<sup>1</sup> It was Kernighan & Pike in ['The Practice of Programming'](https://www.cs.princeton.edu/~bwk/tpop.webpage/) who said as much in Chapter 6, Testing, §6.5 Stress Tests:
> When Steve Bourne was writing his Unix shell (which came to be known as the Bourne shell), he made a directory of 254 files with one-character names, one for each byte value except `'\0'` and slash, the two characters that cannot appear in Unix file names. He used that directory for all manner of tests of pattern-matching and tokenization. (The test directory was, of course, created by a program.) For years afterwards, that directory was the bane of file-tree-walking programs; it tested them to destruction.
<sup>_Note that the directory must have contained entries `.` and `..`, so it was arguably 253 files (and 2 directories), or 255 name entries, rather than 254 files. This doesn't affect the effectiveness of the anecdote, or the careful testing it describes._</sup>
<sup>_TPOP was previously at
http://plan9.bell-labs.com/cm/cs/tpop and
http://cm.bell-labs.com/cm/cs/tpop but both are now (2021-11-12) broken.
See also Wikipedia on [TPOP](https://en.wikipedia.org/wiki/The_Practice_of_Programming)._
</sup>
|
|c#|.net|unit-testing|nunit| |