content
stringlengths 86
88.9k
| title
stringlengths 0
150
| question
stringlengths 1
35.8k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 30
130
|
---|---|---|---|---|---|---|---|---|
Q:
how do I write a algorithm to find genes in a large String
I'm writing a program to find genes in a large string of DNA.
My output is correct on small input strings of DNA, but when I test it on their example DNA string (which is very large—too large to check manually if my output is correct) it says that my output is incorrect.
Here's my code:
public class part1
{
// find stop codon
public int findStopCodon(String dna, int startIndex, String stopCodon)
{
int stopIndex = dna.indexOf(stopCodon, startIndex);
if (stopIndex != -1)
{
if (dna.substring(startIndex, stopIndex + 3).length() % 3 == 0)
{
return stopIndex;
}
}
return dna.length();
}
// find gene
public String findGene(String dna, int startIndex)
{
if ( startIndex != -1)
{
int taaIndex = findStopCodon(dna, startIndex, "TAA");
int tgaIndex = findStopCodon(dna, startIndex, "TGA");
int tagIndex = findStopCodon(dna, startIndex, "TAG");
int temp = Math.min(taaIndex, tgaIndex);
int minIndex = Math.min(temp, tagIndex);
if (minIndex <= dna.length() - 3)
{
return dna.substring(startIndex, minIndex + 3);
}
}
return "";
}
// put all genes into a storage resource
public StorageResource allGenes(String dna)
{
StorageResource geneList = new StorageResource();
int prevIndex = 0;
while (prevIndex <= dna.length())
{
int startIndex = dna.indexOf("ATG", prevIndex);
if (startIndex == -1)
{
return geneList;
}
String gene = findGene(dna, startIndex);
if (gene.isEmpty() != true)
{
geneList.add(gene);
}
prevIndex = startIndex + gene.length() + 1;
}
return geneList;
}
}
When executed on this data: https://users.cs.duke.edu/~rodger/GRch38dnapart.fa
This is my output:
this many genes: 106
number of length \> 60: 31
number of cgRatio \> 0.35: 54
longest: 282
CTG appears: 224 times
A:
The goal of findStopCodon is to find stop codon at a place that is a multiple of 3 compared to the startIndex. (Based on domain knowledge.)
If the stop codon isn't at multiple of 3 compared to start you should continue the search from that point, not returning the end of the string.
|
how do I write a algorithm to find genes in a large String
|
I'm writing a program to find genes in a large string of DNA.
My output is correct on small input strings of DNA, but when I test it on their example DNA string (which is very large—too large to check manually if my output is correct) it says that my output is incorrect.
Here's my code:
public class part1
{
// find stop codon
public int findStopCodon(String dna, int startIndex, String stopCodon)
{
int stopIndex = dna.indexOf(stopCodon, startIndex);
if (stopIndex != -1)
{
if (dna.substring(startIndex, stopIndex + 3).length() % 3 == 0)
{
return stopIndex;
}
}
return dna.length();
}
// find gene
public String findGene(String dna, int startIndex)
{
if ( startIndex != -1)
{
int taaIndex = findStopCodon(dna, startIndex, "TAA");
int tgaIndex = findStopCodon(dna, startIndex, "TGA");
int tagIndex = findStopCodon(dna, startIndex, "TAG");
int temp = Math.min(taaIndex, tgaIndex);
int minIndex = Math.min(temp, tagIndex);
if (minIndex <= dna.length() - 3)
{
return dna.substring(startIndex, minIndex + 3);
}
}
return "";
}
// put all genes into a storage resource
public StorageResource allGenes(String dna)
{
StorageResource geneList = new StorageResource();
int prevIndex = 0;
while (prevIndex <= dna.length())
{
int startIndex = dna.indexOf("ATG", prevIndex);
if (startIndex == -1)
{
return geneList;
}
String gene = findGene(dna, startIndex);
if (gene.isEmpty() != true)
{
geneList.add(gene);
}
prevIndex = startIndex + gene.length() + 1;
}
return geneList;
}
}
When executed on this data: https://users.cs.duke.edu/~rodger/GRch38dnapart.fa
This is my output:
this many genes: 106
number of length \> 60: 31
number of cgRatio \> 0.35: 54
longest: 282
CTG appears: 224 times
|
[
"The goal of findStopCodon is to find stop codon at a place that is a multiple of 3 compared to the startIndex. (Based on domain knowledge.)\nIf the stop codon isn't at multiple of 3 compared to start you should continue the search from that point, not returning the end of the string.\n"
] |
[
1
] |
[
"the problem with my code is that this function should have contained a loop, because in some cases where none of the nearest stop codons are multiples of 3 away from the start index, the function would return dna.length.\n\nwhen it should have have continued looking past those nearest substrings.\n// find stop codon\npublic int findStopCodon(String dna, int startIndex, String stopCodon)\n{\n int stopIndex = dna.indexOf(stopCodon, startIndex);\n if (stopIndex != -1)\n {\n if (dna.substring(startIndex, stopIndex + 3).length() % 3 == 0)\n {\n return stopIndex;\n }\n }\n return dna.length();\n}\n\n"
] |
[
-1
] |
[
"algorithm",
"dna_sequence",
"java"
] |
stackoverflow_0074648678_algorithm_dna_sequence_java.txt
|
Q:
What is the reason for mysql connection timeout using nodejs and RDS database
I was connecting to mysql database and everything was fine. Suddenly, I started to get the TIMEOUT error. So, I try to connect using a simple test code. The code is:
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'RDS HOST',
user:'user',
password:'password',
database:'database'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
However, I am getting this error:
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/sql-test/node_modules/mysql/lib/Connection.js:419:13)
at Socket.g (events.js:292:16)
at emitNone (events.js:86:13)
at Socket.emit (events.js:185:7)
at Socket._onTimeout (net.js:338:8)
at ontimeout (timers.js:386:11)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
--------------------
at Protocol._enqueue (/sql-test/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/sql-test/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/sql-test/node_modules/mysql/lib/Connection.js:130:18)
at Object.<anonymous> (/sql-test/sql-test.js:10:12)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
Some points:
My RDS Database is working fine and there are no security group
blocking the connection. I can connect to my RDS Database throw MySql
Workbeanch or PHPMYADMIN with no problem.
The code is correct. If I change the host for my mysql server running on localhost, I get no error.
Does anybody have an ideia of what else can be the reason for this error?
A:
I know this is old but I thought I would answer it since I had this problem with RDS databases in the past. You need to end the connections to RDS. If you don't, and dont handle the error, nodeJS will exit.
con.connect(function (err) {
if (err) {
console.log("Connection Failed");
var response = {
status: 400,
success: "Failed!",
message: "CONNECTION_FAILURE",
};
console.log(err.stack);
con.end(function(err) {
if (err) {
}
});
return res.send(JSON.stringify(response));
} else console.log("Connected!");
con.query("SELECT 0", function (err, result) {
if (err) {
var response = {
status: 400,
success: "Failed!",
message: "CONNECTION_FAILURE",
};
console.log(err.stack);
con.end(function(err) {
if (err) {
}
});
return res.send(JSON.stringify(response));
}
});
|
What is the reason for mysql connection timeout using nodejs and RDS database
|
I was connecting to mysql database and everything was fine. Suddenly, I started to get the TIMEOUT error. So, I try to connect using a simple test code. The code is:
var mysql = require('mysql');
var connection = mysql.createConnection({
host:'RDS HOST',
user:'user',
password:'password',
database:'database'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
However, I am getting this error:
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (/sql-test/node_modules/mysql/lib/Connection.js:419:13)
at Socket.g (events.js:292:16)
at emitNone (events.js:86:13)
at Socket.emit (events.js:185:7)
at Socket._onTimeout (net.js:338:8)
at ontimeout (timers.js:386:11)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
--------------------
at Protocol._enqueue (/sql-test/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/sql-test/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/sql-test/node_modules/mysql/lib/Connection.js:130:18)
at Object.<anonymous> (/sql-test/sql-test.js:10:12)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
Some points:
My RDS Database is working fine and there are no security group
blocking the connection. I can connect to my RDS Database throw MySql
Workbeanch or PHPMYADMIN with no problem.
The code is correct. If I change the host for my mysql server running on localhost, I get no error.
Does anybody have an ideia of what else can be the reason for this error?
|
[
"I know this is old but I thought I would answer it since I had this problem with RDS databases in the past. You need to end the connections to RDS. If you don't, and dont handle the error, nodeJS will exit.\n con.connect(function (err) {\n if (err) {\n console.log(\"Connection Failed\");\n var response = {\n status: 400,\n success: \"Failed!\",\n message: \"CONNECTION_FAILURE\",\n };\n console.log(err.stack);\n con.end(function(err) {\n if (err) {\n }\n });\n return res.send(JSON.stringify(response));\n } else console.log(\"Connected!\");\n con.query(\"SELECT 0\", function (err, result) {\n if (err) {\n var response = {\n status: 400,\n success: \"Failed!\",\n message: \"CONNECTION_FAILURE\",\n };\n console.log(err.stack);\n con.end(function(err) {\n if (err) {\n }\n });\n return res.send(JSON.stringify(response));\n }\n });\n\n"
] |
[
0
] |
[] |
[] |
[
"amazon_rds",
"connection_timeout",
"mysql",
"node.js"
] |
stackoverflow_0048940889_amazon_rds_connection_timeout_mysql_node.js.txt
|
Q:
How to use CompletableFuture to execute the threads parallaly without waiting and combine the result?
I have executeGetCapability method which is executed in different threads but these threads runs sequentially..meaning one is completed after the other
@Async("threadPoolCapabilitiesExecutor")
public CompletableFuture<CapabilityDTO> executeGetCapability(final String id, final LoggingContextData data){...}
and this method is called in following way:
public CapabilityResponseDTO getCapabilities(final List<String> ids) {
final CapabilityResponseDTO responseDTO = new CapabilityResponseDTO();
final List<CapabilityDTO> listOfCapabilityDTOS = new ArrayList<>();
try {
for (String id: ids) {
listOfCapabilityDTOS .add(
asyncProcessService.executeGetCapability(id, LoggingContext.getLoggingContextData()).get());
}
} catch (Exception e) {
....
}
responseDTO.setDTOS(listOfCapabilityDTOS );
return responseDTO;
}
How can i call executeGetCapability method using CompletableFuture so that thread runs in parallel without waiting for each other and then the result is combined ?? how can i use here CompletableFuture.supplyAsync and or .allOf methods ? Can someone explain me
Thanks
A:
The reduce helper function from this answer converts a CompletableFuture<Stream<T>> to a Stream<CompletableFuture<T>>. You can use it to asynchronously combine the results for multiple calls to executeGetCapability:
// For each id create a future to asynchronously execute executeGetCapability
Stream<CompletableFuture<CapabilityDTO>> futures = ids.stream()
.map(id -> executeGetCapability(id, LoggingContext.getLoggingContextData()));
// Reduce the stream of futures to a future for a stream
// and convert the stream to list
CompletableFuture<List<CapabilityDTO>> capabilitiesFuture = reduce(futures)
.thenApply(Stream::toList);
responseDTO.setDTOS(capabilitiesFuture.get());
|
How to use CompletableFuture to execute the threads parallaly without waiting and combine the result?
|
I have executeGetCapability method which is executed in different threads but these threads runs sequentially..meaning one is completed after the other
@Async("threadPoolCapabilitiesExecutor")
public CompletableFuture<CapabilityDTO> executeGetCapability(final String id, final LoggingContextData data){...}
and this method is called in following way:
public CapabilityResponseDTO getCapabilities(final List<String> ids) {
final CapabilityResponseDTO responseDTO = new CapabilityResponseDTO();
final List<CapabilityDTO> listOfCapabilityDTOS = new ArrayList<>();
try {
for (String id: ids) {
listOfCapabilityDTOS .add(
asyncProcessService.executeGetCapability(id, LoggingContext.getLoggingContextData()).get());
}
} catch (Exception e) {
....
}
responseDTO.setDTOS(listOfCapabilityDTOS );
return responseDTO;
}
How can i call executeGetCapability method using CompletableFuture so that thread runs in parallel without waiting for each other and then the result is combined ?? how can i use here CompletableFuture.supplyAsync and or .allOf methods ? Can someone explain me
Thanks
|
[
"The reduce helper function from this answer converts a CompletableFuture<Stream<T>> to a Stream<CompletableFuture<T>>. You can use it to asynchronously combine the results for multiple calls to executeGetCapability:\n// For each id create a future to asynchronously execute executeGetCapability\nStream<CompletableFuture<CapabilityDTO>> futures = ids.stream()\n .map(id -> executeGetCapability(id, LoggingContext.getLoggingContextData()));\n\n// Reduce the stream of futures to a future for a stream \n// and convert the stream to list\nCompletableFuture<List<CapabilityDTO>> capabilitiesFuture = reduce(futures)\n .thenApply(Stream::toList);\n\nresponseDTO.setDTOS(capabilitiesFuture.get());\n\n"
] |
[
0
] |
[] |
[] |
[
"asynchronous",
"completable_future",
"java.util.concurrent",
"java_threads",
"parallel_processing"
] |
stackoverflow_0074629309_asynchronous_completable_future_java.util.concurrent_java_threads_parallel_processing.txt
|
Q:
Cleanup script with exclusions
Glob(list, A_AppData "Local\Company\Program 1\Program 1\*.*")
Glob(list, A_AppData "Local\Company\Program 2\Program 2\*.*")
Loop, Parse, list, `n
{
FileGetAttrib, FolderOrFile, %A_LoopField%
IfInString, FolderOrFile, D
FileRemoveDir, %A_LoopField%, 1
else
FileDelete, %A_LoopField%
}
MsgBox, Clean-up complete.
;Uncomment (Remove the semi-colon) this next line if you want to see what couldn't be deleted.
;MsgBox %list%
Glob(ByRef list, Pattern, IncludeDirs=1)
{
if (i:=RegExMatch(Pattern,"[*?]")) && (i:=InStr(Pattern,"\",1,i+1))
Loop, % SubStr(Pattern, 1, i-1), 2
Glob(list, A_LoopFileLongPath . SubStr(Pattern,i), IncludeDirs)
else
Loop, %Pattern%, %IncludeDirs%
list .= (list="" ? "" : "`n") . A_LoopFileLongPath
}
What does Glob do exactly?
What is the difference between * and *.* in the original script? I only want to delete the contents of the specified directories.
How can I exclude files with certain extensions from being deleted?
A:
EnvGet, A_LocalAppData, LocalAppData
Glob(list, A_LocalAppData "\Company\Program 1\Program 1\*.*")
Glob(list, A_LocalAppData "\Company\Program 2\Program 2\*.*")
...
Loop, %Pattern%, %IncludeDirs%
if !InStr(A_LoopFileExt, "ext")
list .= (list="" ? "" : "`n") . A_LoopFileLongPath
}
|
Cleanup script with exclusions
|
Glob(list, A_AppData "Local\Company\Program 1\Program 1\*.*")
Glob(list, A_AppData "Local\Company\Program 2\Program 2\*.*")
Loop, Parse, list, `n
{
FileGetAttrib, FolderOrFile, %A_LoopField%
IfInString, FolderOrFile, D
FileRemoveDir, %A_LoopField%, 1
else
FileDelete, %A_LoopField%
}
MsgBox, Clean-up complete.
;Uncomment (Remove the semi-colon) this next line if you want to see what couldn't be deleted.
;MsgBox %list%
Glob(ByRef list, Pattern, IncludeDirs=1)
{
if (i:=RegExMatch(Pattern,"[*?]")) && (i:=InStr(Pattern,"\",1,i+1))
Loop, % SubStr(Pattern, 1, i-1), 2
Glob(list, A_LoopFileLongPath . SubStr(Pattern,i), IncludeDirs)
else
Loop, %Pattern%, %IncludeDirs%
list .= (list="" ? "" : "`n") . A_LoopFileLongPath
}
What does Glob do exactly?
What is the difference between * and *.* in the original script? I only want to delete the contents of the specified directories.
How can I exclude files with certain extensions from being deleted?
|
[
"EnvGet, A_LocalAppData, LocalAppData\nGlob(list, A_LocalAppData \"\\Company\\Program 1\\Program 1\\*.*\")\nGlob(list, A_LocalAppData \"\\Company\\Program 2\\Program 2\\*.*\")\n... \n Loop, %Pattern%, %IncludeDirs%\n if !InStr(A_LoopFileExt, \"ext\")\n list .= (list=\"\" ? \"\" : \"`n\") . A_LoopFileLongPath\n}\n\n"
] |
[
0
] |
[] |
[] |
[
"autohotkey"
] |
stackoverflow_0074622228_autohotkey.txt
|
Q:
Newbie question about C variable declarations
I'm reading an introducty book about C and I came across the following paragraph:
But the following code compiles with expected output:
#include <stdio.h>
int main()
{
for(int i = 0; i<=10; i++)
{
int val = i + 1;
int x = val * val;
printf("%d\n", x);
int y = x;
}
return 0;
}
I use https://www.onlinegdb.com/ and in the above code I declared many variables after the first executable statement. And this is to me does not match what the section from the book tells.
Am I misunderstanding what the book is telling?
A:
In strictly conforming C 1990, declarations could appear only at file scope (outside of function definitions) or at the start of a compound statement. The grammar for a compound statement in C 1990 6.6.2 was:
compound-statement
{ declaration-listopt statement-listopt }
That says a compound statement is { followed by zero or more declarations, then zero or more statements, then }. So the declarations had to come first.
In C 1999 6.8.2, this changed to:
compound-statement
{ block-item-listopt }
A block-item-list is a list of block-item, each of which may be a declaration or a statement, so declarations and statements could be freely mixed.
In your example, the declarations int val = i + 1; and int x = val * val; do not appear after executable statements in their compound statement. The compound statement starts with the { immediately before int val = i + 1;, so that declaration is at the start of the compound statement.
Another change was that the for grammar was changed from this in C 1990 6.6.5:
for ( expressionopt ; expressionopt ; expressionopt ) statement
to this choice of two forms in C 1999 6.8.5:
for ( expressionopt ; expressionopt ; expressionopt ) statement
for ( declaration expressionopt ; expressionopt ) statement
(Note the declaration includes a terminating ;.)
That explains why you can have int i = 0 in for(int i = 0; i<=10; i++).
A:
The book is referring to the original C specification from over 30 years ago known as "ANSI C" or "C89" or "C90". If we run a C compiler in C89 mode, -std=c89, we get a warning from your code...
cc -Wall -Wshadow -Wwrite-strings -Wextra -Wconversion -std=c89 -pedantic -g -fsanitize=address -c -o test.o test.c
test.c:5:9: warning: variable declaration in for loop is a C99-specific feature [-Wc99-extensions]
for(int i = 0; i<=10; i++)
^
test.c:5:9: warning: GCC does not allow variable declarations in for loop initializers before C99 [-Wgcc-compat]
2 warnings generated.
C99, the update to C made in 1999, made this untrue. Running your code with -std=c99 gives no warning. C99 made this and other impactful changes to the language, like // comments.
There is also C11 and the latest stable version of C is C17, but compiler support for both is spotty.
Why is this book referring to such an old version of the language? C has existed since 1978 and there are a lot of old code and old compilers out there. C Compilers have been very slow to fully adopt new standards making authors quite conservative. A big stumbling block was Microsoft Visual C++ did not implement C99 until 2013! So ANSI C was the lowest-common denominator for a very long time.
In recent years, C compilers have gotten better about standards compliance, so you can rely on C99 (which is old enough to drink) as your baseline.
A:
All variables in your example have been declared before used.
The declarations are:
int i ...;
int val ...;
int x ...;
Note that all declarations happen before the first function call in the corresponding block. On other words: i, val and x are all declared before the printf.
As stated in the comments: Some old books might refer to old versions of C. The variable declaration within the for loop came with C99 for example. Beginning with C99 you could also declare variables in the middle of the block. So you are allowed to declare some int y; after the printf and your code would still compile.
|
Newbie question about C variable declarations
|
I'm reading an introducty book about C and I came across the following paragraph:
But the following code compiles with expected output:
#include <stdio.h>
int main()
{
for(int i = 0; i<=10; i++)
{
int val = i + 1;
int x = val * val;
printf("%d\n", x);
int y = x;
}
return 0;
}
I use https://www.onlinegdb.com/ and in the above code I declared many variables after the first executable statement. And this is to me does not match what the section from the book tells.
Am I misunderstanding what the book is telling?
|
[
"In strictly conforming C 1990, declarations could appear only at file scope (outside of function definitions) or at the start of a compound statement. The grammar for a compound statement in C 1990 6.6.2 was:\n\ncompound-statement\n { declaration-listopt statement-listopt }\n\nThat says a compound statement is { followed by zero or more declarations, then zero or more statements, then }. So the declarations had to come first.\nIn C 1999 6.8.2, this changed to:\n\ncompound-statement\n { block-item-listopt }\n\nA block-item-list is a list of block-item, each of which may be a declaration or a statement, so declarations and statements could be freely mixed.\nIn your example, the declarations int val = i + 1; and int x = val * val; do not appear after executable statements in their compound statement. The compound statement starts with the { immediately before int val = i + 1;, so that declaration is at the start of the compound statement.\nAnother change was that the for grammar was changed from this in C 1990 6.6.5:\n\nfor ( expressionopt ; expressionopt ; expressionopt ) statement\n\nto this choice of two forms in C 1999 6.8.5:\n\nfor ( expressionopt ; expressionopt ; expressionopt ) statement\nfor ( declaration expressionopt ; expressionopt ) statement\n\n(Note the declaration includes a terminating ;.)\nThat explains why you can have int i = 0 in for(int i = 0; i<=10; i++).\n",
"The book is referring to the original C specification from over 30 years ago known as \"ANSI C\" or \"C89\" or \"C90\". If we run a C compiler in C89 mode, -std=c89, we get a warning from your code...\ncc -Wall -Wshadow -Wwrite-strings -Wextra -Wconversion -std=c89 -pedantic -g -fsanitize=address -c -o test.o test.c\ntest.c:5:9: warning: variable declaration in for loop is a C99-specific feature [-Wc99-extensions]\n for(int i = 0; i<=10; i++)\n ^\ntest.c:5:9: warning: GCC does not allow variable declarations in for loop initializers before C99 [-Wgcc-compat]\n2 warnings generated.\n\nC99, the update to C made in 1999, made this untrue. Running your code with -std=c99 gives no warning. C99 made this and other impactful changes to the language, like // comments.\nThere is also C11 and the latest stable version of C is C17, but compiler support for both is spotty.\n\nWhy is this book referring to such an old version of the language? C has existed since 1978 and there are a lot of old code and old compilers out there. C Compilers have been very slow to fully adopt new standards making authors quite conservative. A big stumbling block was Microsoft Visual C++ did not implement C99 until 2013! So ANSI C was the lowest-common denominator for a very long time.\nIn recent years, C compilers have gotten better about standards compliance, so you can rely on C99 (which is old enough to drink) as your baseline.\n",
"All variables in your example have been declared before used.\nThe declarations are:\nint i ...;\nint val ...;\nint x ...;\n\nNote that all declarations happen before the first function call in the corresponding block. On other words: i, val and x are all declared before the printf.\nAs stated in the comments: Some old books might refer to old versions of C. The variable declaration within the for loop came with C99 for example. Beginning with C99 you could also declare variables in the middle of the block. So you are allowed to declare some int y; after the printf and your code would still compile.\n"
] |
[
7,
1,
0
] |
[] |
[] |
[
"c"
] |
stackoverflow_0074661801_c.txt
|
Q:
Selenium cannot scrape all elements with same xpath, don't know if the page is not fully loaded?
I am trying to scrape this page the title and the price,
https://magnumbikes.com/collections/e-bikes?sort_by=best-selling,
but only half of the products can be collected (it stops at product Metro X),
not sure if it is the page is not fully loaded,
Please let me know or correct me thank you!
Here is my code:
URL='https://magnumbikes.com/collections/e-bikes?sort_by=best-selling'
#driver.maxmize_window()
driver.get(URL)
#There is a subscription window popping up for first time, refresh the page again!
driver.refresh()
time.sleep(2)
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
titless=WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, '//div/div/h3[@class="collection-card__title h3"]')))
prices=WebDriverWait(driver,20).until(EC.presence_of_all_elements_located((By.XPATH,'//div[@class="collection-card__prices-inner"]/span')))
for i in range(0,len(titless)):
print(titless[i].text)
print(prices[i].text)
A:
Here is a way to get that information using Requests:
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
pd.set_option('display.max_columns', None)
pd.set_option('display.max_colwidth', None)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}
s = requests.Session()
s.headers.update(headers)
big_list = []
for x in range(1, 3):
r = s.get(f'https://magnumbikes.com/collections/e-bikes?page={x}&sort_by=best-selling')
soup = bs(r.text, 'html.parser')
items = soup.select('div[class="collection-filter__item"]')
for i in items:
title = i.select_one('h3 a').get_text()
url = 'https://magnumbikes.com' + i.select_one('h3 a').get('href')
big_list.append((title, url))
df = pd.DataFrame(big_list, columns=['Bike', 'Url'])
print(df.to_markdown())
Result in terminal:
Bike
Url
0
Nomad
https://magnumbikes.com//collections/e-bikes/products/magnum-nomad
1
Pathfinder 350
https://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-350
2
Metro S
https://magnumbikes.com//collections/e-bikes/products/magnum-metro-s
3
Scout
https://magnumbikes.com//collections/e-bikes/products/magnum-scout
4
Payload
https://magnumbikes.com//collections/e-bikes/products/magnum-payload
5
Peak T7
https://magnumbikes.com//collections/e-bikes/products/magnum-peak-t7
6
Metro 750
https://magnumbikes.com//collections/e-bikes/products/magnum-metro-750
7
Pathfinder T
https://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-t
8
Ranger 1.0
https://magnumbikes.com//collections/e-bikes/products/magnum-ranger
9
Low rider 1.0
https://magnumbikes.com//collections/e-bikes/products/magnum-low-rider-2019
10
Pathfinder 500
https://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-500
11
Cruiser 1.0
https://magnumbikes.com//collections/e-bikes/products/magnum-cruiser-1-0
12
Summit 27.5"
https://magnumbikes.com//collections/e-bikes/products/magnum-summit-27-5
13
Metro X
https://magnumbikes.com//collections/e-bikes/products/magnum-metro-x
14
Peak T5
https://magnumbikes.com//collections/e-bikes/products/magnum-peak-t5
15
Premium 3 Low Step
https://magnumbikes.com//collections/e-bikes/products/magnum-premium-3-low-step
16
Navigator X
https://magnumbikes.com//collections/e-bikes/products/magnum-navigator-x
17
Cosmo X
https://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-x
18
Cosmo+
https://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-1
19
Cosmo S
https://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-s
20
Low rider 2.0
https://magnumbikes.com//collections/e-bikes/products/magnum-low-rider
21
Navigator S
https://magnumbikes.com//collections/e-bikes/products/magnum-navigator-s
22
Ranger 2.0
https://magnumbikes.com//collections/e-bikes/products/ranger-2-0
23
Premium 3 High Step
https://magnumbikes.com//collections/e-bikes/products/magnum-premium-3-high-step
24
Voyager
https://magnumbikes.com//collections/e-bikes/products/magnum-voyager
25
Cruiser 2.0
https://magnumbikes.com//collections/e-bikes/products/magnum-cruiser
26
Cosmo
https://magnumbikes.com//collections/e-bikes/products/magnum-cosmo
You can use Selenium if you wish - just observe the urls accessed (taken from Dev tools - Network tab) and the locators.
|
Selenium cannot scrape all elements with same xpath, don't know if the page is not fully loaded?
|
I am trying to scrape this page the title and the price,
https://magnumbikes.com/collections/e-bikes?sort_by=best-selling,
but only half of the products can be collected (it stops at product Metro X),
not sure if it is the page is not fully loaded,
Please let me know or correct me thank you!
Here is my code:
URL='https://magnumbikes.com/collections/e-bikes?sort_by=best-selling'
#driver.maxmize_window()
driver.get(URL)
#There is a subscription window popping up for first time, refresh the page again!
driver.refresh()
time.sleep(2)
driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")
titless=WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.XPATH, '//div/div/h3[@class="collection-card__title h3"]')))
prices=WebDriverWait(driver,20).until(EC.presence_of_all_elements_located((By.XPATH,'//div[@class="collection-card__prices-inner"]/span')))
for i in range(0,len(titless)):
print(titless[i].text)
print(prices[i].text)
|
[
"Here is a way to get that information using Requests:\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport pandas as pd\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_colwidth', None)\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'\n}\n\ns = requests.Session()\ns.headers.update(headers)\n\nbig_list = []\n\nfor x in range(1, 3):\n r = s.get(f'https://magnumbikes.com/collections/e-bikes?page={x}&sort_by=best-selling')\n soup = bs(r.text, 'html.parser')\n items = soup.select('div[class=\"collection-filter__item\"]')\n for i in items:\n title = i.select_one('h3 a').get_text() \n url = 'https://magnumbikes.com' + i.select_one('h3 a').get('href')\n big_list.append((title, url))\ndf = pd.DataFrame(big_list, columns=['Bike', 'Url'])\nprint(df.to_markdown())\n\nResult in terminal:\n\n\n\n\n\nBike\nUrl\n\n\n\n\n0\nNomad\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-nomad\n\n\n1\nPathfinder 350\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-350\n\n\n2\nMetro S\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-metro-s\n\n\n3\nScout\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-scout\n\n\n4\nPayload\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-payload\n\n\n5\nPeak T7\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-peak-t7\n\n\n6\nMetro 750\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-metro-750\n\n\n7\nPathfinder T\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-t\n\n\n8\nRanger 1.0\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-ranger\n\n\n9\nLow rider 1.0\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-low-rider-2019\n\n\n10\nPathfinder 500\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-pathfinder-500\n\n\n11\nCruiser 1.0\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-cruiser-1-0\n\n\n12\nSummit 27.5\"\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-summit-27-5\n\n\n13\nMetro X\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-metro-x\n\n\n14\nPeak T5\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-peak-t5\n\n\n15\nPremium 3 Low Step\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-premium-3-low-step\n\n\n16\nNavigator X\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-navigator-x\n\n\n17\nCosmo X\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-x\n\n\n18\nCosmo+\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-1\n\n\n19\nCosmo S\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-cosmo-s\n\n\n20\nLow rider 2.0\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-low-rider\n\n\n21\nNavigator S\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-navigator-s\n\n\n22\nRanger 2.0\nhttps://magnumbikes.com//collections/e-bikes/products/ranger-2-0\n\n\n23\nPremium 3 High Step\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-premium-3-high-step\n\n\n24\nVoyager\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-voyager\n\n\n25\nCruiser 2.0\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-cruiser\n\n\n26\nCosmo\nhttps://magnumbikes.com//collections/e-bikes/products/magnum-cosmo\n\n\n\n\n\nYou can use Selenium if you wish - just observe the urls accessed (taken from Dev tools - Network tab) and the locators.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] |
stackoverflow_0074660079_python_selenium_selenium_webdriver_web_scraping.txt
|
Q:
Spotify API (Obtaining Authorization Code) using Python
My goal is to connect to the Spotify API using pure Python and I have been able to figure out how to obtain the authorization token given the authorization code but I am unable to get the authorization code itself.
Note: I have not provided the client_id and client_secret for obvious reasons and you can assume that all libraries have been imported.
Once the web browser opens, the authorization code ("code") is displayed as a query parameter in the URL but I am unsure how to go about saving it to a variable. I can't just copy and paste it to a variable as the authorization code constantly changes.
My question is how exactly I would go about retrieving the code query paramter and save it to a variable?
Here is what I have tried so far:
# credentials
client_id = "xxx..."
client_secret = "xxx..."
# urls
redirect_uri = "http://localhost:7777/callback"
auth_url = "https://accounts.spotify.com/authorize?"
token_url = "https://accounts.spotify.com/api/token"
# data scopes
scopes = "user-read-private user-read-email"
# obtains authorization code
payload = {
"client_id": client_id,
"response_type": "code",
"redirect_uri": redirect_uri,
"scope": scopes
}
webbrowser.open(auth_url + urlencode(payload))
code = # NOT SURE HOW TO RETRIEVE CODE
# obtains authorization token
encoded_creds = base64.b64encode(client_id.encode() + b":" + client_secret.encode()).decode('utf-8')
token_headers = {
"Authorization": "Basic " + encoded_creds,
"Content-Type": "application/x-www-form-urlencoded"
}
token_data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_uri
}
r = req.post(token_url, data=token_data, headers=token_headers)
A:
You'll need to extract the code from your callback URL. If authentication is successful, Spotify will make a request to your redirect_uri with the code in the query (e.g http://localhost:7777/callback?code=...).
The easiest way to do that is probably spin up a Flask server (or equivalent) with a GET callback endpoint and grab the code there. Then you can exchange it for the authorization token in the same endpoint if you'd like. This example may be helpful: https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L60
|
Spotify API (Obtaining Authorization Code) using Python
|
My goal is to connect to the Spotify API using pure Python and I have been able to figure out how to obtain the authorization token given the authorization code but I am unable to get the authorization code itself.
Note: I have not provided the client_id and client_secret for obvious reasons and you can assume that all libraries have been imported.
Once the web browser opens, the authorization code ("code") is displayed as a query parameter in the URL but I am unsure how to go about saving it to a variable. I can't just copy and paste it to a variable as the authorization code constantly changes.
My question is how exactly I would go about retrieving the code query paramter and save it to a variable?
Here is what I have tried so far:
# credentials
client_id = "xxx..."
client_secret = "xxx..."
# urls
redirect_uri = "http://localhost:7777/callback"
auth_url = "https://accounts.spotify.com/authorize?"
token_url = "https://accounts.spotify.com/api/token"
# data scopes
scopes = "user-read-private user-read-email"
# obtains authorization code
payload = {
"client_id": client_id,
"response_type": "code",
"redirect_uri": redirect_uri,
"scope": scopes
}
webbrowser.open(auth_url + urlencode(payload))
code = # NOT SURE HOW TO RETRIEVE CODE
# obtains authorization token
encoded_creds = base64.b64encode(client_id.encode() + b":" + client_secret.encode()).decode('utf-8')
token_headers = {
"Authorization": "Basic " + encoded_creds,
"Content-Type": "application/x-www-form-urlencoded"
}
token_data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_uri
}
r = req.post(token_url, data=token_data, headers=token_headers)
|
[
"You'll need to extract the code from your callback URL. If authentication is successful, Spotify will make a request to your redirect_uri with the code in the query (e.g http://localhost:7777/callback?code=...).\nThe easiest way to do that is probably spin up a Flask server (or equivalent) with a GET callback endpoint and grab the code there. Then you can exchange it for the authorization token in the same endpoint if you'd like. This example may be helpful: https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L60\n"
] |
[
1
] |
[] |
[] |
[
"authorization",
"python",
"spotify"
] |
stackoverflow_0074661575_authorization_python_spotify.txt
|
Q:
How do I set a shadow color for Jetpack Compose?
Sorry, I can hardly speak English.
machine translation:
How do I set a shadow color for Jetpack Compose?
I can set shadows, but they're ugly.
Jetpack Compose code:
Surface(
modifier = Modifier.width(160.dp).height(56.dp),
shape = CircleShape,
elevation = 2.dp,
) {
...
}
I want to create a shadow in the code below.
SwiftUI code:
ZStack {
...
}
.shadow(color: Color("button_shadow"), radius: 4, x: 0, y: 2)
.shadow(color: Color("button_shadow"), radius: 20, x: 0, y: 4)
Dark mode also requires a white shadow.
You want to be able to customize the color of the shadow.
A:
In my case for cycle I use this workaround:
@Composable
fun MyButton(){
Box(
modifier = Modifier
.size(64.dp)
.background(
brush = Brush.radialGradient(
colors = listOf(
Color.Yellow,
Color.Transparent
)
)
)
.padding(bottom = 4.dp),
contentAlignment = Alignment.Center
) {
Surface(
shape = CircleShape,
modifier = Modifier
.size(55.dp)
.background(Color.Transparent)
.clickable { }
) {
Box(
modifier = Modifier.padding()
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Icon(
modifier = Modifier.size(35.dp),
imageVector = Icons.Filled.Refresh,
contentDescription = "",
tint = Color.Yellow
)
}
}
}
}
there is the preview:
A:
Compose 1.2.0-alpha06 now supports shadow color attribute for the graphics layer modifier! ambientColor and spotColor can change the color of your shadow.
It's only useful with shapes though (CircleShape, RectangleShape, RoundedCornerShape, or your custom shape)
fun Modifier.shadow(
elevation: Dp,
shape: Shape = RectangleShape,
clip: Boolean = false,
elevation: Dp = 0.dp,
ambientColor: Color = DefaultShadowColor,
spotColor: Color = DefaultShadowColor,
)
https://developer.android.com/jetpack/androidx/releases/compose-ui#1.2.0-alpha06
A:
This is not possible at the moment but you can star the issue here: Link to Issue Tracker
The idea would be to have a modifier for the color, opacity, shape etc.
A:
Well, this has recently changed and you can do it using Material 3 Jetpack Compose library. Just call shadow on modifier and set desired color.
Add dependency
implementation 'androidx.compose.material3:material3:1.0.0-alpha12'
implementation "androidx.compose.ui:1.2.0-beta02"
and add shadow modifier.
.shadow(
elevation = 8.dp,
ambientColor = primaryBlue,
spotColor = primaryBlue
)
sample code.
Image(
painter = painterResource(id = R.drawable.ic_capture_icon),
contentDescription = "capture",
modifier = Modifier
.padding(20.dp)
.background(shape = RoundedCornerShape(15.dp), color = primaryBlue)
.size(60.dp)
.shadow(
elevation = 8.dp,
ambientColor = primaryBlue,
spotColor = primaryBlue
)
.align(Alignment.BottomEnd)
.padding(12.dp)
.clickable {
context.startActivity(Intent(context, GeoSpatialActivity::class.java))
},
colorFilter = ColorFilter.tint(color = Color.White)
)
A:
the link in the comment of @EpicPandaForce uses converts color to int using android.graphics.Color.Argb(Long) which required Api Level >= 26. I found another link in that gist comment in which function argb is used and it is in API level 1 added.
https://gist.github.com/arthurgonzaga/598267f570e38425fc52f97b30e0619d
A:
You can use the code below to add a colorful shadow to your Modifier:
fun Modifier.advanceShadow(
color: Color = Color.Black,
borderRadius: Dp = 16.dp,
blurRadius: Dp = 16.dp,
offsetY: Dp = 0.dp,
offsetX: Dp = 0.dp,
spread: Float = 1f,
) = drawBehind {
this.drawIntoCanvas {
val paint = Paint()
val frameworkPaint = paint.asFrameworkPaint()
val spreadPixel = spread.dp.toPx()
val leftPixel = (0f - spreadPixel) + offsetX.toPx()
val topPixel = (0f - spreadPixel) + offsetY.toPx()
val rightPixel = (this.size.width)
val bottomPixel = (this.size.height + spreadPixel)
if (blurRadius != 0.dp) {
/*
The feature maskFilter used below to apply the blur effect only works
with hardware acceleration disabled.
*/
frameworkPaint.maskFilter =
(BlurMaskFilter(blurRadius.toPx(), BlurMaskFilter.Blur.NORMAL))
}
frameworkPaint.color = color.toArgb()
it.drawRoundRect(
left = leftPixel,
top = topPixel,
right = rightPixel,
bottom = bottomPixel,
radiusX = borderRadius.toPx(),
radiusY = borderRadius.toPx(),
paint
)
}
}
|
How do I set a shadow color for Jetpack Compose?
|
Sorry, I can hardly speak English.
machine translation:
How do I set a shadow color for Jetpack Compose?
I can set shadows, but they're ugly.
Jetpack Compose code:
Surface(
modifier = Modifier.width(160.dp).height(56.dp),
shape = CircleShape,
elevation = 2.dp,
) {
...
}
I want to create a shadow in the code below.
SwiftUI code:
ZStack {
...
}
.shadow(color: Color("button_shadow"), radius: 4, x: 0, y: 2)
.shadow(color: Color("button_shadow"), radius: 20, x: 0, y: 4)
Dark mode also requires a white shadow.
You want to be able to customize the color of the shadow.
|
[
"In my case for cycle I use this workaround:\n@Composable\nfun MyButton(){\n Box(\n modifier = Modifier\n .size(64.dp)\n .background(\n brush = Brush.radialGradient(\n colors = listOf(\n Color.Yellow,\n Color.Transparent\n )\n )\n )\n .padding(bottom = 4.dp),\n contentAlignment = Alignment.Center\n ) {\n Surface(\n shape = CircleShape,\n modifier = Modifier\n .size(55.dp)\n .background(Color.Transparent)\n .clickable { }\n ) {\n Box(\n modifier = Modifier.padding()\n .background(Color.Gray),\n contentAlignment = Alignment.Center\n ) {\n Icon(\n modifier = Modifier.size(35.dp),\n imageVector = Icons.Filled.Refresh,\n contentDescription = \"\",\n tint = Color.Yellow\n )\n }\n }\n\n }\n}\n\nthere is the preview:\n\n",
"Compose 1.2.0-alpha06 now supports shadow color attribute for the graphics layer modifier! ambientColor and spotColor can change the color of your shadow.\nIt's only useful with shapes though (CircleShape, RectangleShape, RoundedCornerShape, or your custom shape)\nfun Modifier.shadow(\n elevation: Dp,\n shape: Shape = RectangleShape,\n clip: Boolean = false,\n elevation: Dp = 0.dp,\n ambientColor: Color = DefaultShadowColor,\n spotColor: Color = DefaultShadowColor,\n)\n\nhttps://developer.android.com/jetpack/androidx/releases/compose-ui#1.2.0-alpha06\n",
"This is not possible at the moment but you can star the issue here: Link to Issue Tracker\nThe idea would be to have a modifier for the color, opacity, shape etc.\n",
"Well, this has recently changed and you can do it using Material 3 Jetpack Compose library. Just call shadow on modifier and set desired color.\nAdd dependency\nimplementation 'androidx.compose.material3:material3:1.0.0-alpha12'\nimplementation \"androidx.compose.ui:1.2.0-beta02\"\n\nand add shadow modifier.\n .shadow(\n elevation = 8.dp,\n ambientColor = primaryBlue,\n spotColor = primaryBlue\n )\n\nsample code.\n Image(\n painter = painterResource(id = R.drawable.ic_capture_icon),\n contentDescription = \"capture\",\n modifier = Modifier\n .padding(20.dp)\n .background(shape = RoundedCornerShape(15.dp), color = primaryBlue)\n .size(60.dp)\n .shadow(\n elevation = 8.dp,\n ambientColor = primaryBlue,\n spotColor = primaryBlue\n )\n .align(Alignment.BottomEnd)\n .padding(12.dp)\n .clickable {\n context.startActivity(Intent(context, GeoSpatialActivity::class.java))\n },\n colorFilter = ColorFilter.tint(color = Color.White)\n )\n\n",
"the link in the comment of @EpicPandaForce uses converts color to int using android.graphics.Color.Argb(Long) which required Api Level >= 26. I found another link in that gist comment in which function argb is used and it is in API level 1 added.\nhttps://gist.github.com/arthurgonzaga/598267f570e38425fc52f97b30e0619d\n",
"You can use the code below to add a colorful shadow to your Modifier:\n fun Modifier.advanceShadow(\n color: Color = Color.Black,\n borderRadius: Dp = 16.dp,\n blurRadius: Dp = 16.dp,\n offsetY: Dp = 0.dp,\n offsetX: Dp = 0.dp,\n spread: Float = 1f,\n) = drawBehind {\n this.drawIntoCanvas {\n val paint = Paint()\n val frameworkPaint = paint.asFrameworkPaint()\n val spreadPixel = spread.dp.toPx()\n val leftPixel = (0f - spreadPixel) + offsetX.toPx()\n val topPixel = (0f - spreadPixel) + offsetY.toPx()\n val rightPixel = (this.size.width)\n val bottomPixel = (this.size.height + spreadPixel)\n\n if (blurRadius != 0.dp) {\n /*\n The feature maskFilter used below to apply the blur effect only works\n with hardware acceleration disabled.\n */\n frameworkPaint.maskFilter =\n (BlurMaskFilter(blurRadius.toPx(), BlurMaskFilter.Blur.NORMAL))\n }\n\n frameworkPaint.color = color.toArgb()\n it.drawRoundRect(\n left = leftPixel,\n top = topPixel,\n right = rightPixel,\n bottom = bottomPixel,\n radiusX = borderRadius.toPx(),\n radiusY = borderRadius.toPx(),\n paint\n )\n }\n}\n\n"
] |
[
9,
8,
2,
2,
0,
0
] |
[] |
[] |
[
"android_jetpack_compose"
] |
stackoverflow_0066203515_android_jetpack_compose.txt
|
Q:
Kadena Pact Create Account Fails
Hi Kadena Pact developers,
I'm following https://docs.kadena.io/build/frontend/pact-lang-api-cookbook#create-account to create coin accounts.
getBalance(`sender00`) returns
{
"gas": 20,
"result": {
"status": "success",
"data": 99998999.9999446
},
"reqKey": "AnmQHR9ciGruzwaV2LksjFANS8Mbr5UBuj26d2w4TLE",
"logs": "wsATyGqckuIvlm89hhd2j4t6RMkCrcwJe_oeCYr7Th8",
"metaData": {
"publicMeta": {
"creationTime": 1670018678,
"ttl": 28000,
"gasLimit": 600,
"chainId": "0",
"gasPrice": 1e-7,
"sender": "368820f80c324bbc7c2b0610688a7da43e39f91d118732671cd9c7500ff43cca"
},
"blockTime": 1670018669855184,
"prevBlockHash": "g5bNGUcMPQYC4klTi-D0QhsMBIT9oggVa_-Ea8hyQq4",
"blockHeight": 1964
},
"continuation": null,
"txId": null
}
I want to create another account using sender00 keypairs, however it fails w/ error message
Validation failed for hash "iu9bake1-nzhfQuYoRCM_LggDBenBLDWjGf6o7d00kY": Attempt to buy gas failed with: : Failure: Tx Failed: read: row not found: 368820f80c324bbc7c2b0610688a7da43e39f91d118732671cd9c7500ff43cca
Here is the whole script and the .env file
SENDER00_PUBLIC=368820f80c324bbc7c2b0610688a7da43e39f91d118732671cd9c7500ff43cca
SENDER00_SECRET=251a920c403ae8c8f65f59142316af3c82b631fba46ddea92ee8c95035bd2898
Script file
import * as dotenv from 'dotenv'
dotenv.config()
import Pact from 'pact-lang-api';
const GAS_PRICE = 0.0000001;
const GAS_LIMIT = 400;
const TTL = 28000;
const NETWORK_ID = 'development'//'testnet04';
const CHAIN_ID = '0';
const API_HOST = `http://localhost:8080/chainweb/0.0/${NETWORK_ID}/chain/${CHAIN_ID}/pact`;
const creationTime = () => Math.round((new Date).getTime() / 1000) - 15;
async function getBalance(account) {
const cmd = {
networkId: NETWORK_ID,
keyPairs: KEY_PAIR,
pactCode: `(coin.get-balance "${account}")`,
envData: {},
meta: {
creationTime: creationTime(),
ttl: 28000,
gasLimit: 600,
chainId: CHAIN_ID,
gasPrice: 0.0000001,
sender: KEY_PAIR.publicKey
}
};
const result = await Pact.fetch.local(cmd, API_HOST);
console.log(JSON.stringify(result, null, 2));
}
const KEY_PAIR = {
'publicKey': `${process.env.SENDER00_PUBLIC}`,
'secretKey': `${process.env.SENDER00_SECRET}`
}
async function createAccount(newAccount) {
const cmd = {
networkId: NETWORK_ID,
keyPairs: KEY_PAIR,
pactCode: `(coin.create-account "${newAccount}" (read-keyset "account-keyset"))`,
envData: {
"account-keyset": {
keys: [
// Drop the k:
newAccount.substr(2)
],
pred: "keys-all"
},
},
meta: {
creationTime: creationTime(),
ttl: 28000,
gasLimit: 600,
chainId: CHAIN_ID,
gasPrice: 0.0000001,
sender: KEY_PAIR.publicKey
}
};
const response = await Pact.fetch.send(cmd, API_HOST);
if (!response.requestKeys)
{
return console.error(response)
}
console.log(`Request key: ${response.requestKeys[0]}`);
console.log("Transaction pending...");
const txResult = await Pact.fetch.listen(
{ listen: response.requestKeys[0] },
API_HOST
);
console.log("Transaction mined!");
console.log(txResult);
}
await getBalance(`sender00`) // OK
await createAccount(`testaccount`)
A:
I changed the sender in cmd.meta.sender to sender00 and it worked.
Public keys and account names are different things I belive.
|
Kadena Pact Create Account Fails
|
Hi Kadena Pact developers,
I'm following https://docs.kadena.io/build/frontend/pact-lang-api-cookbook#create-account to create coin accounts.
getBalance(`sender00`) returns
{
"gas": 20,
"result": {
"status": "success",
"data": 99998999.9999446
},
"reqKey": "AnmQHR9ciGruzwaV2LksjFANS8Mbr5UBuj26d2w4TLE",
"logs": "wsATyGqckuIvlm89hhd2j4t6RMkCrcwJe_oeCYr7Th8",
"metaData": {
"publicMeta": {
"creationTime": 1670018678,
"ttl": 28000,
"gasLimit": 600,
"chainId": "0",
"gasPrice": 1e-7,
"sender": "368820f80c324bbc7c2b0610688a7da43e39f91d118732671cd9c7500ff43cca"
},
"blockTime": 1670018669855184,
"prevBlockHash": "g5bNGUcMPQYC4klTi-D0QhsMBIT9oggVa_-Ea8hyQq4",
"blockHeight": 1964
},
"continuation": null,
"txId": null
}
I want to create another account using sender00 keypairs, however it fails w/ error message
Validation failed for hash "iu9bake1-nzhfQuYoRCM_LggDBenBLDWjGf6o7d00kY": Attempt to buy gas failed with: : Failure: Tx Failed: read: row not found: 368820f80c324bbc7c2b0610688a7da43e39f91d118732671cd9c7500ff43cca
Here is the whole script and the .env file
SENDER00_PUBLIC=368820f80c324bbc7c2b0610688a7da43e39f91d118732671cd9c7500ff43cca
SENDER00_SECRET=251a920c403ae8c8f65f59142316af3c82b631fba46ddea92ee8c95035bd2898
Script file
import * as dotenv from 'dotenv'
dotenv.config()
import Pact from 'pact-lang-api';
const GAS_PRICE = 0.0000001;
const GAS_LIMIT = 400;
const TTL = 28000;
const NETWORK_ID = 'development'//'testnet04';
const CHAIN_ID = '0';
const API_HOST = `http://localhost:8080/chainweb/0.0/${NETWORK_ID}/chain/${CHAIN_ID}/pact`;
const creationTime = () => Math.round((new Date).getTime() / 1000) - 15;
async function getBalance(account) {
const cmd = {
networkId: NETWORK_ID,
keyPairs: KEY_PAIR,
pactCode: `(coin.get-balance "${account}")`,
envData: {},
meta: {
creationTime: creationTime(),
ttl: 28000,
gasLimit: 600,
chainId: CHAIN_ID,
gasPrice: 0.0000001,
sender: KEY_PAIR.publicKey
}
};
const result = await Pact.fetch.local(cmd, API_HOST);
console.log(JSON.stringify(result, null, 2));
}
const KEY_PAIR = {
'publicKey': `${process.env.SENDER00_PUBLIC}`,
'secretKey': `${process.env.SENDER00_SECRET}`
}
async function createAccount(newAccount) {
const cmd = {
networkId: NETWORK_ID,
keyPairs: KEY_PAIR,
pactCode: `(coin.create-account "${newAccount}" (read-keyset "account-keyset"))`,
envData: {
"account-keyset": {
keys: [
// Drop the k:
newAccount.substr(2)
],
pred: "keys-all"
},
},
meta: {
creationTime: creationTime(),
ttl: 28000,
gasLimit: 600,
chainId: CHAIN_ID,
gasPrice: 0.0000001,
sender: KEY_PAIR.publicKey
}
};
const response = await Pact.fetch.send(cmd, API_HOST);
if (!response.requestKeys)
{
return console.error(response)
}
console.log(`Request key: ${response.requestKeys[0]}`);
console.log("Transaction pending...");
const txResult = await Pact.fetch.listen(
{ listen: response.requestKeys[0] },
API_HOST
);
console.log("Transaction mined!");
console.log(txResult);
}
await getBalance(`sender00`) // OK
await createAccount(`testaccount`)
|
[
"I changed the sender in cmd.meta.sender to sender00 and it worked.\nPublic keys and account names are different things I belive.\n"
] |
[
0
] |
[] |
[] |
[
"kadena",
"pact_lang"
] |
stackoverflow_0074662050_kadena_pact_lang.txt
|
Q:
disable mouse wheel click
how can I disable mouse a wheel click only in a certain div?
I want to use the scroll function normally, but I don't want to switch the cursor to that "quick scroll" when someone clicks the mouse wheel.
I tried this, but it has changed nothing
$(document).on('click', function(e){
if(e.which == 2){
e.preventDefault(); //stop default click action from mousewheel
}
});
A:
To disable the mouse wheel click on a certain div in JavaScript, you can add an event listener for the mousedown event to the div element. In the event listener function, you can prevent the default behavior of the mouse wheel click using the preventDefault() method. Here is an example:
const div = document.querySelector('#my-div');
div.addEventListener('mousedown', function(event) {
if (event.which === 2) { // Check if the middle mouse button was clicked
event.preventDefault(); // Prevent the default behavior
}
});
Keep in mind that this will only prevent the default behavior of the mouse wheel click, but the scroll event will still be triggered. This means that the div will still be able to scroll if the user uses the mouse wheel or if they use the scroll bar. If you want to completely disable the scroll function, you can set the overflow property of the div to "hidden" or "auto" to prevent the div from scrolling.
const div = document.querySelector('#my-div');
div.style.overflow = 'hidden'; // Set the overflow property to prevent scrolling
|
disable mouse wheel click
|
how can I disable mouse a wheel click only in a certain div?
I want to use the scroll function normally, but I don't want to switch the cursor to that "quick scroll" when someone clicks the mouse wheel.
I tried this, but it has changed nothing
$(document).on('click', function(e){
if(e.which == 2){
e.preventDefault(); //stop default click action from mousewheel
}
});
|
[
"To disable the mouse wheel click on a certain div in JavaScript, you can add an event listener for the mousedown event to the div element. In the event listener function, you can prevent the default behavior of the mouse wheel click using the preventDefault() method. Here is an example:\nconst div = document.querySelector('#my-div');\ndiv.addEventListener('mousedown', function(event) {\n if (event.which === 2) { // Check if the middle mouse button was clicked\n event.preventDefault(); // Prevent the default behavior\n }\n});\n\nKeep in mind that this will only prevent the default behavior of the mouse wheel click, but the scroll event will still be triggered. This means that the div will still be able to scroll if the user uses the mouse wheel or if they use the scroll bar. If you want to completely disable the scroll function, you can set the overflow property of the div to \"hidden\" or \"auto\" to prevent the div from scrolling.\nconst div = document.querySelector('#my-div');\ndiv.style.overflow = 'hidden'; // Set the overflow property to prevent scrolling\n\n"
] |
[
2
] |
[] |
[] |
[
"css",
"javascript"
] |
stackoverflow_0074662066_css_javascript.txt
|
Q:
Aggregate is returning (some) duplicate items with same ID
Our Mongo replication servers experienced a crash because of to many traffic and a query that wasn't optimized. This all has been solved and everything is working correctly, we just have one problem we can't figure out.
While our primary server crashed, some items got added. That went ok, but the weird thing is that these items that where added in the crash window are now returned double in our aggregate queries.
If I'm going a find() query, it doesn't show up. How is this even possible?
Here's our aggregate query:
`
[
{
'$match': { is_active: true, is_removed: { $ne: true }, _id: { $in: ['390195122352164864'] } }
},
{ '$sort': { 'list_ranking.default': -1 } },
{ '$limit': 48 },
{
'$lookup': {
from: 'items',
localField: 'parent_id',
foreignField: '_id',
as: 'parent'
}
},
{
'$lookup': {
from: 'items_type',
localField: 'item_type',
foreignField: 'key',
as: 'type'
}
},
{
'$lookup': {
from: 'items_rarity',
localField: 'item_rarity',
foreignField: 'key',
as: 'rarity'
}
},
{
'$lookup': {
from: 'items_serie',
localField: 'item_serie',
foreignField: 'key',
as: 'serie'
}
},
{
'$lookup': {
from: 'items_set',
localField: 'item_set',
foreignField: 'key',
as: 'sets'
}
},
{
'$lookup': {
from: 'items_introduction',
localField: 'item_introduction',
foreignField: 'key',
as: 'introduction'
}
},
{
'$lookup': {
from: 'items_background',
localField: 'item_background',
foreignField: 'key',
as: 'background'
}
},
{
'$lookup': {
from: 'items_set',
localField: 'parent.item_set',
foreignField: 'key',
as: 'parentSets'
}
},
{ '$unwind': { path: '$parent', preserveNullAndEmptyArrays: true } },
{ '$unwind': { path: '$type', preserveNullAndEmptyArrays: true } },
{ '$unwind': { path: '$rarity', preserveNullAndEmptyArrays: true } },
{ '$unwind': { path: '$serie', preserveNullAndEmptyArrays: true } },
{ '$unwind': { path: '$sets', preserveNullAndEmptyArrays: true } },
{
'$unwind': { path: '$introduction', preserveNullAndEmptyArrays: true }
},
{
'$unwind': { path: '$background', preserveNullAndEmptyArrays: true }
},
{
'$unwind': { path: '$parentSets', preserveNullAndEmptyArrays: true }
},
{
'$project': {
slug: 1,
'parent.slug': 1,
name: 1,
'parent.name': 1,
description: 1,
'parent.description': 1,
key: 1,
'parent.key': 1,
icon: 1,
'parent.icon': 1,
featured: 1,
'parent.featured': 1,
media_id: 1,
'parent.media_id': 1,
media_type: 1,
'parent.media_type': 1,
media_uploaded_at: 1,
'parent.media_uploaded_at': 1,
media_processed_at: 1,
'parent.media_processed_at': 1,
list_order: 1,
'parent.list_order': 1,
list_ranking: 1,
'parent.list_ranking': 1,
rating_good: 1,
'parent.rating_good': 1,
rating_bad: 1,
'parent.rating_bad': 1,
estimated_available_combos: 1,
'parent.estimated_available_combos': 1,
obtained_type: 1,
'parent.obtained_type': 1,
obtained_value: 1,
'parent.obtained_value': 1,
v3_itemid: 1,
'parent.v3_itemid': 1,
v3_itemkey: 1,
'parent.v3_itemkey': 1,
v3_mediaid: 1,
'parent.v3_mediaid': 1,
is_active: 1,
'parent.is_active': 1,
is_released: 1,
'parent.is_released': 1,
is_removed: 1,
'parent.is_removed': 1,
modified_at: 1,
'parent.modified_at': 1,
created_at: 1,
'parent.created_at': 1,
'type.slug': 1,
'type.name': 1,
'type.key': 1,
'rarity.slug': 1,
'rarity.name': 1,
'rarity.key': 1,
'rarity.color': 1,
'serie.slug': 1,
'serie.name': 1,
'serie.key': 1,
'serie.color': 1,
'sets.slug': 1,
'sets.name': 1,
'sets.key': 1,
'sets.is_active': 1,
'parentSets.slug': 1,
'parentSets.name': 1,
'parentSets.key': 1,
'parentSets.is_active': 1,
'background.slug': 1,
'background.name': 1,
'background.key': 1,
'introduction.slug': 1,
'introduction.name': 1,
'introduction.key': 1,
'introduction.chapter': 1,
'introduction.season': 1,
'parent._id': 1
}
}
]
`
And this is what we're getting back:
`
[
{
_id: '390195122352164864',
slug: 'ffc-neymar-jr',
name: 'FFC Neymar Jr',
description: 'Knows a thing or two.',
key: 'character_redoasisgooseberry',
icon: 'b74a4677-e2ba-4f25-9e92-25756dafc9d2',
featured: 'b422fadb-6960-4122-9d3d-37cbc06501e8',
media_id: '04ddd281-309e-40e5-811d-767e52d84847',
media_type: 'video/mp4',
media_uploaded_at: null,
media_processed_at: 2022-12-02T07:34:43.371Z,
obtained_type: 'vbucks',
obtained_value: '1200',
rating_good: 101,
rating_bad: 6,
list_order: 6396,
list_ranking: {
default: 6807,
last_1_hr: 534,
last_24_hrs: 6807,
last_7_days: 7682
},
estimated_available_combos: 6,
is_released: true,
is_active: true,
is_removed: false,
modified_at: null,
created_at: 2022-11-30T17:36:06.643Z,
type: { slug: 'outfit', name: 'Outfit', key: 'AthenaCharacter' },
rarity: {
slug: 'rare',
name: 'Rare',
key: 'EFortRarity::Rare',
color: '28C4F2'
},
serie: {
slug: 'icon',
name: 'Icon Series',
key: 'CreatorCollabSeries',
color: '5DD6EA'
},
sets: {
is_active: false,
slug: 'set01',
name: 'Fortnite Football Club',
key: 'SphereKickGroup'
},
introduction: {
slug: 'chapter-3-season-4',
name: 'Introduced in Chapter 3, Season 4.',
key: 22,
chapter: '3',
season: '4'
}
},
{
_id: '390195122352164864',
slug: 'ffc-neymar-jr',
name: 'FFC Neymar Jr',
description: 'Knows a thing or two.',
key: 'character_redoasisgooseberry',
icon: 'b74a4677-e2ba-4f25-9e92-25756dafc9d2',
featured: 'b422fadb-6960-4122-9d3d-37cbc06501e8',
media_id: '04ddd281-309e-40e5-811d-767e52d84847',
media_type: 'video/mp4',
media_uploaded_at: null,
media_processed_at: 2022-12-02T07:34:43.371Z,
obtained_type: 'vbucks',
obtained_value: '1200',
rating_good: 101,
rating_bad: 6,
list_order: 6396,
list_ranking: {
default: 6807,
last_1_hr: 534,
last_24_hrs: 6807,
last_7_days: 7682
},
estimated_available_combos: 6,
is_released: true,
is_active: true,
is_removed: false,
modified_at: null,
created_at: 2022-11-30T17:36:06.643Z,
type: { slug: 'outfit', name: 'Outfit', key: 'AthenaCharacter' },
rarity: {
slug: 'rare',
name: 'Rare',
key: 'EFortRarity::Rare',
color: '28C4F2'
},
serie: {
slug: 'icon',
name: 'Icon Series',
key: 'CreatorCollabSeries',
color: '5DD6EA'
},
sets: {
slug: 'set01',
name: 'Fortnite Football Club',
key: 'SphereKickGroup',
is_active: false
},
introduction: {
slug: 'chapter-3-season-4',
name: 'Introduced in Chapter 3, Season 4.',
key: 22,
chapter: '3',
season: '4'
}
}
]
`
How is this possible?
Thanks,
Sam
Tried to rebuild indexes, restarted all Mongo instances, restarted the api servers, removed the items and added them back.
A:
This is the expected outcome when using $unwind as if there is more than one matching document it will essentially duplicate the whole document, replacing the array with each item in your array as an object.
If you're only expecting a single document to be returned it sounds like the issue is caused by there being more than one matching document from a $lookup.
It could be caused by any one of the lookups, but from the output you posted the two sets are slightly different so I would start by searching items_set to see if there is more than one matching document. If there is then deleting the duplicate should solve the issue.
db.items_set.find({ key: 'SphereKickGroup' })
|
Aggregate is returning (some) duplicate items with same ID
|
Our Mongo replication servers experienced a crash because of to many traffic and a query that wasn't optimized. This all has been solved and everything is working correctly, we just have one problem we can't figure out.
While our primary server crashed, some items got added. That went ok, but the weird thing is that these items that where added in the crash window are now returned double in our aggregate queries.
If I'm going a find() query, it doesn't show up. How is this even possible?
Here's our aggregate query:
`
[
{
'$match': { is_active: true, is_removed: { $ne: true }, _id: { $in: ['390195122352164864'] } }
},
{ '$sort': { 'list_ranking.default': -1 } },
{ '$limit': 48 },
{
'$lookup': {
from: 'items',
localField: 'parent_id',
foreignField: '_id',
as: 'parent'
}
},
{
'$lookup': {
from: 'items_type',
localField: 'item_type',
foreignField: 'key',
as: 'type'
}
},
{
'$lookup': {
from: 'items_rarity',
localField: 'item_rarity',
foreignField: 'key',
as: 'rarity'
}
},
{
'$lookup': {
from: 'items_serie',
localField: 'item_serie',
foreignField: 'key',
as: 'serie'
}
},
{
'$lookup': {
from: 'items_set',
localField: 'item_set',
foreignField: 'key',
as: 'sets'
}
},
{
'$lookup': {
from: 'items_introduction',
localField: 'item_introduction',
foreignField: 'key',
as: 'introduction'
}
},
{
'$lookup': {
from: 'items_background',
localField: 'item_background',
foreignField: 'key',
as: 'background'
}
},
{
'$lookup': {
from: 'items_set',
localField: 'parent.item_set',
foreignField: 'key',
as: 'parentSets'
}
},
{ '$unwind': { path: '$parent', preserveNullAndEmptyArrays: true } },
{ '$unwind': { path: '$type', preserveNullAndEmptyArrays: true } },
{ '$unwind': { path: '$rarity', preserveNullAndEmptyArrays: true } },
{ '$unwind': { path: '$serie', preserveNullAndEmptyArrays: true } },
{ '$unwind': { path: '$sets', preserveNullAndEmptyArrays: true } },
{
'$unwind': { path: '$introduction', preserveNullAndEmptyArrays: true }
},
{
'$unwind': { path: '$background', preserveNullAndEmptyArrays: true }
},
{
'$unwind': { path: '$parentSets', preserveNullAndEmptyArrays: true }
},
{
'$project': {
slug: 1,
'parent.slug': 1,
name: 1,
'parent.name': 1,
description: 1,
'parent.description': 1,
key: 1,
'parent.key': 1,
icon: 1,
'parent.icon': 1,
featured: 1,
'parent.featured': 1,
media_id: 1,
'parent.media_id': 1,
media_type: 1,
'parent.media_type': 1,
media_uploaded_at: 1,
'parent.media_uploaded_at': 1,
media_processed_at: 1,
'parent.media_processed_at': 1,
list_order: 1,
'parent.list_order': 1,
list_ranking: 1,
'parent.list_ranking': 1,
rating_good: 1,
'parent.rating_good': 1,
rating_bad: 1,
'parent.rating_bad': 1,
estimated_available_combos: 1,
'parent.estimated_available_combos': 1,
obtained_type: 1,
'parent.obtained_type': 1,
obtained_value: 1,
'parent.obtained_value': 1,
v3_itemid: 1,
'parent.v3_itemid': 1,
v3_itemkey: 1,
'parent.v3_itemkey': 1,
v3_mediaid: 1,
'parent.v3_mediaid': 1,
is_active: 1,
'parent.is_active': 1,
is_released: 1,
'parent.is_released': 1,
is_removed: 1,
'parent.is_removed': 1,
modified_at: 1,
'parent.modified_at': 1,
created_at: 1,
'parent.created_at': 1,
'type.slug': 1,
'type.name': 1,
'type.key': 1,
'rarity.slug': 1,
'rarity.name': 1,
'rarity.key': 1,
'rarity.color': 1,
'serie.slug': 1,
'serie.name': 1,
'serie.key': 1,
'serie.color': 1,
'sets.slug': 1,
'sets.name': 1,
'sets.key': 1,
'sets.is_active': 1,
'parentSets.slug': 1,
'parentSets.name': 1,
'parentSets.key': 1,
'parentSets.is_active': 1,
'background.slug': 1,
'background.name': 1,
'background.key': 1,
'introduction.slug': 1,
'introduction.name': 1,
'introduction.key': 1,
'introduction.chapter': 1,
'introduction.season': 1,
'parent._id': 1
}
}
]
`
And this is what we're getting back:
`
[
{
_id: '390195122352164864',
slug: 'ffc-neymar-jr',
name: 'FFC Neymar Jr',
description: 'Knows a thing or two.',
key: 'character_redoasisgooseberry',
icon: 'b74a4677-e2ba-4f25-9e92-25756dafc9d2',
featured: 'b422fadb-6960-4122-9d3d-37cbc06501e8',
media_id: '04ddd281-309e-40e5-811d-767e52d84847',
media_type: 'video/mp4',
media_uploaded_at: null,
media_processed_at: 2022-12-02T07:34:43.371Z,
obtained_type: 'vbucks',
obtained_value: '1200',
rating_good: 101,
rating_bad: 6,
list_order: 6396,
list_ranking: {
default: 6807,
last_1_hr: 534,
last_24_hrs: 6807,
last_7_days: 7682
},
estimated_available_combos: 6,
is_released: true,
is_active: true,
is_removed: false,
modified_at: null,
created_at: 2022-11-30T17:36:06.643Z,
type: { slug: 'outfit', name: 'Outfit', key: 'AthenaCharacter' },
rarity: {
slug: 'rare',
name: 'Rare',
key: 'EFortRarity::Rare',
color: '28C4F2'
},
serie: {
slug: 'icon',
name: 'Icon Series',
key: 'CreatorCollabSeries',
color: '5DD6EA'
},
sets: {
is_active: false,
slug: 'set01',
name: 'Fortnite Football Club',
key: 'SphereKickGroup'
},
introduction: {
slug: 'chapter-3-season-4',
name: 'Introduced in Chapter 3, Season 4.',
key: 22,
chapter: '3',
season: '4'
}
},
{
_id: '390195122352164864',
slug: 'ffc-neymar-jr',
name: 'FFC Neymar Jr',
description: 'Knows a thing or two.',
key: 'character_redoasisgooseberry',
icon: 'b74a4677-e2ba-4f25-9e92-25756dafc9d2',
featured: 'b422fadb-6960-4122-9d3d-37cbc06501e8',
media_id: '04ddd281-309e-40e5-811d-767e52d84847',
media_type: 'video/mp4',
media_uploaded_at: null,
media_processed_at: 2022-12-02T07:34:43.371Z,
obtained_type: 'vbucks',
obtained_value: '1200',
rating_good: 101,
rating_bad: 6,
list_order: 6396,
list_ranking: {
default: 6807,
last_1_hr: 534,
last_24_hrs: 6807,
last_7_days: 7682
},
estimated_available_combos: 6,
is_released: true,
is_active: true,
is_removed: false,
modified_at: null,
created_at: 2022-11-30T17:36:06.643Z,
type: { slug: 'outfit', name: 'Outfit', key: 'AthenaCharacter' },
rarity: {
slug: 'rare',
name: 'Rare',
key: 'EFortRarity::Rare',
color: '28C4F2'
},
serie: {
slug: 'icon',
name: 'Icon Series',
key: 'CreatorCollabSeries',
color: '5DD6EA'
},
sets: {
slug: 'set01',
name: 'Fortnite Football Club',
key: 'SphereKickGroup',
is_active: false
},
introduction: {
slug: 'chapter-3-season-4',
name: 'Introduced in Chapter 3, Season 4.',
key: 22,
chapter: '3',
season: '4'
}
}
]
`
How is this possible?
Thanks,
Sam
Tried to rebuild indexes, restarted all Mongo instances, restarted the api servers, removed the items and added them back.
|
[
"This is the expected outcome when using $unwind as if there is more than one matching document it will essentially duplicate the whole document, replacing the array with each item in your array as an object.\nIf you're only expecting a single document to be returned it sounds like the issue is caused by there being more than one matching document from a $lookup.\nIt could be caused by any one of the lookups, but from the output you posted the two sets are slightly different so I would start by searching items_set to see if there is more than one matching document. If there is then deleting the duplicate should solve the issue.\ndb.items_set.find({ key: 'SphereKickGroup' })\n\n"
] |
[
1
] |
[] |
[] |
[
"mongodb",
"mongoose"
] |
stackoverflow_0074661634_mongodb_mongoose.txt
|
Q:
Using I18n in plain JS
I'm working on a React project, which I added internationalization from i18nexus, and i'm trying to use the translation in a plain JS file.
index.js
`
import React, { Suspense } from "react";
import { BrowserRouter } from "react-router-dom";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "./i18n.js";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<React.StrictMode>
<Suspense fallback="loading">
<App />
</Suspense>
</React.StrictMode>
</BrowserRouter>
);
reportWebVitals();
`
i18n.js
`
import i18next from "i18next";
import HttpBackend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
const apiKey = "sQeJnBmSuGryd28mX8s5mQ";
const loadPath = `https://api.i18nexus.com/project_resources/translations/{{lng}}/{{ns}}.json?api_key=${apiKey}`;
i18next
.use(HttpBackend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en",
ns: ["default"],
defaultNS: "default",
supportedLngs: ["en", "fr"],
backend: {
loadPath: loadPath
}
});
export default i18next;
`
Data.js
`
import i18next from "./i18n.js";
export const NavigationMenu = [
{
id: 1,
title: "home",
text: i18next.t("menu_home"),
path: "/"
},
{
id: 2,
title: "shop",
text: i18next.t("menu_shop"),
path: "/shop"
}
];
`
and this is where i want to map my data :
`
import React from "react";
import "./Header.css";
import { NavigationMenu } from "../Data.js";
function Header() {
return (
<div className="header">
<div className="header__menu">
<ul>
{NavigationMenu.map(item => (
<li>{item.text}</li>
))}
</ul>
</div>
</div>
);
}
export default Header;
`
Hope you understood the assignement, and thank you for you help.
I'm trying to add i18n translations to a plain JS file and then use them in a React component by maping throught them.
A:
i18next needs to finish loading the translations before you define NavigationMenu.
The easiest way is to render the translation in the component:
export const NavigationMenu = [
{
id: 1,
title: "home",
text: "menu_home",
path: "/"
},
{
id: 2,
title: "shop",
text: "menu_shop",
path: "/shop"
}
];
import React from "react";
import "./Header.css";
import { NavigationMenu } from "../Data.js";
import { useTranslation } from "react-i18next";
function Header() {
const { t } = useTranslation();
return (
<div className="header">
<div className="header__menu">
<ul>
{NavigationMenu.map(item => (
<li>{t(item.text)}</li>
))}
</ul>
</div>
</div>
);
}
export default Header;
|
Using I18n in plain JS
|
I'm working on a React project, which I added internationalization from i18nexus, and i'm trying to use the translation in a plain JS file.
index.js
`
import React, { Suspense } from "react";
import { BrowserRouter } from "react-router-dom";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "./i18n.js";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
<React.StrictMode>
<Suspense fallback="loading">
<App />
</Suspense>
</React.StrictMode>
</BrowserRouter>
);
reportWebVitals();
`
i18n.js
`
import i18next from "i18next";
import HttpBackend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
const apiKey = "sQeJnBmSuGryd28mX8s5mQ";
const loadPath = `https://api.i18nexus.com/project_resources/translations/{{lng}}/{{ns}}.json?api_key=${apiKey}`;
i18next
.use(HttpBackend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: "en",
ns: ["default"],
defaultNS: "default",
supportedLngs: ["en", "fr"],
backend: {
loadPath: loadPath
}
});
export default i18next;
`
Data.js
`
import i18next from "./i18n.js";
export const NavigationMenu = [
{
id: 1,
title: "home",
text: i18next.t("menu_home"),
path: "/"
},
{
id: 2,
title: "shop",
text: i18next.t("menu_shop"),
path: "/shop"
}
];
`
and this is where i want to map my data :
`
import React from "react";
import "./Header.css";
import { NavigationMenu } from "../Data.js";
function Header() {
return (
<div className="header">
<div className="header__menu">
<ul>
{NavigationMenu.map(item => (
<li>{item.text}</li>
))}
</ul>
</div>
</div>
);
}
export default Header;
`
Hope you understood the assignement, and thank you for you help.
I'm trying to add i18n translations to a plain JS file and then use them in a React component by maping throught them.
|
[
"i18next needs to finish loading the translations before you define NavigationMenu.\nThe easiest way is to render the translation in the component:\nexport const NavigationMenu = [\n {\n id: 1,\n title: \"home\",\n text: \"menu_home\",\n path: \"/\"\n },\n {\n id: 2,\n title: \"shop\",\n text: \"menu_shop\",\n path: \"/shop\"\n }\n];\n\nimport React from \"react\";\nimport \"./Header.css\";\nimport { NavigationMenu } from \"../Data.js\";\nimport { useTranslation } from \"react-i18next\";\n\nfunction Header() {\n const { t } = useTranslation();\n\n return (\n <div className=\"header\">\n <div className=\"header__menu\">\n <ul>\n {NavigationMenu.map(item => (\n <li>{t(item.text)}</li>\n ))}\n </ul>\n </div>\n </div>\n );\n}\n\nexport default Header;\n\n"
] |
[
0
] |
[] |
[] |
[
"i18next",
"reactjs"
] |
stackoverflow_0074463012_i18next_reactjs.txt
|
Q:
Replacing WHERE clause with OR by using INNER JOIN
I have the following query: that is trying to get pt_ids that have certain diagnosis codes OR certain outcome_codes. I have accounted for these conditions by including the specific codes I'd like in the WHERE clause. However, I would like to know if I can also do this using in INNER JOIN.
SELECT DISTINCT
pt_id
FROM #df
WHERE flag <> 1
AND (diagnosis IN
(
SELECT Code
FROM #df_codes
WHERE code_id = '20'
)
OR outcome_code IN
(
SELECT Code
FROM #df_codes
WHERE code_id = '25'
));
The above code is taking quite a while to run and I am wondering if writing it in the following way 1) is appropriate/viable and 2) will leader to a faster run time. I am essentially trying to join #df with #df_codes on either Code = diagnosis OR code = outcome_code
My Solution
SELECT DISTINCT
pt_id
FROM #df a
JOIN (select * from #df_codes where code_id = '20')b ON a.diagnosis = b.Code OR
(select * from #df_codes where code_id = '25')c ON a.outcome_code = c.Code
WHERE flag <> 1
A:
I would do it like this:
SELECT DISTINCT pt_id
FROM #df
INNER JOIN #df_codes ON (
#df.diagnosis = #df_codes.code
AND #df_codes.code_id = '20'
)
OR (
#df.outcome_code = #df_codes.code
AND #df_codes.code_id = '25'
)
WHERE flag <> 1
A:
Just a rough suggestion to create small temp tables and join it back to main table. I would suggest use the CTE or original table query and do following:
SELECT Code
into #x
FROM #df_codes
WHERE code_id = '20'
SELECT Code
into #y
FROM #df_codes
WHERE code_id = '25'
SELECT
pt_id
FROM #df
join #x x on x.Code = diagnosis
WHERE flag <> 1
Union
SELECT
pt_id
FROM #df
join #y y on y.Code = diagnosis
WHERE flag <> 1
Just replace #df by a CTE that way you can use the existing indexes.
|
Replacing WHERE clause with OR by using INNER JOIN
|
I have the following query: that is trying to get pt_ids that have certain diagnosis codes OR certain outcome_codes. I have accounted for these conditions by including the specific codes I'd like in the WHERE clause. However, I would like to know if I can also do this using in INNER JOIN.
SELECT DISTINCT
pt_id
FROM #df
WHERE flag <> 1
AND (diagnosis IN
(
SELECT Code
FROM #df_codes
WHERE code_id = '20'
)
OR outcome_code IN
(
SELECT Code
FROM #df_codes
WHERE code_id = '25'
));
The above code is taking quite a while to run and I am wondering if writing it in the following way 1) is appropriate/viable and 2) will leader to a faster run time. I am essentially trying to join #df with #df_codes on either Code = diagnosis OR code = outcome_code
My Solution
SELECT DISTINCT
pt_id
FROM #df a
JOIN (select * from #df_codes where code_id = '20')b ON a.diagnosis = b.Code OR
(select * from #df_codes where code_id = '25')c ON a.outcome_code = c.Code
WHERE flag <> 1
|
[
"I would do it like this:\nSELECT DISTINCT pt_id\nFROM #df\nINNER JOIN #df_codes ON (\n #df.diagnosis = #df_codes.code\n AND #df_codes.code_id = '20'\n )\n OR (\n #df.outcome_code = #df_codes.code\n AND #df_codes.code_id = '25'\n )\nWHERE flag <> 1\n\n",
"Just a rough suggestion to create small temp tables and join it back to main table. I would suggest use the CTE or original table query and do following:\nSELECT Code\ninto #x\nFROM #df_codes\nWHERE code_id = '20'\n\nSELECT Code\ninto #y\nFROM #df_codes\nWHERE code_id = '25'\n\n\nSELECT\npt_id\nFROM #df\njoin #x x on x.Code = diagnosis \nWHERE flag <> 1\nUnion\nSELECT\npt_id\nFROM #df\njoin #y y on y.Code = diagnosis \nWHERE flag <> 1\n\nJust replace #df by a CTE that way you can use the existing indexes.\n"
] |
[
0,
0
] |
[
"Use EXISTS instead:\nSELECT DISTINCT\n d.pt_id\n FROM #df d\n WHERE flag <> 1\n AND EXISTS (SELECT *\n FROM #df_codes c\n WHERE (c.code = d.diagnosis AND c.code_id = '20')\n OR (c.code = d.outcome_code AND c.code_id = '25');\n\nIf #df lists each patient a single time - then you don't need the DISTINCT. If you try using a join and a patient has both then you would get 2 rows - and then use DISTINCT to eliminate the 'duplicates'.\n"
] |
[
-1
] |
[
"inner_join",
"sql",
"sql_server",
"where_clause"
] |
stackoverflow_0074661428_inner_join_sql_sql_server_where_clause.txt
|
Q:
Python: Sum up list of objects
I am working with a number of custom classes X that have __add__(self), and when added together return another class, Y.
I often have iterables [of various sizes] of X, ex = [X1, X2, X3] that I would love to add together to get Y. However, sum(ex) throws an int error, because sum starts at 0 which can't be added to my class X.
Can someone please help me with an easy, pythonic way to do X1 + X2 + X3 ... of an interable, so I get Y...
Thanks!
Ps it’s a 3rd party class, X, so I can’t change it. It does have radd though.
My gut was that there was some way to do list comprehension? Like += on themselves
A:
You can specify the starting point for a sum by passing it as a parameter. For example, sum([1,2,3], 10) produces 16 (10 + 1 + 2 + 3), and sum([[1], [2], [3]], []) produces [1,2,3].
So if you pass an appropriate ("zero-like") X object as the second parameter to your sum, ie sum([x1, x2, x3,...], x0) you should get the results you're looking for
Some example code, per request. Given the following definitions:
class X:
def __init__(self, val):
self.val = val
def __add__(self, other):
return X(self.val + other.val)
def __repr__(self):
return "X({})".format(self.val)
class Y:
def __init__(self, val):
self.val = val
def __add__(self, other):
return X(self.val + other.val)
def __repr__(self):
return "Y({})".format(self.val)
I get the following results:
>>> sum([Y(1), Y(2), Y(3)], Y(0))
X(6)
>>> sum([Y(1), Y(2), Y(3)], Y(0))
X(6)
>>>
(note that Y returns an X object - but that the two objects' add methods are compatible, which may not be the case in the OP's situation)
|
Python: Sum up list of objects
|
I am working with a number of custom classes X that have __add__(self), and when added together return another class, Y.
I often have iterables [of various sizes] of X, ex = [X1, X2, X3] that I would love to add together to get Y. However, sum(ex) throws an int error, because sum starts at 0 which can't be added to my class X.
Can someone please help me with an easy, pythonic way to do X1 + X2 + X3 ... of an interable, so I get Y...
Thanks!
Ps it’s a 3rd party class, X, so I can’t change it. It does have radd though.
My gut was that there was some way to do list comprehension? Like += on themselves
|
[
"You can specify the starting point for a sum by passing it as a parameter. For example, sum([1,2,3], 10) produces 16 (10 + 1 + 2 + 3), and sum([[1], [2], [3]], []) produces [1,2,3].\nSo if you pass an appropriate (\"zero-like\") X object as the second parameter to your sum, ie sum([x1, x2, x3,...], x0) you should get the results you're looking for\nSome example code, per request. Given the following definitions:\nclass X: \n def __init__(self, val): \n self.val = val \n def __add__(self, other):\n return X(self.val + other.val) \n \n def __repr__(self): \n return \"X({})\".format(self.val) \n \nclass Y: \n def __init__(self, val): \n self.val = val \n def __add__(self, other):\n return X(self.val + other.val) \n \n def __repr__(self): \n return \"Y({})\".format(self.val) \n\n\nI get the following results:\n>>> sum([Y(1), Y(2), Y(3)], Y(0))\nX(6)\n>>> sum([Y(1), Y(2), Y(3)], Y(0))\nX(6)\n>>>\n\n(note that Y returns an X object - but that the two objects' add methods are compatible, which may not be the case in the OP's situation)\n"
] |
[
4
] |
[
"Assuming that you can add an X to a Y (i.e. __add__ is defined for Y and accepts an object of class X), then you can use\nreduce from functools, a generic way to apply an operation to a number of objects, either with or without a start value.\nfrom functools import reduce\n\nxes = [x1, x2, x3]\ny = reduce(lambda a,b: a+b, xes)\n\n",
"What if you did something like:\nY = [ex[0]=+X for x in ex[1:]][0]\n\nI haven’t tested it yet though, on mobile\n"
] |
[
-1,
-1
] |
[
"python"
] |
stackoverflow_0074661819_python.txt
|
Q:
why does numpy matrix multiply computation time increase by an order of magnitude at 100x100?
When computing A @ a where A is a random N by N matrix and a is a vector with N random elements using numpy the computation time jumps by an order of magnitude at N=100. Is there any particular reason for this? As a comparison the same operation using torch on the cpu has a more gradual increase
Tried it with python3.10 and 3.9 and 3.7 with the same behavior
Code used for generating numpy part of the plot:
import numpy as np
from tqdm.notebook import tqdm
import pandas as pd
import time
import sys
def sym(A):
return .5 * (A + A.T)
results = []
for n in tqdm(range(2, 500)):
for trial_idx in range(10):
A = sym(np.random.randn(n, n))
a = np.random.randn(n)
t = time.time()
for i in range(1000):
A @ a
t = time.time() - t
results.append({
'n': n,
'time': t,
'method': 'numpy',
})
results = pd.DataFrame(results)
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.semilogy(results.n.unique(), results.groupby('n').time.mean(), label="numpy")
ax.set_title(f'A @ a timimgs (1000 times)\nPython {sys.version.split(" ")[0]}')
ax.legend()
ax.set_xlabel('n')
ax.set_ylabel('avg. time')
Update
Adding
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
before ìmport numpy gives a more expected output, see this answer for details: https://stackoverflow.com/a/74662135/5043576
A:
numpy tries to use threads when multiplying matricies of size 100 or larger, and the default CBLAS implementation of threaded multiplication is ... sub optimal, as opposed to other backends like intel-MKL or ATLAS.
if you force it to use only 1 thread using the answers in this post you will get a continuous line for numpy performance.
|
why does numpy matrix multiply computation time increase by an order of magnitude at 100x100?
|
When computing A @ a where A is a random N by N matrix and a is a vector with N random elements using numpy the computation time jumps by an order of magnitude at N=100. Is there any particular reason for this? As a comparison the same operation using torch on the cpu has a more gradual increase
Tried it with python3.10 and 3.9 and 3.7 with the same behavior
Code used for generating numpy part of the plot:
import numpy as np
from tqdm.notebook import tqdm
import pandas as pd
import time
import sys
def sym(A):
return .5 * (A + A.T)
results = []
for n in tqdm(range(2, 500)):
for trial_idx in range(10):
A = sym(np.random.randn(n, n))
a = np.random.randn(n)
t = time.time()
for i in range(1000):
A @ a
t = time.time() - t
results.append({
'n': n,
'time': t,
'method': 'numpy',
})
results = pd.DataFrame(results)
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.semilogy(results.n.unique(), results.groupby('n').time.mean(), label="numpy")
ax.set_title(f'A @ a timimgs (1000 times)\nPython {sys.version.split(" ")[0]}')
ax.legend()
ax.set_xlabel('n')
ax.set_ylabel('avg. time')
Update
Adding
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
before ìmport numpy gives a more expected output, see this answer for details: https://stackoverflow.com/a/74662135/5043576
|
[
"numpy tries to use threads when multiplying matricies of size 100 or larger, and the default CBLAS implementation of threaded multiplication is ... sub optimal, as opposed to other backends like intel-MKL or ATLAS.\nif you force it to use only 1 thread using the answers in this post you will get a continuous line for numpy performance.\n"
] |
[
7
] |
[] |
[] |
[
"linear_algebra",
"numerical_computing",
"numpy",
"python"
] |
stackoverflow_0074661959_linear_algebra_numerical_computing_numpy_python.txt
|
Q:
Processing a Kafka message using KSQL that has a field that can be either an ARRAY or a STRUCT
I'm consuming a Kafka topic published by another team (so I have very limited influence over the message format). The message has a field that holds an ARRAY of STRUCTS (an array of objects), but if the array has only one value then it just holds that STRUCT (no array, just an object). I'm trying to transform the message using Confluent KSQL. Unfortunately, I cannot figure out how to do this.
For example:
{ "field": {...} } <-- STRUCT (single element)
{ "field": [ {...}, {...} ] } <-- ARRAY (multiple elements)
{ "field": [ {...}, {...}, {...} ] <-- ARRAY (multiple elements)
If I configure the field in my message schema as a STRUCT then all messages with multiple values error. If I configure the field in my message schema as an ARRAY then all messages with a single value error. I could create two streams and merge them, but then my error log will be polluted with irrelevant errors.
I've tried capturing this field as a STRING/VARCHAR which is fine and I can split the messages into two streams. If I do this, then I can parse the single value messages and extract the data I need, but I cannot figure out how to parse the multivalue messages. None of the KSQL JSON functions seem to allow parsing of JSON Arrays out of JSON Strings. I can use EXTRACTJSONFIELD() to extract a particular element of the array, but not all of the elements.
Am I missing something? Is there any way to handle this reasonably?
A:
In my experience, this is one use-case where KSQL just doesn't work. You would need to use Kafka Streams or a plain consumer to deserialize the event as a generic JSON type, then check object.get("field").isArray() or isObject(), and handle accordingly.
Even if you used a UDF in KSQL, the STREAM definition would be required to know ahead of time if you have field ARRAY<?> or field STRUCT<...>
|
Processing a Kafka message using KSQL that has a field that can be either an ARRAY or a STRUCT
|
I'm consuming a Kafka topic published by another team (so I have very limited influence over the message format). The message has a field that holds an ARRAY of STRUCTS (an array of objects), but if the array has only one value then it just holds that STRUCT (no array, just an object). I'm trying to transform the message using Confluent KSQL. Unfortunately, I cannot figure out how to do this.
For example:
{ "field": {...} } <-- STRUCT (single element)
{ "field": [ {...}, {...} ] } <-- ARRAY (multiple elements)
{ "field": [ {...}, {...}, {...} ] <-- ARRAY (multiple elements)
If I configure the field in my message schema as a STRUCT then all messages with multiple values error. If I configure the field in my message schema as an ARRAY then all messages with a single value error. I could create two streams and merge them, but then my error log will be polluted with irrelevant errors.
I've tried capturing this field as a STRING/VARCHAR which is fine and I can split the messages into two streams. If I do this, then I can parse the single value messages and extract the data I need, but I cannot figure out how to parse the multivalue messages. None of the KSQL JSON functions seem to allow parsing of JSON Arrays out of JSON Strings. I can use EXTRACTJSONFIELD() to extract a particular element of the array, but not all of the elements.
Am I missing something? Is there any way to handle this reasonably?
|
[
"In my experience, this is one use-case where KSQL just doesn't work. You would need to use Kafka Streams or a plain consumer to deserialize the event as a generic JSON type, then check object.get(\"field\").isArray() or isObject(), and handle accordingly.\nEven if you used a UDF in KSQL, the STREAM definition would be required to know ahead of time if you have field ARRAY<?> or field STRUCT<...>\n"
] |
[
1
] |
[] |
[] |
[
"apache_kafka",
"json",
"ksqldb"
] |
stackoverflow_0074646223_apache_kafka_json_ksqldb.txt
|
Q:
Which s3 policy types are supported in MINIO?
I am investigating minio. For now I have docker-compose with minio service and minio console is available for me. As I understand minio is kinda replacement for amazon s3.
I've found the following page:
http://awspolicygen.s3.amazonaws.com/policygen.html
So there are 5 policy types in amazon S3
IAM Policy
S3 Bucket Policy
SNS Topic Policy
VPC Endpoint Policy
SQS Queue Policy
Which of them are supported in minio ? Is there any abilities to configure it through minio console?
I can't find it in minio documentation for some reasons
A:
IAM Policy - you can read about them in detail https://min.io/docs/minio/linux/administration/identity-access-management.html
MinIO supports LDAP, Multiple IDP vendors, mTLS-based client authentication, and various other styles of access management - more than what AWS S3 does mostly to cater to all the on-prem needs.
|
Which s3 policy types are supported in MINIO?
|
I am investigating minio. For now I have docker-compose with minio service and minio console is available for me. As I understand minio is kinda replacement for amazon s3.
I've found the following page:
http://awspolicygen.s3.amazonaws.com/policygen.html
So there are 5 policy types in amazon S3
IAM Policy
S3 Bucket Policy
SNS Topic Policy
VPC Endpoint Policy
SQS Queue Policy
Which of them are supported in minio ? Is there any abilities to configure it through minio console?
I can't find it in minio documentation for some reasons
|
[
"IAM Policy - you can read about them in detail https://min.io/docs/minio/linux/administration/identity-access-management.html\nMinIO supports LDAP, Multiple IDP vendors, mTLS-based client authentication, and various other styles of access management - more than what AWS S3 does mostly to cater to all the on-prem needs.\n"
] |
[
1
] |
[] |
[] |
[
"access_control",
"amazon_iam",
"amazon_s3",
"minio"
] |
stackoverflow_0074597862_access_control_amazon_iam_amazon_s3_minio.txt
|
Q:
JS: Fibonacci as Class (Node.js)
I am learn some new algorithms lately.
I have a piece of functional code:
export function fibAlgo(n) {
if (n < 1) {
return 0;
}
var a = 0;
var b = 1;
for (var i = 1; i < n; ++i) {
var c = a + b;
a = b;
b = c;
}
return b;
}
export function fib(n) {
for (var i = 1; i < n; i++) {
console.log("f(" + i + ")" + "=", fibAlgo(i));
}
}
//Example: fib O(n)
that I wanna try to convert into a class like this:
class Fibonacci {
constructor(_a = 0, _b = 1) {
this.a = _a;
this.b = _b;
}
fibAlgo(n) {
if (n < 1) {
return 0;
}
for (var i = 1; i < n; ++i) {
var c = this.a + this.b;
this.a = this.b;
this.b = c;
}
return this.b;
}
calculate = (n) => {
for (var i = 1; i < n; i++) {
console.log("f(" + i + ")" + "=", this.fibAlgo(i));
}
//Example: fib O(n)
};
}
export { Fibonacci };
I call it inside my HTML like this:
<script type="module">
import { Fibonacci } from "./js/fibClass.js";
const Fibo = new Fibonacci();
Fibo.calculate(21);
</script>
These are my results:
This is clearly wrong. What did I miss?
BTW: I am trying to learn how to write proper classes.
My idea was basically:
having a,b as inital values defined in the constructor (0,1)
writing the calculate function that takes the actual instance def. value
tried to use setter, but since I dont use them in the instance, I used regular functions
another function that runs the calculation function inside the class and print the values
if you wanna any conceptual hints, feel free to tell me
A:
You didn't clear this.a and this.b between iterations
class Fibonacci {
constructor(_a = 0, _b = 1) {
this.a = _a;
this.b = _b;
}
fibAlgo(n) {
if (n < 1) {
return 0;
}
for (var i = 1; i < n; ++i) {
var c = this.a + this.b;
this.a = this.b;
this.b = c;
}
const x = this.b
this.b = 1
this.a = 0
return x;
}
calculate = (n) => {
for (var i = 1; i < n; i++) {
console.log("f(" + i + ")" + "=", this.fibAlgo(i));
}
};
}
const Fibo = new Fibonacci();
Fibo.calculate(21);
Using a class here would make sense if you would store values somewhere to make calculation faster
class Fibonacci {
constructor() {
this.values = [0, 1]
}
fibAlgo(n) {
if (n in this.values) {
return this.values[n]
}
let a = this.values[this.values.length - 2]
let b = this.values[this.values.length - 1]
for (let i = this.values.length; i <= n; i += 1) {
const c = a + b;
a = b;
b = c;
this.values.push(c)
}
return this.values[n];
}
calculate(n) {
for (let i = 1; i < n; i += 1) {
console.log("f(" + i + ")" + "=", this.fibAlgo(i));
}
};
}
const Fibo = new Fibonacci();
Fibo.calculate(21);
|
JS: Fibonacci as Class (Node.js)
|
I am learn some new algorithms lately.
I have a piece of functional code:
export function fibAlgo(n) {
if (n < 1) {
return 0;
}
var a = 0;
var b = 1;
for (var i = 1; i < n; ++i) {
var c = a + b;
a = b;
b = c;
}
return b;
}
export function fib(n) {
for (var i = 1; i < n; i++) {
console.log("f(" + i + ")" + "=", fibAlgo(i));
}
}
//Example: fib O(n)
that I wanna try to convert into a class like this:
class Fibonacci {
constructor(_a = 0, _b = 1) {
this.a = _a;
this.b = _b;
}
fibAlgo(n) {
if (n < 1) {
return 0;
}
for (var i = 1; i < n; ++i) {
var c = this.a + this.b;
this.a = this.b;
this.b = c;
}
return this.b;
}
calculate = (n) => {
for (var i = 1; i < n; i++) {
console.log("f(" + i + ")" + "=", this.fibAlgo(i));
}
//Example: fib O(n)
};
}
export { Fibonacci };
I call it inside my HTML like this:
<script type="module">
import { Fibonacci } from "./js/fibClass.js";
const Fibo = new Fibonacci();
Fibo.calculate(21);
</script>
These are my results:
This is clearly wrong. What did I miss?
BTW: I am trying to learn how to write proper classes.
My idea was basically:
having a,b as inital values defined in the constructor (0,1)
writing the calculate function that takes the actual instance def. value
tried to use setter, but since I dont use them in the instance, I used regular functions
another function that runs the calculation function inside the class and print the values
if you wanna any conceptual hints, feel free to tell me
|
[
"You didn't clear this.a and this.b between iterations\n\n\nclass Fibonacci {\n constructor(_a = 0, _b = 1) {\n this.a = _a;\n this.b = _b;\n }\n\n fibAlgo(n) {\n if (n < 1) {\n return 0;\n }\n\n for (var i = 1; i < n; ++i) {\n var c = this.a + this.b;\n this.a = this.b;\n this.b = c;\n }\n const x = this.b\n this.b = 1\n this.a = 0\n return x;\n }\n\n calculate = (n) => {\n for (var i = 1; i < n; i++) {\n console.log(\"f(\" + i + \")\" + \"=\", this.fibAlgo(i));\n }\n };\n}\n\nconst Fibo = new Fibonacci();\nFibo.calculate(21);\n\n\n\nUsing a class here would make sense if you would store values somewhere to make calculation faster\n\n\nclass Fibonacci {\n constructor() {\n this.values = [0, 1]\n }\n\n fibAlgo(n) {\n if (n in this.values) {\n return this.values[n]\n }\n\n let a = this.values[this.values.length - 2]\n let b = this.values[this.values.length - 1]\n\n for (let i = this.values.length; i <= n; i += 1) {\n const c = a + b;\n a = b;\n b = c;\n this.values.push(c)\n }\n\n return this.values[n];\n }\n\n calculate(n) {\n for (let i = 1; i < n; i += 1) {\n console.log(\"f(\" + i + \")\" + \"=\", this.fibAlgo(i));\n }\n };\n}\n\nconst Fibo = new Fibonacci();\nFibo.calculate(21);\n\n\n\n"
] |
[
0
] |
[] |
[] |
[
"class",
"fibonacci",
"javascript",
"node.js"
] |
stackoverflow_0074662081_class_fibonacci_javascript_node.js.txt
|
Q:
'jt' is not recognized as an internal or external command
Trying to change theme of Jupyter notebook but running into difficulty after successful install.
I run:
jt-t chesterish
'jt' is not recognized as an internal or external command, operable
program or batch file.
I know its related to not setting the environmental path somehow. But I have tried using SETX PATH but still didn't work and found not other solution thus far. I have before set up python so I can directly type "python" to get it on the command line but doesn't work for anything else like "jupyter".
A:
Even if ı have installed the jupyterthemes and upgrade it, ı have the same issue when ı write down the command (!jt -t [themename]) into one of the jupyter notebook's cells. The solution that ı have found is open up the Anaconda prompt and after installing the jupyterthemes, write the command (jt -t exampletheme) and restart the jupyter notebook.
A:
I had the same problem. I was using a conda environment with Python 3.7 installed. After I switched the kernel to the original standard "Python 3" kernel with Python 3.9 install, then the jt commands worked for me. Not sure if it was an environment issue or a python version issue.
|
'jt' is not recognized as an internal or external command
|
Trying to change theme of Jupyter notebook but running into difficulty after successful install.
I run:
jt-t chesterish
'jt' is not recognized as an internal or external command, operable
program or batch file.
I know its related to not setting the environmental path somehow. But I have tried using SETX PATH but still didn't work and found not other solution thus far. I have before set up python so I can directly type "python" to get it on the command line but doesn't work for anything else like "jupyter".
|
[
"Even if ı have installed the jupyterthemes and upgrade it, ı have the same issue when ı write down the command (!jt -t [themename]) into one of the jupyter notebook's cells. The solution that ı have found is open up the Anaconda prompt and after installing the jupyterthemes, write the command (jt -t exampletheme) and restart the jupyter notebook.\n",
"I had the same problem. I was using a conda environment with Python 3.7 installed. After I switched the kernel to the original standard \"Python 3\" kernel with Python 3.9 install, then the jt commands worked for me. Not sure if it was an environment issue or a python version issue.\n"
] |
[
1,
0
] |
[] |
[] |
[
"jupyter",
"path",
"python"
] |
stackoverflow_0054411892_jupyter_path_python.txt
|
Q:
How do I write a code that takes user input to form an array, and from that array the user decides if we should find the smallest or largest value?
I need to create a code using loops to ask for user input on certain values.
Of those values I need to ask the user if they want me to find the smallest or largest number or just end the program. If the number -1000 is entered in the program the program ends. Basically how do I link my menu of options to a the actual actions per option.Here's what I have so far.
numbersEntered = []
lengthNumbers = int(input("Please enter the length of your list/array:"))
print("Please enter your numbers individually:")
for x in range(lengthNumbers):
data=int(input())
numbersEntered.append(data)
def menu():
print("[A] Smallest")
print("[B] Largest")
print("[C] Quit")
menu()
Options=float(input(f"Please select either option A,B,or C:"))
optionA = min(numbersEntered)
optionB = max(numbersEntered)
optionC = quit
while numbersEntered != C:
if numbersEntered == A:
print("The smallest number is:", min(numbersEntered))
elif numbersEntered == B:
print("The largest number is:", max(numbersEntered) )
elif numbersEntered ==-1000:
print("Quit")
I tried a while loop to connect the menu to said action but that did not work and idk why. I am a beginner programer so I'm very new to this stuff.
A:
Your while loop is incorrect. The correct way is to receive user input as a string and take action accordingly. The following is a working sample:
numbersEntered = []
lengthNumbers = int(input("Please enter the length of your list/array: "))
print("Please enter your numbers individually: ")
for x in range(lengthNumbers):
data = int(input())
if data == -1000:
print("-1000 received, exiting")
exit()
numbersEntered.append(data)
def menu():
print("[A] Smallest")
print("[B] Largest")
print("[C] Quit")
menu()
while True:
option = input("Please select either option A,B,or C: ")
if option == "A":
print("The smallest number is:", min(numbersEntered))
elif option == "B":
print("The largest number is:", max(numbersEntered))
elif option == "C":
print("Quit")
break
A:
You are close, but...
The program doesn't really exit and bypass the remainder of the
program if -1000 is entered.
The input function is being converted to a float type instead of a
string 'A', 'B', or 'C'.
The while loop and underlying if statements have issues with the type
and value being compared as well as not exiting if 'C' was entered.
Here is a pass at the fixed code... There are a lot of ways to solve this. You were close so I added extra comments that I hope helps you with the flow and solving your next programming puzzle.
numbersEntered = []
# moved functions outside program flow
def menu():
print("[A] Smallest")
print("[B] Largest")
print("[C] Quit")
#############################################
# program logic starts here.
# You could put all this in a main() function
#############################################
lengthNumbers = int(input("Please enter the length of your list/array:"))
print("Please enter your numbers individually:")
for x in range(lengthNumbers):
data=int(input())
numbersEntered.append(data)
# added a check for -1000 to exit the input loop
if (data == -1000):
break
# removed the OptionA, B, C and values as they aren't necessary
# changed the while condition to skip if the user chose to exit in the
# input section
while numbersEntered[-1] != -1000:
# moved the menu and input inside the while loop to repeat the menu
menu()
# changed input from float to str and convert to uppercase
Options=str(input(f"Please select either option A,B,or C:")).upper()
# compare to strings ('A', 'B', or 'C') vs value of A, B, or C
if Options == 'A':
print("The smallest number is:", min(numbersEntered))
elif Options == 'B':
print("The largest number is:", max(numbersEntered) )
# check for 'C' input from user to break out of the while loop
elif Options == 'C':
break
# move the exit/quit message to the end of the program
print('Exited Program')
|
How do I write a code that takes user input to form an array, and from that array the user decides if we should find the smallest or largest value?
|
I need to create a code using loops to ask for user input on certain values.
Of those values I need to ask the user if they want me to find the smallest or largest number or just end the program. If the number -1000 is entered in the program the program ends. Basically how do I link my menu of options to a the actual actions per option.Here's what I have so far.
numbersEntered = []
lengthNumbers = int(input("Please enter the length of your list/array:"))
print("Please enter your numbers individually:")
for x in range(lengthNumbers):
data=int(input())
numbersEntered.append(data)
def menu():
print("[A] Smallest")
print("[B] Largest")
print("[C] Quit")
menu()
Options=float(input(f"Please select either option A,B,or C:"))
optionA = min(numbersEntered)
optionB = max(numbersEntered)
optionC = quit
while numbersEntered != C:
if numbersEntered == A:
print("The smallest number is:", min(numbersEntered))
elif numbersEntered == B:
print("The largest number is:", max(numbersEntered) )
elif numbersEntered ==-1000:
print("Quit")
I tried a while loop to connect the menu to said action but that did not work and idk why. I am a beginner programer so I'm very new to this stuff.
|
[
"Your while loop is incorrect. The correct way is to receive user input as a string and take action accordingly. The following is a working sample:\nnumbersEntered = []\nlengthNumbers = int(input(\"Please enter the length of your list/array: \"))\nprint(\"Please enter your numbers individually: \")\n\nfor x in range(lengthNumbers):\n data = int(input())\n if data == -1000:\n print(\"-1000 received, exiting\")\n exit()\n numbersEntered.append(data)\n\n\ndef menu():\n print(\"[A] Smallest\")\n print(\"[B] Largest\")\n print(\"[C] Quit\")\n\n\nmenu()\n\nwhile True:\n option = input(\"Please select either option A,B,or C: \")\n if option == \"A\":\n print(\"The smallest number is:\", min(numbersEntered))\n elif option == \"B\":\n print(\"The largest number is:\", max(numbersEntered))\n elif option == \"C\":\n print(\"Quit\")\n break\n\n\n",
"You are close, but...\n\nThe program doesn't really exit and bypass the remainder of the\nprogram if -1000 is entered.\n\nThe input function is being converted to a float type instead of a\nstring 'A', 'B', or 'C'.\n\nThe while loop and underlying if statements have issues with the type\nand value being compared as well as not exiting if 'C' was entered.\n\n\nHere is a pass at the fixed code... There are a lot of ways to solve this. You were close so I added extra comments that I hope helps you with the flow and solving your next programming puzzle.\n\n numbersEntered = []\n\n # moved functions outside program flow\n def menu():\n print(\"[A] Smallest\")\n print(\"[B] Largest\")\n print(\"[C] Quit\")\n\n #############################################\n # program logic starts here. \n # You could put all this in a main() function\n #############################################\n lengthNumbers = int(input(\"Please enter the length of your list/array:\"))\n print(\"Please enter your numbers individually:\")\n\n\n for x in range(lengthNumbers):\n data=int(input())\n numbersEntered.append(data)\n # added a check for -1000 to exit the input loop\n if (data == -1000):\n break\n\n\n # removed the OptionA, B, C and values as they aren't necessary\n\n # changed the while condition to skip if the user chose to exit in the \n # input section\n while numbersEntered[-1] != -1000:\n # moved the menu and input inside the while loop to repeat the menu\n menu()\n # changed input from float to str and convert to uppercase\n Options=str(input(f\"Please select either option A,B,or C:\")).upper()\n # compare to strings ('A', 'B', or 'C') vs value of A, B, or C\n if Options == 'A':\n print(\"The smallest number is:\", min(numbersEntered))\n elif Options == 'B':\n print(\"The largest number is:\", max(numbersEntered) )\n # check for 'C' input from user to break out of the while loop\n elif Options == 'C':\n break\n\n # move the exit/quit message to the end of the program\n print('Exited Program')\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"arraylist",
"arrays",
"python_3.8",
"python_3.x",
"while_loop"
] |
stackoverflow_0074661344_arraylist_arrays_python_3.8_python_3.x_while_loop.txt
|
Q:
What are comparative operators in C?
On my midterm there was a question that I believe has two correct answers, A and B. The question states:
Which of the following sets of operators is composed only of comparative operators?
A) >, <, >=, <=
B) ==, !=
C) &&, ||, !
D) None of the above.
Page 235 of my textbook (Computer Science: A Structured Programming Approach Using C by Forouzan and Gilberg) states,
C provides six comparative operators. … The operators are shown in Figure 5-4.
Figure 5-4 shows the operators <, <=, >, >=, ==, and !=. I emailed this to my lecturer and she responded with:
I understand the point you made in your submitted paper, but the best course of action is to stick to CS159 notes packet rather than Forouzan's textbook, as the textbook is considered a supplemental resource for this course.
Page 119 of my notes packet (Purdue University's CS159 notes packet) says that comparative operators are == and !=. So does comparative operator have two definitions? Even in that case the question would have two correct answers.
A:
§6.5.8 of the ISO C11 standard defines the operators <, >, <= and >= to be the "relational operators".
§6.5.9 of the ISO C11 standard defines the operators == and != to be the "equality operators".
The ISO C standard does not use the terms "comparative operators" or "comparison operators", so it also does not provide a definition for them.
However, all six of the operators mentioned above are intended for comparing both operands, so the most meaningful definition of such a term would include all of these operators.
A:
C defines
4 Relational operators: <, >, <=, >=
and
2 Equality operators: ==, !=.
C does not define comparative operator.
So unless you have some other source defining comparative operator, there is no definitive answer.
@Tom Karzes makes a good point: "... your course is adopting nonstandard terminology, then testing you on your understanding of that terminology. I would stick to the standard."
|
What are comparative operators in C?
|
On my midterm there was a question that I believe has two correct answers, A and B. The question states:
Which of the following sets of operators is composed only of comparative operators?
A) >, <, >=, <=
B) ==, !=
C) &&, ||, !
D) None of the above.
Page 235 of my textbook (Computer Science: A Structured Programming Approach Using C by Forouzan and Gilberg) states,
C provides six comparative operators. … The operators are shown in Figure 5-4.
Figure 5-4 shows the operators <, <=, >, >=, ==, and !=. I emailed this to my lecturer and she responded with:
I understand the point you made in your submitted paper, but the best course of action is to stick to CS159 notes packet rather than Forouzan's textbook, as the textbook is considered a supplemental resource for this course.
Page 119 of my notes packet (Purdue University's CS159 notes packet) says that comparative operators are == and !=. So does comparative operator have two definitions? Even in that case the question would have two correct answers.
|
[
"§6.5.8 of the ISO C11 standard defines the operators <, >, <= and >= to be the \"relational operators\".\n§6.5.9 of the ISO C11 standard defines the operators == and != to be the \"equality operators\".\nThe ISO C standard does not use the terms \"comparative operators\" or \"comparison operators\", so it also does not provide a definition for them.\nHowever, all six of the operators mentioned above are intended for comparing both operands, so the most meaningful definition of such a term would include all of these operators.\n",
"C defines\n4 Relational operators: <, >, <=, >=\nand\n2 Equality operators: ==, !=.\nC does not define comparative operator.\nSo unless you have some other source defining comparative operator, there is no definitive answer.\n\n@Tom Karzes makes a good point: \"... your course is adopting nonstandard terminology, then testing you on your understanding of that terminology. I would stick to the standard.\"\n"
] |
[
4,
2
] |
[] |
[] |
[
"c",
"operators"
] |
stackoverflow_0074661977_c_operators.txt
|
Q:
Finding Number of Customers Who Played at Least One Product Video
I am looking through the progression of pages users clicked on within one of our apps. Customers can go backwards in the process and each action has a time stamp. I want to find the percentage of customers who played a protection plan video at least once
ActivityType: page title (can visit the same page more than once)
Interested in "Products Presented" (Main protection plan page) and "Product Video Viewed"
ConsumerID: customers unique identifier
EventDateTime: Timestamp for each page visit
Is there a way to count CustomerId that played at least one video?
DistinctCustomersPlayedVideo =
CALCULATE(
DISTINCTCOUNT(ConsumerFunnelTime[ConsumerID],
COUNT(ConsumerFunnelTime[ActivityType] IN {"ProductVideoViewed"} >= 1))
)
I can then divide this by the number of distinct customers that made it to the protection page at least once
Data:
{
EventDateTime ActivityType ConsumerID ConsumerFunnel
22:48.0 Products Presented 4623439 1
22:50.0 Products Presented 4623439 2
26:15.0 Product Video Viewed 4623439 3
44:27.0 Products Presented 4673980 1
44:27.0 Products Presented 4673980 1
29:10.0 Products Presented 4674538 1
29:11.0 Products Presented 4674538 2
11:50.0 Products Presented 4674699 1
11:50.0 Products Presented 4674699 1
21:02.0 Products Presented 4674721 1
21:03.0 Products Presented 4674721 2
52:17.0 Products Presented 4674837 1
52:19.0 Products Presented 4674837 2
26:16.0 Products Presented 4674837 3
26:18.0 Products Presented 4674837 4
}
A:
Try this measure:
DistinctCustomersPlayedVideo =
CALCULATE(
DISTINCTCOUNT(ConsumerFunnelTime[ConsumerID]),
ConsumerFunnelTime[ActivityType] = "Product Video Viewed"
)
|
Finding Number of Customers Who Played at Least One Product Video
|
I am looking through the progression of pages users clicked on within one of our apps. Customers can go backwards in the process and each action has a time stamp. I want to find the percentage of customers who played a protection plan video at least once
ActivityType: page title (can visit the same page more than once)
Interested in "Products Presented" (Main protection plan page) and "Product Video Viewed"
ConsumerID: customers unique identifier
EventDateTime: Timestamp for each page visit
Is there a way to count CustomerId that played at least one video?
DistinctCustomersPlayedVideo =
CALCULATE(
DISTINCTCOUNT(ConsumerFunnelTime[ConsumerID],
COUNT(ConsumerFunnelTime[ActivityType] IN {"ProductVideoViewed"} >= 1))
)
I can then divide this by the number of distinct customers that made it to the protection page at least once
Data:
{
EventDateTime ActivityType ConsumerID ConsumerFunnel
22:48.0 Products Presented 4623439 1
22:50.0 Products Presented 4623439 2
26:15.0 Product Video Viewed 4623439 3
44:27.0 Products Presented 4673980 1
44:27.0 Products Presented 4673980 1
29:10.0 Products Presented 4674538 1
29:11.0 Products Presented 4674538 2
11:50.0 Products Presented 4674699 1
11:50.0 Products Presented 4674699 1
21:02.0 Products Presented 4674721 1
21:03.0 Products Presented 4674721 2
52:17.0 Products Presented 4674837 1
52:19.0 Products Presented 4674837 2
26:16.0 Products Presented 4674837 3
26:18.0 Products Presented 4674837 4
}
|
[
"Try this measure:\nDistinctCustomersPlayedVideo = \nCALCULATE(\n DISTINCTCOUNT(ConsumerFunnelTime[ConsumerID]),\n ConsumerFunnelTime[ActivityType] = \"Product Video Viewed\"\n)\n\n"
] |
[
0
] |
[] |
[] |
[
"count",
"dax",
"powerbi"
] |
stackoverflow_0074661356_count_dax_powerbi.txt
|
Q:
React Native: glitch when dragging view
I want to be able to drag and move a View using touch events. The render is glitchy, flickering. The app seem to be confused by the moving view itself. Responder values are glitchy only if i move it.
how can i prevent that?
import React, { useRef } from 'react';
import {
Animated,
View,
} from 'react-native';
const CURSOR_SIDE_SIZE = 20;
const CURSOR_HALF_SIDE_SIZE = CURSOR_SIDE_SIZE / 2;
export default (props) => {
const touch = useRef(
new Animated.ValueXY({ x: 0, y: 0 })
).current;
return (
<View
onStartShouldSetResponder={() => true}
onResponderMove={(event) => {
touch.setValue({
x: event.nativeEvent.locationX,
y: event.nativeEvent.locationY,
});
}}
style={{ flex: 1 }}>
<Animated.View
style={{
position: 'absolute',
left: Animated.subtract(touch.x, CURSOR_HALF_SIDE_SIZE),
top: Animated.subtract(touch.y, CURSOR_HALF_SIDE_SIZE),
height: CURSOR_SIDE_SIZE,
width: CURSOR_SIDE_SIZE,
borderRadius: CURSOR_HALF_SIDE_SIZE,
backgroundColor: 'orange',
}}
/>
</View>
);
};
A:
There are several possible causes for the flickering and glitchy behavior you are experiencing. One possible cause is that you are updating the position of the view using the setValue method in the onResponderMove event handler. This method updates the values of the Animated.ValueXY object immediately, which may cause the flickering and glitchy behavior you are seeing.
To fix this issue, you can use the Animated.event helper method to create a new event handler that updates the Animated.ValueXY object with a smoothed, low-pass filtered version of the touch position. This will reduce the flickering and improve the overall performance of your animation.
Here is an example of how you can use the Animated.event method to create a smooth event handler for the onResponderMove event:
import React, { useRef } from 'react';
import {
Animated,
View,
} from 'react-native';
const CURSOR_SIDE_SIZE = 20;
const CURSOR_HALF_SIDE_SIZE = CURSOR_SIDE_SIZE / 2;
export default (props) => {
const touch = useRef(
new Animated.ValueXY({ x: 0, y: 0 })
).current;
const onMove = Animated.event(
[{ nativeEvent: { locationX: touch.x, locationY: touch.y } }],
{ useNativeDriver: true }
);
return (
<View
onStartShouldSetResponder={() => true}
onResponderMove={onMove}
style={{ flex: 1 }}
>
<Animated.View
style={{
position: 'absolute',
left: Animated.subtract(touch.x, CURSOR_HALF_SIDE_SIZE),
top: Animated.subtract(touch.y, CURSOR_HALF_SIDE_SIZE),
height: CURSOR_SIDE_SIZE,
width: CURSOR_SIDE_SIZE,
borderRadius: CURSOR_HALF_SIDE_SIZE,
backgroundColor: 'orange',
}}
/>
</View>
);
};
In this example, the onMove event handler is created using the Animated.event method. This method takes two arguments: an array of objects that specify the source values for the animation, and an options object that specifies the animation configuration.
In this case, the source values are the locationX and locationY properties of the nativeEvent object passed to the onResponderMove event handler. These values are used to update the x and y properties of the Animated.ValueXY object, which are then used to position the view.
The options object passed to the Animated.event method specifies that the animation should use the native driver, which means that the animation updates will be handled directly by the native animation system on the device, rather than by the JavaScript thread. This can improve the performance of the animation and reduce the likelihood of flickering and other glitchy behavior.
|
React Native: glitch when dragging view
|
I want to be able to drag and move a View using touch events. The render is glitchy, flickering. The app seem to be confused by the moving view itself. Responder values are glitchy only if i move it.
how can i prevent that?
import React, { useRef } from 'react';
import {
Animated,
View,
} from 'react-native';
const CURSOR_SIDE_SIZE = 20;
const CURSOR_HALF_SIDE_SIZE = CURSOR_SIDE_SIZE / 2;
export default (props) => {
const touch = useRef(
new Animated.ValueXY({ x: 0, y: 0 })
).current;
return (
<View
onStartShouldSetResponder={() => true}
onResponderMove={(event) => {
touch.setValue({
x: event.nativeEvent.locationX,
y: event.nativeEvent.locationY,
});
}}
style={{ flex: 1 }}>
<Animated.View
style={{
position: 'absolute',
left: Animated.subtract(touch.x, CURSOR_HALF_SIDE_SIZE),
top: Animated.subtract(touch.y, CURSOR_HALF_SIDE_SIZE),
height: CURSOR_SIDE_SIZE,
width: CURSOR_SIDE_SIZE,
borderRadius: CURSOR_HALF_SIDE_SIZE,
backgroundColor: 'orange',
}}
/>
</View>
);
};
|
[
"There are several possible causes for the flickering and glitchy behavior you are experiencing. One possible cause is that you are updating the position of the view using the setValue method in the onResponderMove event handler. This method updates the values of the Animated.ValueXY object immediately, which may cause the flickering and glitchy behavior you are seeing.\nTo fix this issue, you can use the Animated.event helper method to create a new event handler that updates the Animated.ValueXY object with a smoothed, low-pass filtered version of the touch position. This will reduce the flickering and improve the overall performance of your animation.\nHere is an example of how you can use the Animated.event method to create a smooth event handler for the onResponderMove event:\nimport React, { useRef } from 'react';\nimport {\n Animated,\n View,\n} from 'react-native';\n\nconst CURSOR_SIDE_SIZE = 20;\nconst CURSOR_HALF_SIDE_SIZE = CURSOR_SIDE_SIZE / 2;\n\nexport default (props) => {\n const touch = useRef(\n new Animated.ValueXY({ x: 0, y: 0 })\n ).current;\n\n const onMove = Animated.event(\n [{ nativeEvent: { locationX: touch.x, locationY: touch.y } }],\n { useNativeDriver: true }\n );\n\n return (\n <View \n onStartShouldSetResponder={() => true}\n onResponderMove={onMove}\n style={{ flex: 1 }}\n >\n <Animated.View\n style={{\n position: 'absolute',\n left: Animated.subtract(touch.x, CURSOR_HALF_SIDE_SIZE),\n top: Animated.subtract(touch.y, CURSOR_HALF_SIDE_SIZE),\n height: CURSOR_SIDE_SIZE,\n width: CURSOR_SIDE_SIZE,\n borderRadius: CURSOR_HALF_SIDE_SIZE,\n backgroundColor: 'orange',\n }}\n />\n </View>\n );\n};\n\nIn this example, the onMove event handler is created using the Animated.event method. This method takes two arguments: an array of objects that specify the source values for the animation, and an options object that specifies the animation configuration.\nIn this case, the source values are the locationX and locationY properties of the nativeEvent object passed to the onResponderMove event handler. These values are used to update the x and y properties of the Animated.ValueXY object, which are then used to position the view.\nThe options object passed to the Animated.event method specifies that the animation should use the native driver, which means that the animation updates will be handled directly by the native animation system on the device, rather than by the JavaScript thread. This can improve the performance of the animation and reduce the likelihood of flickering and other glitchy behavior.\n"
] |
[
0
] |
[] |
[] |
[
"react_native",
"reactjs"
] |
stackoverflow_0074662037_react_native_reactjs.txt
|
Q:
MSW Runtime request handler not working in Cypress (NextJs, Cypress, MSW)
I am using NextJs along with Cypress and MSW. I want to use the MSW worker in Cypress to flexibly mock responses for my api request along the test to have a common mocking tool for all types of tests.
The MSW handlers in the worker setup (in NextJs) is intercepting the request from the Cypress test run without any issue. But when I define a runtime request handler in Cypress to overwrite an existing handler or to add a test-specific handler, the api request does not get intercepted.
Here are the relevant files:
./test/server/testWorker.ts
import { graphql, setupWorker } from "msw";
import { handlers } from "./serverHandlers";
const worker = setupWorker(...handlers);
window.msw = {
worker,
graphql,
};
export * from "msw";
export { worker };
./test/server/index.ts
async function initMocks() {
if (typeof window !== "undefined") {
const { worker } = await import("./testWorker");
worker.start();
}
}
initMocks();
export {};
./_app.tsx
...
if (process.env.NEXT_PUBLIC_API_MOCKING === "enabled") {
require("../test/server");
}
function MyApp({....
...
./cypress/e2e/test.cy.ts
describe("test", () => {
const data = buildTestData();
beforeEach(() => {
cy.visit("/");
cy.window().then((window) => {
const { worker, graphql } = window.msw;
// This runtime request handler does not work
worker.use(
graphql
.link("https://example/graphql.json")
.query(/fetchdata/i, (req, res, ctx) => {
return res(
ctx.data({
data
})
);
})
);
});
});
...
The worker.printHandlers() command shows that the runtime request handler in the console is registered but the request was not intercepted. MSW warns me 'captured a request without a matching request handler' in my console.
I am grateful for any help!
A:
It looks like you are trying to use the MSW worker in Cypress to flexibly mock responses for your API requests. It seems that the MSW handlers in the worker setup are successfully intercepting the requests from the Cypress test run, but when you define a runtime request handler in Cypress, the API requests are not intercepted.
One potential issue could be that the worker.use() method is being called before the worker has started. In the beforeEach block of your Cypress test, you are calling worker.use() immediately after accessing the worker from the window object. However, it is possible that the worker has not yet started at this point, which would prevent the runtime request handler from being registered.
To fix this issue, you can try moving the call to worker.use() inside the initMocks() function in ./test/server/index.ts, after the worker.start() method is called. This would ensure that the runtime request handler is registered after the worker has started, which should allow the API requests to be intercepted by the worker.
Here is an example of how you could modify ./test/server/index.ts to fix this issue:
async function initMocks() {
if (typeof window !== "undefined") {
const { worker } = await import("./testWorker");
worker.start();
// Move the call to worker.use() here
const { graphql } = window.msw;
worker.use(
graphql
.link("https://example/graphql.json")
.query(/fetchdata/i, (req, res, ctx) => {
return res(
ctx.data({
data
})
);
})
);
}
}
initMocks();
export {};
After making this change, you should be able to use the runtime request handler in Cypress to intercept and mock API requests as needed. I hope this helps!
|
MSW Runtime request handler not working in Cypress (NextJs, Cypress, MSW)
|
I am using NextJs along with Cypress and MSW. I want to use the MSW worker in Cypress to flexibly mock responses for my api request along the test to have a common mocking tool for all types of tests.
The MSW handlers in the worker setup (in NextJs) is intercepting the request from the Cypress test run without any issue. But when I define a runtime request handler in Cypress to overwrite an existing handler or to add a test-specific handler, the api request does not get intercepted.
Here are the relevant files:
./test/server/testWorker.ts
import { graphql, setupWorker } from "msw";
import { handlers } from "./serverHandlers";
const worker = setupWorker(...handlers);
window.msw = {
worker,
graphql,
};
export * from "msw";
export { worker };
./test/server/index.ts
async function initMocks() {
if (typeof window !== "undefined") {
const { worker } = await import("./testWorker");
worker.start();
}
}
initMocks();
export {};
./_app.tsx
...
if (process.env.NEXT_PUBLIC_API_MOCKING === "enabled") {
require("../test/server");
}
function MyApp({....
...
./cypress/e2e/test.cy.ts
describe("test", () => {
const data = buildTestData();
beforeEach(() => {
cy.visit("/");
cy.window().then((window) => {
const { worker, graphql } = window.msw;
// This runtime request handler does not work
worker.use(
graphql
.link("https://example/graphql.json")
.query(/fetchdata/i, (req, res, ctx) => {
return res(
ctx.data({
data
})
);
})
);
});
});
...
The worker.printHandlers() command shows that the runtime request handler in the console is registered but the request was not intercepted. MSW warns me 'captured a request without a matching request handler' in my console.
I am grateful for any help!
|
[
"It looks like you are trying to use the MSW worker in Cypress to flexibly mock responses for your API requests. It seems that the MSW handlers in the worker setup are successfully intercepting the requests from the Cypress test run, but when you define a runtime request handler in Cypress, the API requests are not intercepted.\nOne potential issue could be that the worker.use() method is being called before the worker has started. In the beforeEach block of your Cypress test, you are calling worker.use() immediately after accessing the worker from the window object. However, it is possible that the worker has not yet started at this point, which would prevent the runtime request handler from being registered.\nTo fix this issue, you can try moving the call to worker.use() inside the initMocks() function in ./test/server/index.ts, after the worker.start() method is called. This would ensure that the runtime request handler is registered after the worker has started, which should allow the API requests to be intercepted by the worker.\nHere is an example of how you could modify ./test/server/index.ts to fix this issue:\nasync function initMocks() {\n if (typeof window !== \"undefined\") {\n const { worker } = await import(\"./testWorker\");\n worker.start();\n\n // Move the call to worker.use() here\n const { graphql } = window.msw;\n worker.use(\n graphql\n .link(\"https://example/graphql.json\")\n .query(/fetchdata/i, (req, res, ctx) => {\n return res(\n ctx.data({\n data\n })\n );\n })\n );\n }\n}\n\ninitMocks();\n\nexport {};\n\nAfter making this change, you should be able to use the runtime request handler in Cypress to intercept and mock API requests as needed. I hope this helps!\n"
] |
[
1
] |
[] |
[] |
[
"cypress",
"e2e_testing",
"mocking",
"msw",
"next.js"
] |
stackoverflow_0074648556_cypress_e2e_testing_mocking_msw_next.js.txt
|
Q:
How to count how many specific weekdays appear between two variable dates? And then show date by date how many events happened?
I apologize if the question title is not clear, but I will try to clarify my issue in this description:
I have a table containing flights schedules with the specific schema and example:
id
departure_country
arrival_country
frequency
start_date
end_date
20
Germany
Poland
..3.5..
2022-12-20
2022-12-30
35
France
Portugal
.2.4..7
2023-02-11
2023-04-15
frequency means which days of the week the flight occurs, 1 being Mondays, 2 being Tuesdays and so on.
My final output should be a table with how many flights occur per day from specific countries.
My idea so far is to create a table keeping the same structure, but splitting the frequency into each number and counting how many of each weekday occurs between the two dates (start and end date) to reach the total flights happening for this period.
I feel like maybe I'm tackling this issue in the wrong way. Apart from the issues with the code I tried, I do not have any idea at this point on how to later count the total amount of flights per date since the code above would display it per ID. any ideas would be highly appreciated!
Thanks!
This is the code I have so far to count how many flights per each ID (with comments explaining the issues found), but the code is not running due to the issues mentioned:
WITH dates AS (SELECT * FROM UNNEST(GENERATE_DATE_ARRAY(start_date, end_date))) -- bigquery does not recognize start_date and end_date
SELECT
id,
departure_country,
arrival_country,
REGEXP_EXTRACT_ALL(frequency, r"([0-9])") AS frequencyNEW,
start_date,
end_date,
COUNT(CASE WHEN FORMAT_DATE('%u',(select * from dates)) = frequencyNEW THEN 1 END)
FROM flights_table
CROSS JOIN UNNEST(frequencyNEW) -- trying to flatten the data but bigquery does not recognize the frequencyNEW field
GROUP BY 1,2,3,4,5,6 -- groupby doesn't work because of the array created with the REGEXP
ORDER BY 1
A:
UNNEST(frequencyNEW) is not possible, because the variable frequencyNEW is not defined yet. Please use a CTE or a sub-select or UNNEST(REGEXP_EXTRACT_ALL(frequency, r"([0-9])")).
A fast solution is to use an inner ((Select ... )). Here all dates are unnested and a where condition is used to filter the one on the right day of the week. Since BigQuery uses the Sunday as 1 and you want it to be 7, a +6 and modulo 7 is applied. With where frequency like '%7%' for a Sunday in the date list, the frequency is checked for a 7.
Depending on your desired output, please remove the #.
with tbl as (select "Germany" departure_country,"..3.5.." frequency, date("2022-12-20") start_date,date("2022-12-30")end_date
union all select "France",".2.4..7",date("2023-02-11"),date("2023-04-15"))
select
# *,
departure_country,sum(
((Select count(x) from unnest(GENERATE_DATE_ARRAY(start_date,end_date)) as x
where frequency like '%'|| mod(extract(DAYOFWEEK from x)+6,7)||'%' )) #as days
) #
from tbl
group by 1 # please comment this line out
This script is quite slow if there more than 10000 rows in the table.
|
How to count how many specific weekdays appear between two variable dates? And then show date by date how many events happened?
|
I apologize if the question title is not clear, but I will try to clarify my issue in this description:
I have a table containing flights schedules with the specific schema and example:
id
departure_country
arrival_country
frequency
start_date
end_date
20
Germany
Poland
..3.5..
2022-12-20
2022-12-30
35
France
Portugal
.2.4..7
2023-02-11
2023-04-15
frequency means which days of the week the flight occurs, 1 being Mondays, 2 being Tuesdays and so on.
My final output should be a table with how many flights occur per day from specific countries.
My idea so far is to create a table keeping the same structure, but splitting the frequency into each number and counting how many of each weekday occurs between the two dates (start and end date) to reach the total flights happening for this period.
I feel like maybe I'm tackling this issue in the wrong way. Apart from the issues with the code I tried, I do not have any idea at this point on how to later count the total amount of flights per date since the code above would display it per ID. any ideas would be highly appreciated!
Thanks!
This is the code I have so far to count how many flights per each ID (with comments explaining the issues found), but the code is not running due to the issues mentioned:
WITH dates AS (SELECT * FROM UNNEST(GENERATE_DATE_ARRAY(start_date, end_date))) -- bigquery does not recognize start_date and end_date
SELECT
id,
departure_country,
arrival_country,
REGEXP_EXTRACT_ALL(frequency, r"([0-9])") AS frequencyNEW,
start_date,
end_date,
COUNT(CASE WHEN FORMAT_DATE('%u',(select * from dates)) = frequencyNEW THEN 1 END)
FROM flights_table
CROSS JOIN UNNEST(frequencyNEW) -- trying to flatten the data but bigquery does not recognize the frequencyNEW field
GROUP BY 1,2,3,4,5,6 -- groupby doesn't work because of the array created with the REGEXP
ORDER BY 1
|
[
"UNNEST(frequencyNEW) is not possible, because the variable frequencyNEW is not defined yet. Please use a CTE or a sub-select or UNNEST(REGEXP_EXTRACT_ALL(frequency, r\"([0-9])\")).\nA fast solution is to use an inner ((Select ... )). Here all dates are unnested and a where condition is used to filter the one on the right day of the week. Since BigQuery uses the Sunday as 1 and you want it to be 7, a +6 and modulo 7 is applied. With where frequency like '%7%' for a Sunday in the date list, the frequency is checked for a 7.\nDepending on your desired output, please remove the #.\nwith tbl as (select \"Germany\" departure_country,\"..3.5..\" frequency, date(\"2022-12-20\") start_date,date(\"2022-12-30\")end_date\nunion all select \"France\",\".2.4..7\",date(\"2023-02-11\"),date(\"2023-04-15\"))\n\nselect \n# *,\ndeparture_country,sum(\n((Select count(x) from unnest(GENERATE_DATE_ARRAY(start_date,end_date)) as x \nwhere frequency like '%'|| mod(extract(DAYOFWEEK from x)+6,7)||'%' )) #as days\n) #\n from tbl \n group by 1 # please comment this line out\n\nThis script is quite slow if there more than 10000 rows in the table.\n"
] |
[
0
] |
[] |
[] |
[
"google_bigquery"
] |
stackoverflow_0074658292_google_bigquery.txt
|
Q:
Where do I modify the admin view code for a 3rd party app?
I am using a 3rd party app in my django webapp.
But I want to customize the admin view for one of the models in the 3rd party app.
The customization is more than changing the change_list.html template i.e. I will need to add code to talk to an external webservice etc.
However, I don't want to modify the 3rd party app. Instead I want to override it.
How I override the ModelAdmin for a model that comes from a 3rd party app ?
A:
This should get you started:
from django.contrib import admin
from thirdpartyapp.models import ThirdPartyModel
from thirdpartyapp.admin import ThirdPartyAdmin
class CustomThirdPartyAdmin(ThirdPartyAdmin):
pass
admin.site.unregister(ThirdPartyModel)
admin.site.register(ThirdPartyModel, CustomThirdPartyAdmin)
I use this often to customize the UserAdmin as shown in this answer.
A:
For those who after put the code on any app/admin.py file, and get this error:
django.contrib.admin.sites.NotRegistered: The model <MODEL_APP_NAME> is not registered
You need to change the name of the admin view for example adding "Custom<Model_NAME>Admin" I think there are conflicts using the same model admin name. With that solution removes the error.
|
Where do I modify the admin view code for a 3rd party app?
|
I am using a 3rd party app in my django webapp.
But I want to customize the admin view for one of the models in the 3rd party app.
The customization is more than changing the change_list.html template i.e. I will need to add code to talk to an external webservice etc.
However, I don't want to modify the 3rd party app. Instead I want to override it.
How I override the ModelAdmin for a model that comes from a 3rd party app ?
|
[
"This should get you started:\nfrom django.contrib import admin\nfrom thirdpartyapp.models import ThirdPartyModel\nfrom thirdpartyapp.admin import ThirdPartyAdmin\n\nclass CustomThirdPartyAdmin(ThirdPartyAdmin):\n pass\n\n\nadmin.site.unregister(ThirdPartyModel)\nadmin.site.register(ThirdPartyModel, CustomThirdPartyAdmin)\n\nI use this often to customize the UserAdmin as shown in this answer.\n",
"For those who after put the code on any app/admin.py file, and get this error:\ndjango.contrib.admin.sites.NotRegistered: The model <MODEL_APP_NAME> is not registered\nYou need to change the name of the admin view for example adding \"Custom<Model_NAME>Admin\" I think there are conflicts using the same model admin name. With that solution removes the error.\n"
] |
[
41,
0
] |
[] |
[] |
[
"django"
] |
stackoverflow_0009321955_django.txt
|
Q:
Writing into shared memory while semaphore value is 0 causes program to freeze in C, ubuntu
I'm writing a multi-process project for a university assignment in operating systems and I've come across a strange issue. Writing into a specific part of shared memory while the semaphore value is 0 causes my program to freeze.
More specifically, the first time I run the executable of parent, the first child process writes into the part of the memory attached to shm_segment_pointer->content once, then the next child process to reach that part of the program freezes the moment before it writes into the same part. Then in all subsequent runs, not even the first child is able to write into that memory segment, freezing up before doing so.
commands used to run:
gcc parent.c -o parent
gcc child.c -o child
./parent
parent.c
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/shm.h>
#include <time.h>
#include "utilities.h"
#define _OPEN_SYS_ITOA_EXT
#define N 4
#define REQUEST_HANDLING_REQ (unsigned long)1000
#define CLIENT_PATH_BUFSIZE 255
#define INITIAL_VALUE 1
void path_to_child(char* buffer){
unsigned long dir_len;
getcwd(buffer, CLIENT_PATH_BUFSIZE);
dir_len = strlen(buffer);
strcpy(buffer + dir_len, "/child");
}
int main(int argc, char* argv[]){
char* newargv[2];
char child_exe[CLIENT_PATH_BUFSIZE];
unsigned int file_line_size, seg_amount;
sem_t *main_sem, *rw_sem;
int i = 0;
pid_t pid = 1;
int shmid_struct, shmid_text;
unsigned int segment_size = 50;
srand(time(NULL));
sem_unlink(SEM_NAME);
sem_unlink(RW_SEM_NAME);
/*Initialize shared memory*/
shmid_struct = shmget((key_t)SHM_KEY_SEG_STRUCT, sizeof(shm_seg), SHM_SEGMENT_PERM | IPC_CREAT);
if (shmid_struct == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shmid_text = shmget((key_t)SHM_KEY_SEG_TEXT, SHM_LINE_SIZE * segment_size * sizeof(char), SHM_SEGMENT_PERM | IPC_CREAT);
if (shmid_struct == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
/*Init semaphores*/
main_sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, SEM_PERMS, INITIAL_VALUE);
if(SEM_FAILED == main_sem){
perror("sem_open error on main sem");
exit(EXIT_FAILURE);
}
rw_sem = sem_open(RW_SEM_NAME, O_CREAT | O_EXCL, SEM_PERMS, INITIAL_VALUE);
if(SEM_FAILED == rw_sem){
perror("sem_open error on rw_sem");
exit(EXIT_FAILURE);
}
/* Initialize the info needed for child functions*/
newargv[0] = "child"; //The name of the child process
newargv[1] = NULL;
path_to_child(child_exe);
fflush(stdout);
for( i = 0; i < N; i++ ){
if( 0 > (pid = fork())){
perror("Could not fork, ending process...");
exit(1);
} else if(0 == pid){
//Initiate child process
execv(child_exe,newargv);
//If exec failed:
perror("exec2: execv failed");
exit(2);
}
}
/**************************************Cleanup Section******************************************/
/*Close file descriptors*/
/*Wait for child processes to finish*/
for( i = 0; i < N; i++ ){
pid = wait(NULL);
if(pid == -1){
perror("wait failed");
}
}
/*Clean up shared memory*/
if (shmctl(shmid_text, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid_struct, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
/*Unlink semaphore, removing it from the file system only after the child processes are done*/
if(sem_unlink(SEM_NAME) < 0){
perror("sem_unlink failed");
}
if(sem_unlink(RW_SEM_NAME) < 0){
perror("sem_unlink failed");
}
return 0;
}
child.c
int main(int argc, char *argv[]){
struct timespec sleep_time;
sem_t *semaphore, *rw_semaphore;
shm_seg *shm_segment_pointer;
int ifd, ofd;
FILE* fptr;
int shmid_struct, shmid_text;
/********************************Init section*********************************************/
srand(time(NULL));
/*Open semaphore from the semaphore file.*/
semaphore = sem_open(SEM_NAME, 0);
if (semaphore == SEM_FAILED) {
perror("sem_open failed");
exit(EXIT_FAILURE);
}
rw_semaphore = sem_open(RW_SEM_NAME, 0);
if (rw_semaphore == SEM_FAILED) {
perror("sem_open failed");
exit(EXIT_FAILURE);
}
setbuf(stdout,NULL);
/* Make shared memory segment for the . */
shmid_struct = shmget(SHM_KEY_SEG_STRUCT, sizeof(shm_seg), SHM_SEGMENT_PERM);
if (shmid_struct == -1) {
perror("Acquisition");
}
shmid_text = shmget(SHM_KEY_SEG_TEXT, seg_size * SHM_LINE_SIZE * sizeof(char), SHM_SEGMENT_PERM);
if (shmid_text == -1) {
perror("Acquisition");
}
/* Attach the segments. */
shm_segment_pointer = (shm_seg*)shmat(shmid_struct, NULL, 0);
if ( shm_segment_pointer == (void *) -1) {
perror("Attachment of segment");
exit(2);
}
shm_segment_pointer->content = (char*)shmat(shmid_text, NULL, 0);
if ( shm_segment_pointer->content == (void *) -1) {
perror("Attachment of text");
exit(2);
}
/************************************Working Segment************************************************/
sem_wait(semaphore);
printf("Testing assignement to seg number...");
shm_segment_pointer->seg_num = 1;
printf("Successful.\nTesting assignment to string...");
strcpy( shm_segment_pointer->content, "ABCD");
printf("shm contents are: %s\n",shm_segment_pointer->content);
sem_post(semaphore);
sleep(10);
if (sem_close(semaphore) < 0)
perror("sem_close(1) failed");
if( sem_close(rw_semaphore) < 0)
perror("sem_close(1) failed");
/* detach from the shared memory segment: */
if(shmdt(shm_segment_pointer->content) == -1) {
perror("shmdt on text point failed");
exit(1);
}
if (shmdt(shm_segment_pointer) == -1) {
perror("shmdt on segment pointer failed");
exit(1);
return 0;
}
utilities.h
#ifndef _UTILITIES_H_
#define _UTILITIES_H_
#include <stdlib.h>
#define SEM_NAME "SM"
#define RW_SEM_NAME "RW_SM"
#define OUTPUT_FILE "testoutput.txt"
#define SHM_LINE_SIZE 1024
#define SHM_SEGMENT_PERM 0666
#define SHM_KEY_SEG_STRUCT 01234
#define SHM_KEY_SEG_TEXT 02345
#define SEM_PERMS (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
typedef struct shared_memory_seg_tag{
int seg_num;
char* content;
} shm_seg;
#endif /* _UTILITIES_H_ */
Output:
51200
seg size:50
Testing assignement to seg number...Successful.
Testing assignment to string...
As stated, the program doesn't end, it freezes there and won't continue without forcing it to end.
I tried removing the semaphores, which fixed the freezing issue but was not the desired behaviour. I also tried delaying the detachment of the segments, which didn't change anything. The only thing that work was completely restructuring my project, which no longer uses a struct to store the segment information.
A:
You have a couple of errors in form that may or may not actually be causing you trouble, as described in comments on the question. But your main issue has nothing in particular to do with the semaphores. It is that this ...
typedef struct shared_memory_seg_tag{
int seg_num;
char* content;
} shm_seg;
... is nonsense for an object stored in shared memory.
Specifically, it pretty much never makes sense to store pointers in memory shared between processes. Putting a pointer in shared memory allows other processes to see the pointer, but not whatever, if anything, it points to. Not even if the pointed-to object is also in the shared memory segment, because the segment is not guaranteed to be attached at the same address in each process.
What's more, your particular pointer isn't even initialized to point to anything in the first place. Your child processes are attempting to copy data to whatever random place it points.
You probably want to declare an array instead of a pointer:
typedef struct shared_memory_seg_tag{
int seg_num;
char content[MAX_CONTENT_SIZE];
} shm_seg;
That makes space for the content available in the shared memory segment, and gives you a valid pointer to it in each child. Of course, you do have to choose a MAX_CONTENT_SIZE that suits all your needs.
|
Writing into shared memory while semaphore value is 0 causes program to freeze in C, ubuntu
|
I'm writing a multi-process project for a university assignment in operating systems and I've come across a strange issue. Writing into a specific part of shared memory while the semaphore value is 0 causes my program to freeze.
More specifically, the first time I run the executable of parent, the first child process writes into the part of the memory attached to shm_segment_pointer->content once, then the next child process to reach that part of the program freezes the moment before it writes into the same part. Then in all subsequent runs, not even the first child is able to write into that memory segment, freezing up before doing so.
commands used to run:
gcc parent.c -o parent
gcc child.c -o child
./parent
parent.c
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/shm.h>
#include <time.h>
#include "utilities.h"
#define _OPEN_SYS_ITOA_EXT
#define N 4
#define REQUEST_HANDLING_REQ (unsigned long)1000
#define CLIENT_PATH_BUFSIZE 255
#define INITIAL_VALUE 1
void path_to_child(char* buffer){
unsigned long dir_len;
getcwd(buffer, CLIENT_PATH_BUFSIZE);
dir_len = strlen(buffer);
strcpy(buffer + dir_len, "/child");
}
int main(int argc, char* argv[]){
char* newargv[2];
char child_exe[CLIENT_PATH_BUFSIZE];
unsigned int file_line_size, seg_amount;
sem_t *main_sem, *rw_sem;
int i = 0;
pid_t pid = 1;
int shmid_struct, shmid_text;
unsigned int segment_size = 50;
srand(time(NULL));
sem_unlink(SEM_NAME);
sem_unlink(RW_SEM_NAME);
/*Initialize shared memory*/
shmid_struct = shmget((key_t)SHM_KEY_SEG_STRUCT, sizeof(shm_seg), SHM_SEGMENT_PERM | IPC_CREAT);
if (shmid_struct == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
shmid_text = shmget((key_t)SHM_KEY_SEG_TEXT, SHM_LINE_SIZE * segment_size * sizeof(char), SHM_SEGMENT_PERM | IPC_CREAT);
if (shmid_struct == -1) {
fprintf(stderr, "shmget failed\n");
exit(EXIT_FAILURE);
}
/*Init semaphores*/
main_sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, SEM_PERMS, INITIAL_VALUE);
if(SEM_FAILED == main_sem){
perror("sem_open error on main sem");
exit(EXIT_FAILURE);
}
rw_sem = sem_open(RW_SEM_NAME, O_CREAT | O_EXCL, SEM_PERMS, INITIAL_VALUE);
if(SEM_FAILED == rw_sem){
perror("sem_open error on rw_sem");
exit(EXIT_FAILURE);
}
/* Initialize the info needed for child functions*/
newargv[0] = "child"; //The name of the child process
newargv[1] = NULL;
path_to_child(child_exe);
fflush(stdout);
for( i = 0; i < N; i++ ){
if( 0 > (pid = fork())){
perror("Could not fork, ending process...");
exit(1);
} else if(0 == pid){
//Initiate child process
execv(child_exe,newargv);
//If exec failed:
perror("exec2: execv failed");
exit(2);
}
}
/**************************************Cleanup Section******************************************/
/*Close file descriptors*/
/*Wait for child processes to finish*/
for( i = 0; i < N; i++ ){
pid = wait(NULL);
if(pid == -1){
perror("wait failed");
}
}
/*Clean up shared memory*/
if (shmctl(shmid_text, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
if (shmctl(shmid_struct, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl(IPC_RMID) failed\n");
exit(EXIT_FAILURE);
}
/*Unlink semaphore, removing it from the file system only after the child processes are done*/
if(sem_unlink(SEM_NAME) < 0){
perror("sem_unlink failed");
}
if(sem_unlink(RW_SEM_NAME) < 0){
perror("sem_unlink failed");
}
return 0;
}
child.c
int main(int argc, char *argv[]){
struct timespec sleep_time;
sem_t *semaphore, *rw_semaphore;
shm_seg *shm_segment_pointer;
int ifd, ofd;
FILE* fptr;
int shmid_struct, shmid_text;
/********************************Init section*********************************************/
srand(time(NULL));
/*Open semaphore from the semaphore file.*/
semaphore = sem_open(SEM_NAME, 0);
if (semaphore == SEM_FAILED) {
perror("sem_open failed");
exit(EXIT_FAILURE);
}
rw_semaphore = sem_open(RW_SEM_NAME, 0);
if (rw_semaphore == SEM_FAILED) {
perror("sem_open failed");
exit(EXIT_FAILURE);
}
setbuf(stdout,NULL);
/* Make shared memory segment for the . */
shmid_struct = shmget(SHM_KEY_SEG_STRUCT, sizeof(shm_seg), SHM_SEGMENT_PERM);
if (shmid_struct == -1) {
perror("Acquisition");
}
shmid_text = shmget(SHM_KEY_SEG_TEXT, seg_size * SHM_LINE_SIZE * sizeof(char), SHM_SEGMENT_PERM);
if (shmid_text == -1) {
perror("Acquisition");
}
/* Attach the segments. */
shm_segment_pointer = (shm_seg*)shmat(shmid_struct, NULL, 0);
if ( shm_segment_pointer == (void *) -1) {
perror("Attachment of segment");
exit(2);
}
shm_segment_pointer->content = (char*)shmat(shmid_text, NULL, 0);
if ( shm_segment_pointer->content == (void *) -1) {
perror("Attachment of text");
exit(2);
}
/************************************Working Segment************************************************/
sem_wait(semaphore);
printf("Testing assignement to seg number...");
shm_segment_pointer->seg_num = 1;
printf("Successful.\nTesting assignment to string...");
strcpy( shm_segment_pointer->content, "ABCD");
printf("shm contents are: %s\n",shm_segment_pointer->content);
sem_post(semaphore);
sleep(10);
if (sem_close(semaphore) < 0)
perror("sem_close(1) failed");
if( sem_close(rw_semaphore) < 0)
perror("sem_close(1) failed");
/* detach from the shared memory segment: */
if(shmdt(shm_segment_pointer->content) == -1) {
perror("shmdt on text point failed");
exit(1);
}
if (shmdt(shm_segment_pointer) == -1) {
perror("shmdt on segment pointer failed");
exit(1);
return 0;
}
utilities.h
#ifndef _UTILITIES_H_
#define _UTILITIES_H_
#include <stdlib.h>
#define SEM_NAME "SM"
#define RW_SEM_NAME "RW_SM"
#define OUTPUT_FILE "testoutput.txt"
#define SHM_LINE_SIZE 1024
#define SHM_SEGMENT_PERM 0666
#define SHM_KEY_SEG_STRUCT 01234
#define SHM_KEY_SEG_TEXT 02345
#define SEM_PERMS (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)
typedef struct shared_memory_seg_tag{
int seg_num;
char* content;
} shm_seg;
#endif /* _UTILITIES_H_ */
Output:
51200
seg size:50
Testing assignement to seg number...Successful.
Testing assignment to string...
As stated, the program doesn't end, it freezes there and won't continue without forcing it to end.
I tried removing the semaphores, which fixed the freezing issue but was not the desired behaviour. I also tried delaying the detachment of the segments, which didn't change anything. The only thing that work was completely restructuring my project, which no longer uses a struct to store the segment information.
|
[
"You have a couple of errors in form that may or may not actually be causing you trouble, as described in comments on the question. But your main issue has nothing in particular to do with the semaphores. It is that this ...\n\ntypedef struct shared_memory_seg_tag{\n int seg_num;\n char* content;\n} shm_seg;\n\n\n... is nonsense for an object stored in shared memory.\nSpecifically, it pretty much never makes sense to store pointers in memory shared between processes. Putting a pointer in shared memory allows other processes to see the pointer, but not whatever, if anything, it points to. Not even if the pointed-to object is also in the shared memory segment, because the segment is not guaranteed to be attached at the same address in each process.\nWhat's more, your particular pointer isn't even initialized to point to anything in the first place. Your child processes are attempting to copy data to whatever random place it points.\nYou probably want to declare an array instead of a pointer:\ntypedef struct shared_memory_seg_tag{\n int seg_num;\n char content[MAX_CONTENT_SIZE];\n} shm_seg;\n\nThat makes space for the content available in the shared memory segment, and gives you a valid pointer to it in each child. Of course, you do have to choose a MAX_CONTENT_SIZE that suits all your needs.\n"
] |
[
1
] |
[] |
[] |
[
"c",
"linux",
"semaphore",
"shared_memory",
"ubuntu"
] |
stackoverflow_0074661463_c_linux_semaphore_shared_memory_ubuntu.txt
|
Q:
How do I detect hitting enter twice to let user exit from populating array with for loop?
I have to let user fill an array with 0-500 values, and at any moment they can exit entering the array with two consecutive empty value inputs (hitting enter twice).
Then the array displays, then it sorts itself, and finally displays again.
I have no idea how to capture enter twice in a row to exit the loop.
The best I can do to help communicate what I am doing, I used getch(); which I am pretty sure my teacher would not like since it isn't standard.
I've tried cin.peek and cin.get but if there is nothing in the stream it always waits for enter which I don't want happening.
I found getch(); and it basically bypasses the problem I am having. I need to make this program operate the same way but using something that is in the c++ standard. Hitting enter after every entry is fine, but I need to detect an empty line and then go into a state where I can detect another one. If it detects one empty line I need to be able to resume entering values.
Here is a somewhat working version with getch(); of what I am going for.
#include <iostream>
#include <conio.h>
using std::cin;
using std::cout;
using std::endl;
const int ARRAY = 500;
int GetUserArray(int b[ARRAY]);
void DisplayVals(int ArrayofValues[ARRAY], int &x);
void SortArray(int ArrayofValues[ARRAY], int& x);
int main()
{
int UserArray[ARRAY]= {0};
int NumberofValues = 0;
//User Populates Array, catches number of entries with return
NumberofValues = GetUserArray(UserArray);
//Displays the NON-SORTED array
DisplayVals(UserArray, NumberofValues);
//Sorts Array
SortArray(UserArray, NumberofValues);
//Displays the SORTED array
DisplayVals(UserArray, NumberofValues);
return 0;
}
int GetUserArray(int UserArray[ARRAY])
{
int howmany = 0;
int input = 0;
//ASCII code for enter key is 13 '\n'
int x = 0;
cout << "Please enter an integer values: ";
for (int i = 0; i < ARRAY; i++)
{
input = _getche();
if (input == 13)
{
cout << endl;
cout << "Please enter an integer value: ";
input = _getche();
if (input == 13)
{
i += 499;
cout << endl;
cout << endl;
cout << "Exiting...";
}
}
UserArray[i] = input;
howmany++;
}
return howmany;
}
void DisplayVals(int ArrayofValues[ARRAY], int &x)
{
cout << '\n' << endl;
for (int i = 0; i < x ; i++)
{
char Display = 0;
Display = ArrayofValues[i];
cout << Display << ' ';
}
cout << endl;
}
void SortArray(int ArrayofValues[ARRAY], int& x)
{
bool sorted = false;
for (int pass = 0; pass < x; pass++)
{
for (int i = 1; i < (x - pass - 1); i++)
{
if ((ArrayofValues[i - 1]) < ArrayofValues[i])
{
int temp = ArrayofValues[i - 1];
ArrayofValues[i - 1] = ArrayofValues[i];
ArrayofValues[i] = temp;
}
}
}
}
A:
Note: ASCII value of \n is 10.
Following is the tested and working code:
int GetUserArray(int UserArray[ARRAY]) {
int input = 0;
int exit_flag = 0;
int howmany = 0;
cout << "Please enter an integer values: ";
for (int i = 0; i < ARRAY; i++) {
input = cin.get(); //Stores ASCII value inside input
if(input==10){
if(exit_flag){
i+=ARRAY; // You should not hard-code any values.
cout<<"Exiting";
}
exit_flag = 1;
--i; //If you don't want to skip an index in case of Single Enter.
continue;
}
else{
exit_flag=0;
UserArray[i] = input-'0'; //Converting ASCII to INT.
howmany++;
cin.ignore(); //Clearing the input buffer as we have pressed 'Enter'.
}
}
return howmany;
}
Thank you.
|
How do I detect hitting enter twice to let user exit from populating array with for loop?
|
I have to let user fill an array with 0-500 values, and at any moment they can exit entering the array with two consecutive empty value inputs (hitting enter twice).
Then the array displays, then it sorts itself, and finally displays again.
I have no idea how to capture enter twice in a row to exit the loop.
The best I can do to help communicate what I am doing, I used getch(); which I am pretty sure my teacher would not like since it isn't standard.
I've tried cin.peek and cin.get but if there is nothing in the stream it always waits for enter which I don't want happening.
I found getch(); and it basically bypasses the problem I am having. I need to make this program operate the same way but using something that is in the c++ standard. Hitting enter after every entry is fine, but I need to detect an empty line and then go into a state where I can detect another one. If it detects one empty line I need to be able to resume entering values.
Here is a somewhat working version with getch(); of what I am going for.
#include <iostream>
#include <conio.h>
using std::cin;
using std::cout;
using std::endl;
const int ARRAY = 500;
int GetUserArray(int b[ARRAY]);
void DisplayVals(int ArrayofValues[ARRAY], int &x);
void SortArray(int ArrayofValues[ARRAY], int& x);
int main()
{
int UserArray[ARRAY]= {0};
int NumberofValues = 0;
//User Populates Array, catches number of entries with return
NumberofValues = GetUserArray(UserArray);
//Displays the NON-SORTED array
DisplayVals(UserArray, NumberofValues);
//Sorts Array
SortArray(UserArray, NumberofValues);
//Displays the SORTED array
DisplayVals(UserArray, NumberofValues);
return 0;
}
int GetUserArray(int UserArray[ARRAY])
{
int howmany = 0;
int input = 0;
//ASCII code for enter key is 13 '\n'
int x = 0;
cout << "Please enter an integer values: ";
for (int i = 0; i < ARRAY; i++)
{
input = _getche();
if (input == 13)
{
cout << endl;
cout << "Please enter an integer value: ";
input = _getche();
if (input == 13)
{
i += 499;
cout << endl;
cout << endl;
cout << "Exiting...";
}
}
UserArray[i] = input;
howmany++;
}
return howmany;
}
void DisplayVals(int ArrayofValues[ARRAY], int &x)
{
cout << '\n' << endl;
for (int i = 0; i < x ; i++)
{
char Display = 0;
Display = ArrayofValues[i];
cout << Display << ' ';
}
cout << endl;
}
void SortArray(int ArrayofValues[ARRAY], int& x)
{
bool sorted = false;
for (int pass = 0; pass < x; pass++)
{
for (int i = 1; i < (x - pass - 1); i++)
{
if ((ArrayofValues[i - 1]) < ArrayofValues[i])
{
int temp = ArrayofValues[i - 1];
ArrayofValues[i - 1] = ArrayofValues[i];
ArrayofValues[i] = temp;
}
}
}
}
|
[
"Note: ASCII value of \\n is 10.\nFollowing is the tested and working code:\nint GetUserArray(int UserArray[ARRAY]) {\n int input = 0;\n int exit_flag = 0;\n int howmany = 0;\n\n cout << \"Please enter an integer values: \";\n for (int i = 0; i < ARRAY; i++) {\n input = cin.get(); //Stores ASCII value inside input\n if(input==10){\n if(exit_flag){\n i+=ARRAY; // You should not hard-code any values.\n cout<<\"Exiting\";\n }\n exit_flag = 1;\n --i; //If you don't want to skip an index in case of Single Enter.\n continue;\n }\n else{\n exit_flag=0;\n UserArray[i] = input-'0'; //Converting ASCII to INT.\n howmany++;\n cin.ignore(); //Clearing the input buffer as we have pressed 'Enter'.\n }\n }\n return howmany;\n}\n\nThank you.\n"
] |
[
0
] |
[] |
[] |
[
"c++",
"cin",
"enter",
"getch"
] |
stackoverflow_0074661324_c++_cin_enter_getch.txt
|
Q:
Hibernate 6 equivelant of SQLFunction render
I am struggling to find out how to migrate my code containing org.hibernate.dialect.function.SQLFunction.render method … to Hibernate 6
SessionFactoryImplementor d = this.entityManagerFactory.unwrap(SessionFactoryImplementor.class);
SQLFunction fnc = d.getSqlFunctionRegistry()
.findSQLFunction("fncName“);
String render = fnc.render(null, expressions,
this.entityManagerFactory.unwrap(SessionFactoryImplementor.class));
the first part I guess should be
SqlFunction fnc = (SqlFunction) d.getQueryEngine().getSqmFunctionRegistry().findFunctionDescriptor("fncName“);
but I am stuck with the the 2nd part
A:
SessionFactoryImplementor is documented as an SPI, and so we don't really recommend using it in this way.
/**
* Defines the internal contract between the {@link SessionFactory} and the internal
* implementation of Hibernate.
At least, if you do this sort of thing, you do it at your own risk.
As you've noticed, SqmFunctionDescriptor, which is the replacement for SQLFunction, is a much more technical API, which was a very necessary change, because Hibernate's handling of functions is now much more sophisticated.
I can't really imagine why you would want to be hand-rendering a function invocation, but I'm sure you must have your reasons. Whatever they are, I think it's not likely to work, at least not without an unreasonable amount of messiness.
Sorry.
|
Hibernate 6 equivelant of SQLFunction render
|
I am struggling to find out how to migrate my code containing org.hibernate.dialect.function.SQLFunction.render method … to Hibernate 6
SessionFactoryImplementor d = this.entityManagerFactory.unwrap(SessionFactoryImplementor.class);
SQLFunction fnc = d.getSqlFunctionRegistry()
.findSQLFunction("fncName“);
String render = fnc.render(null, expressions,
this.entityManagerFactory.unwrap(SessionFactoryImplementor.class));
the first part I guess should be
SqlFunction fnc = (SqlFunction) d.getQueryEngine().getSqmFunctionRegistry().findFunctionDescriptor("fncName“);
but I am stuck with the the 2nd part
|
[
"SessionFactoryImplementor is documented as an SPI, and so we don't really recommend using it in this way.\n/**\n * Defines the internal contract between the {@link SessionFactory} and the internal\n * implementation of Hibernate.\n\nAt least, if you do this sort of thing, you do it at your own risk.\nAs you've noticed, SqmFunctionDescriptor, which is the replacement for SQLFunction, is a much more technical API, which was a very necessary change, because Hibernate's handling of functions is now much more sophisticated.\nI can't really imagine why you would want to be hand-rendering a function invocation, but I'm sure you must have your reasons. Whatever they are, I think it's not likely to work, at least not without an unreasonable amount of messiness.\nSorry.\n"
] |
[
0
] |
[] |
[] |
[
"hibernate",
"hibernate_6.x",
"spring_boot",
"spring_boot_3"
] |
stackoverflow_0074534387_hibernate_hibernate_6.x_spring_boot_spring_boot_3.txt
|
Q:
RGB to hex and hex to RGB
How to convert colors in RGB format to hex format and vice versa?
For example, convert '#0080C0' to (0, 128, 192).
A:
Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.
The following will do to the RGB to hex conversion and add any required zero padding:
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
Converting the other way:
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
alert(hexToRgb("#0033ff").g); // "51";
Finally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:
function rgbToHex(r, g, b) {
return "#" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);
}
alert(rgbToHex(0, 51, 255)); // #0033ff
Update 3 December 2012
Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
alert(hexToRgb("#0033ff").g); // "51";
alert(hexToRgb("#03f").g); // "51";
A:
An alternative version of hexToRgb:
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
Edit: 3/28/2017
Here is another approach that seems to be even faster
function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);
return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}
Edit: 8/11/2017
The new approach above after more testing is not faster :(. Though it is a fun alternate way.
A:
ECMAScript 6 version of Tim Down's answer
Converting RGB to hex
const rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => {
const hex = x.toString(16)
return hex.length === 1 ? '0' + hex : hex
}).join('')
console.log(rgbToHex(0, 51, 255)); // '#0033ff'
Converting hex to RGB
Returns an array [r, g, b]. Works also with shorthand hex triplets such as "#03F".
const hexToRgb = hex =>
hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i
,(m, r, g, b) => '#' + r + r + g + g + b + b)
.substring(1).match(/.{2}/g)
.map(x => parseInt(x, 16))
console.log(hexToRgb("#0033ff")) // [0, 51, 255]
console.log(hexToRgb("#03f")) // [0, 51, 255]
Bonus: RGB to hex using padStart() method
const rgbToHex = (r, g, b) => '#' + [r, g, b]
.map(x => x.toString(16).padStart(2, '0')).join('')
console.log(rgbToHex(0, 51, 255)); // '#0033ff'
Note that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.
A:
Here's my version:
function rgbToHex(red, green, blue) {
const rgb = (red << 16) | (green << 8) | (blue << 0);
return '#' + (0x1000000 + rgb).toString(16).slice(1);
}
function hexToRgb(hex) {
const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
if (normal) return normal.slice(1).map(e => parseInt(e, 16));
const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
if (shorthand) return shorthand.slice(1).map(e => 0x11 * parseInt(e, 16));
return null;
}
A:
function hex2rgb(hex) {
return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}
A:
I'm assuming you mean HTML-style hexadecimal notation, i.e. #rrggbb. Your code is almost correct, except you've got the order reversed. It should be:
var decColor = red * 65536 + green * 256 + blue;
Also, using bit-shifts might make it a bit easier to read:
var decColor = (red << 16) + (green << 8) + blue;
A:
One-line functional HEX to RGBA
Supports both short #fff and long #ffffff forms.
Supports alpha channel (opacity).
Does not care if hash specified or not, works in both cases.
function hexToRGBA(hex, opacity) {
return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(isFinite(opacity) ? opacity : 1).join(',') + ')';
}
examples:
hexToRGBA('#fff') -> rgba(255,255,255,1)
hexToRGBA('#ffffff') -> rgba(255,255,255,1)
hexToRGBA('#fff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('#ffffff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('fff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('ffffff', .2) -> rgba(255,255,255,0.2)
hexToRGBA('#ffffff', 0) -> rgba(255,255,255,0)
hexToRGBA('#ffffff', .5) -> rgba(255,255,255,0.5)
hexToRGBA('#ffffff', 1) -> rgba(255,255,255,1)
A:
Try (bonus)
let hex2rgb= c=> `rgb(${c.match(/\w\w/g).map(x=>+`0x${x}`)})`
let rgb2hex=c=>'#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``
let hex2rgb= c=> `rgb(${c.match(/\w\w/g).map(x=>+`0x${x}`)})`;
let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``;
// TEST
console.log('#0080C0 -->', hex2rgb('#0080C0'));
console.log('rgb(0, 128, 192) -->', rgb2hex('rgb(0, 128, 192)'));
A:
This code accept #fff and #ffffff variants and opacity.
function hex2rgb(hex, opacity) {
var h=hex.replace('#', '');
h = h.match(new RegExp('(.{'+h.length/3+'})', 'g'));
for(var i=0; i<h.length; i++)
h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);
if (typeof opacity != 'undefined') h.push(opacity);
return 'rgba('+h.join(',')+')';
}
A:
Bitwise solution normally is weird. But in this case I guess that is more elegant
function hexToRGB(hexColor){
return {
red: (hexColor >> 16) & 0xFF,
green: (hexColor >> 8) & 0xFF,
blue: hexColor & 0xFF,
}
}
Usage:
const {red, green, blue } = hexToRGB(0xFF00FF)
console.log(red) // 255
console.log(green) // 0
console.log(blue) // 255
A:
(2017) SIMPLE ES6 composable arrow functions
I can't resist sharing this for those who may be writing some modern functional/compositional js using ES6. Here are some slick one-liners I am using in a color module that does color interpolation for data visualization.
Note that this does not handle the alpha channel at all.
const arrayToRGBString = rgb => `rgb(${rgb.join(',')})`;
const hexToRGBArray = hex => hex.match(/[A-Za-z0-9]{2}/g).map(v => parseInt(v, 16));
const rgbArrayToHex = rgb => `#${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`;
const rgbStringToArray = rgb => rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/).splice(1, 3)
.map(v => Number(v));
const rgbStringToHex = rgb => rgbArrayToHex(rgbStringToArray(rgb));
BTW, If you like this style/syntax, I wrote a full color module (modern-color) you can grab from npm. I made it so I could use prop getters for conversion and parse virtually anything (Color.parse(anything)). Worth a look if you deal with color a lot like I do.
A:
This could be used for getting colors from computed style propeties:
function rgbToHex(color) {
color = ""+ color;
if (!color || color.indexOf("rgb") < 0) {
return;
}
if (color.charAt(0) == "#") {
return color;
}
var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
r = parseInt(nums[2], 10).toString(16),
g = parseInt(nums[3], 10).toString(16),
b = parseInt(nums[4], 10).toString(16);
return "#"+ (
(r.length == 1 ? "0"+ r : r) +
(g.length == 1 ? "0"+ g : g) +
(b.length == 1 ? "0"+ b : b)
);
}
// not computed
<div style="color: #4d93bc; border: 1px solid red;">...</div>
// computed
<div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div>
console.log( rgbToHex(color) ) // #4d93bc
console.log( rgbToHex(borderTopColor) ) // #ff0000
Ref: https://github.com/k-gun/so/blob/master/so_util.js
A:
Hex to RGB
const hex2rgb = (hex) => {
const r = parseInt(hex.slice(1, 3), 16)
const g = parseInt(hex.slice(3, 5), 16)
const b = parseInt(hex.slice(5, 7), 16)
// return {r, g, b} // return an object
return [ r, g, b ]
}
console.log(hex2rgb("#0080C0"))
RGB to Hex
const rgb2hex = (r, g, b) => {
var rgb = (r << 16) | (g << 8) | b
// return '#' + rgb.toString(16) // #80c0
// return '#' + (0x1000000 + rgb).toString(16).slice(1) // #0080c0
// or use [padStart](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)
return '#' + rgb.toString(16).padStart(6, 0)
}
console.log(rgb2hex(0, 128, 192))
Also if someone need online tool, I have built Hex to RGB and vice versa.
A:
May you be after something like this?
function RGB2HTML(red, green, blue)
{
return '#' + red.toString(16) +
green.toString(16) +
blue.toString(16);
}
alert(RGB2HTML(150, 135, 200));
displays #9687c8
A:
// Ignoring hsl notation, color values are commonly expressed as names, rgb, rgba or hex-
// Hex can be 3 values or 6.
// Rgb can be percentages as well as integer values.
// Best to account for all of these formats, at least.
String.prototype.padZero= function(len, c){
var s= this, c= c || "0", len= len || 2;
while(s.length < len) s= c + s;
return s;
}
var colors={
colornames:{
aqua: '#00ffff', black: '#000000', blue: '#0000ff', fuchsia: '#ff00ff',
gray: '#808080', green: '#008000', lime: '#00ff00', maroon: '#800000',
navy: '#000080', olive: '#808000', purple: '#800080', red: '#ff0000',
silver: '#c0c0c0', teal: '#008080', white: '#ffffff', yellow: '#ffff00'
},
toRgb: function(c){
c= '0x'+colors.toHex(c).substring(1);
c= [(c>> 16)&255, (c>> 8)&255, c&255];
return 'rgb('+c.join(',')+')';
},
toHex: function(c){
var tem, i= 0, c= c? c.toString().toLowerCase(): '';
if(/^#[a-f0-9]{3,6}$/.test(c)){
if(c.length< 7){
var A= c.split('');
c= A[0]+A[1]+A[1]+A[2]+A[2]+A[3]+A[3];
}
return c;
}
if(/^[a-z]+$/.test(c)){
return colors.colornames[c] || '';
}
c= c.match(/\d+(\.\d+)?%?/g) || [];
if(c.length<3) return '';
c= c.slice(0, 3);
while(i< 3){
tem= c[i];
if(tem.indexOf('%')!= -1){
tem= Math.round(parseFloat(tem)*2.55);
}
else tem= parseInt(tem);
if(tem< 0 || tem> 255) c.length= 0;
else c[i++]= tem.toString(16).padZero(2);
}
if(c.length== 3) return '#'+c.join('').toLowerCase();
return '';
}
}
//var c='#dc149c';
//var c='rgb(100%,25%,0)';
//
var c= 'red';
alert(colors.toRgb(c)+'\n'+colors.toHex(c));
A:
@ Tim, to add to your answer (its a little awkward fitting this into a comment).
As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.
I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.
function rgbToHex(r, g, b) {
if(r < 0 || r > 255) alert("r is out of bounds; "+r);
if(g < 0 || g > 255) alert("g is out of bounds; "+g);
if(b < 0 || b > 255) alert("b is out of bounds; "+b);
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}
A:
If you need compare two color values (given as RGB, name color or hex value) or convert to HEX use HTML5 canvas object.
var canvas = document.createElement("canvas");
var ctx = this.canvas.getContext('2d');
ctx.fillStyle = "rgb(pass,some,value)";
var temp = ctx.fillStyle;
ctx.fillStyle = "someColor";
alert(ctx.fillStyle == temp);
A:
2021 version
You can simply use rgb-hex & hex-rgb as it is battle-tested & has multiple options that are not available in other solutions.
I was recently building a Color Picker & these 2 packages came in handy.
Usage
rgb-hex
import rgbHex from 'rgb-hex';
rgbHex(65, 131, 196);
//=> '4183c4'
rgbHex('rgb(40, 42, 54)');
//=> '282a36'
rgbHex(65, 131, 196, 0.2);
//=> '4183c433'
rgbHex(40, 42, 54, '75%');
//=> '282a36bf'
rgbHex('rgba(40, 42, 54, 75%)');
//=> '282a36bf'
hex-rgb
import hexRgb from 'hex-rgb';
hexRgb('4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}
hexRgb('#4183c4');
//=> {red: 65, green: 131, blue: 196, alpha: 1}
hexRgb('#fff');
//=> {red: 255, green: 255, blue: 255, alpha: 1}
hexRgb('#22222299');
//=> {red: 34, green: 34, blue: 34, alpha: 0.6}
hexRgb('#0006');
//=> {red: 0, green: 0, blue: 0, alpha: 0.4}
hexRgb('#cd2222cc');
//=> {red: 205, green: 34, blue: 34, alpha: 0.8}
hexRgb('#cd2222cc', {format: 'array'});
//=> [205, 34, 34, 0.8]
hexRgb('#cd2222cc', {format: 'css'});
//=> 'rgb(205 34 34 / 80%)'
hexRgb('#000', {format: 'css'});
//=> 'rgb(0 0 0)'
hexRgb('#22222299', {alpha: 1});
//=> {red: 34, green: 34, blue: 34, alpha: 1}
hexRgb('#fff', {alpha: 0.5});
//=> {red: 255, green: 255, blue: 255, alpha: 0.5}
A:
Shorthand version that accepts a string:
function rgbToHex(a){
a=a.replace(/[^\d,]/g,"").split(",");
return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
}
document.write(rgbToHex("rgb(255,255,255)"));
To check if it's not already hexadecimal
function rgbToHex(a){
if(~a.indexOf("#"))return a;
a=a.replace(/[^\d,]/g,"").split(",");
return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)
}
document.write("rgb: "+rgbToHex("rgb(255,255,255)")+ " -- hex: "+rgbToHex("#e2e2e2"));
A:
I came across this problem since I wanted to parse any color string value and be able to specify an opacity, so I wrote this function that uses the canvas API.
var toRGBA = function () {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = 1;
canvas.height = 1;
return function (color) {
context.fillStyle = color;
context.fillRect(0, 0, 1, 1);
var data = context.getImageData(0, 0, 1, 1).data;
return {
r: data[0],
g: data[1],
b: data[2],
a: data[3]
};
};
}();
Note about context.fillStyle:
If parsing the value results in failure, then it must be ignored, and the attribute must retain its previous value.
Here's a Stack Snippet demo you can use to test inputs:
var toRGBA = function () {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.width = 1;
canvas.height = 1;
return function (color) {
context.fillStyle = color;
context.fillRect(0, 0, 1, 1);
var data = context.getImageData(0, 0, 1, 1).data;
return {
r: data[0],
g: data[1],
b: data[2],
a: data[3]
};
};
}();
var inputs = document.getElementsByTagName('input');
function setColor() {
inputs[1].value = JSON.stringify(toRGBA(inputs[0].value));
document.body.style.backgroundColor = inputs[0].value;
}
inputs[0].addEventListener('input', setColor);
setColor();
input {
width: 200px;
margin: 0.5rem;
}
<input value="cyan" />
<input readonly="readonly" />
A:
i needed a function that accepts invalid values too like
rgb(-255, 255, 255)
rgb(510, 255, 255)
this is a spin off of @cwolves answer
function rgb(r, g, b) {
this.c = this.c || function (n) {
return Math.max(Math.min(n, 255), 0)
};
return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase();
}
A:
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");
function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
Use these Function to achive the result without any issue. :)
A:
Instead of copy'n'pasting snippets found here and there, I'd recommend to use a well tested and maintained library: Colors.js (available for node.js and browser). It's just 7 KB (minified, gzipped even less).
A:
A simple answer to convert RGB to hex. Here values of color channels are clamped between 0 and 255.
function RGBToHex(r = 0, g = 0, b = 0) {
// clamp and convert to hex
let hr = Math.max(0, Math.min(255, Math.round(r))).toString(16);
let hg = Math.max(0, Math.min(255, Math.round(g))).toString(16);
let hb = Math.max(0, Math.min(255, Math.round(b))).toString(16);
return "#" +
(hr.length<2?"0":"") + hr +
(hg.length<2?"0":"") + hg +
(hb.length<2?"0":"") + hb;
}
A:
This snippet converts hex to rgb and rgb to hex.
View demo
function hexToRgb(str) {
if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) {
var hex = str.substr(1);
hex = hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex;
var rgb = parseInt(hex, 16);
return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';
}
return false;
}
function rgbToHex(red, green, blue) {
var out = '#';
for (var i = 0; i < 3; ++i) {
var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);
if (isNaN(n) || n < 0 || n > 255) {
return false;
}
out += (n < 16 ? '0' : '') + n.toString(16);
}
return out
}
A:
My version of hex2rbg:
Accept short hex like #fff
Algorithm compacity is o(n), should faster than using regex. e.g String.replace, String.split, String.match etc..
Use constant space.
Support rgb and rgba.
you may need remove hex.trim() if you are using IE8.
e.g.
hex2rgb('#fff') //rgb(255,255,255)
hex2rgb('#fff', 1) //rgba(255,255,255,1)
hex2rgb('#ffffff') //rgb(255,255,255)
hex2rgb('#ffffff', 1) //rgba(255,255,255,1)
code:
function hex2rgb (hex, opacity) {
hex = hex.trim();
hex = hex[0] === '#' ? hex.substr(1) : hex;
var bigint = parseInt(hex, 16), h = [];
if (hex.length === 3) {
h.push((bigint >> 4) & 255);
h.push((bigint >> 2) & 255);
} else {
h.push((bigint >> 16) & 255);
h.push((bigint >> 8) & 255);
}
h.push(bigint & 255);
if (arguments.length === 2) {
h.push(opacity);
return 'rgba('+h.join()+')';
} else {
return 'rgb('+h.join()+')';
}
}
A:
While this answer is unlikely to fit the question perfectly it may be very useful none the less.
Create any random element
var toRgb = document.createElement('div');
Set any valid style to the color you want to convert
toRg.style.color = "hsl(120, 60%, 70%)";
Call the style property again
> toRgb.style.color;
< "rgb(133, 225, 133)" Your color has been converted to Rgb
Works for: Hsl, Hex
Does not work for: Named colors
A:
I realise there are lots of answers to this but if you're like me and you know your HEX is always going to be 6 characters with or without the # prefix then this is probably the simplest method if you want to do some quick inline stuff. It does not care if it starts with or without a hash.
var hex = "#ffffff";
var rgb = [
parseInt(hex.substr(-6,2),16),
parseInt(hex.substr(-4,2),16),
parseInt(hex.substr(-2),16)
];
A:
2022: If you often manipulate colors and doesn't mind using a package,
Use tinycolor2. It's a fast library (Around 400kb) for color manipulation and conversion in JavaScript.
It accepts various color string format. Like:
tinycolor("#000"); // Hex3
tinycolor("#f0f0f6"); // Hex6
tinycolor("#f0f0f688"); // Hex8
tinycolor("f0f0f6"); // Hex withouth the number sign '#'
tinycolor("rgb (255, 0, 0)"); // RGB
tinycolor("rgba (255, 0, 0, .5)"); // RGBA
tinycolor({ r: 255, g: 0, b: 0 }); // RGB object
tinycolor("hsl(0, 100%, 50%)"); // HSL
tinycolor("hsla(0, 100%, 50%, .5)"); // HSLA
tinycolor("red"); // Named
RGB to HEX
var color = tinycolor('rgb(0, 128, 192)');
color.toHexString(); //#0080C0
HEX to RGB
var color = tinycolor('#0080C0');
color.toRgbString(); // rgb(0, 128, 192)
Visit documentation for more demo.
A:
HEX to RGB (ES6) + tests [2022]
convertHexToRgb.ts:
/**
* RGB color regexp
*/
export const RGB_REG_EXP = /rgb\((\d{1,3}), (\d{1,3}), (\d{1,3})\)/;
/**
* HEX color regexp
*/
export const HEX_REG_EXP = /^#?(([\da-f]){3}|([\da-f]){6})$/i;
/**
* Converts HEX to RGB.
*
* Color must be only HEX string and must be:
* - 7-characters starts with "#" symbol ('#ffffff')
* - or 6-characters without "#" symbol ('ffffff')
* - or 4-characters starts with "#" symbol ('#fff')
* - or 3-characters without "#" symbol ('fff')
*
* @function { color: string => string } convertHexToRgb
* @return { string } returns RGB color string or empty string
*/
export const convertHexToRgb = (color: string): string => {
const errMessage = `
Something went wrong while working with colors...
Make sure the colors provided to the "PieDonutChart" meet the following requirements:
Color must be only HEX string and must be
7-characters starts with "#" symbol ('#ffffff')
or 6-characters without "#" symbol ('ffffff')
or 4-characters starts with "#" symbol ('#fff')
or 3-characters without "#" symbol ('fff')
- - - - - - - - -
Error in: "convertHexToRgb" function
Received value: ${color}
`;
if (
!color
|| typeof color !== 'string'
|| color.length < 3
|| color.length > 7
) {
console.error(errMessage);
return '';
}
const replacer = (...args: string[]) => {
const [
_,
r,
g,
b,
] = args;
return '' + r + r + g + g + b + b;
};
const rgbHexArr = color
?.replace(HEX_REG_EXP, replacer)
.match(/.{2}/g)
?.map(x => parseInt(x, 16));
/**
* "HEX_REG_EXP.test" is here to create more strong tests
*/
if (rgbHexArr && Array.isArray(rgbHexArr) && HEX_REG_EXP.test(color)) {
return `rgb(${rgbHexArr[0]}, ${rgbHexArr[1]}, ${rgbHexArr[2]})`;
}
console.error(errMessage);
return '';
};
I'm using Jest for tests
color.spec.ts
describe('function "convertHexToRgb"', () => {
it('returns a valid RGB with the provided 3-digit HEX color: [color = \'fff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('fff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = \'#fff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 6-digit HEX color: [color = \'ffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('ffffff');
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = \'#ffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb(TEST_COLOR);
expect(RGB_REG_EXP.test(rgb)).toBeTruthy();
expect(consoleErrorMocked).not.toHaveBeenCalled();
});
it('returns an empty string when the provided value is not a string: [color = 1234]', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
// @ts-ignore
const rgb = convertHexToRgb(1234);
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided color is too short: [color = \'FF\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('FF');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided color is too long: [color = \'#fffffff\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fffffff');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = \'#fffffp\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('#fffffp');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is invalid: [color = \'*\']', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
const rgb = convertHexToRgb('*');
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
it('returns an empty string when the provided value is undefined: [color = undefined]', () => {
expect.assertions(2);
const { consoleErrorMocked } = mockConsole();
// @ts-ignore
const rgb = convertHexToRgb(undefined);
expect(rgb).toBe('');
expect(consoleErrorMocked).toHaveBeenCalledTimes(1);
});
});
tests result:
function "convertHexToRgb"
√ returns a valid RGB with the provided 3-digit HEX color: [color = 'fff']
√ returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = '#fff']
√ returns a valid RGB with the provided 6-digit HEX color: [color = 'ffffff']
√ returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = '#ffffff']
√ returns an empty string when the provided value is not a string: [color = 1234]
√ returns an empty string when the provided color is too short: [color = 'FF']
√ returns an empty string when the provided color is too long: [color = '#fffffff']
√ returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = '#fffffp']
√ returns an empty string when the provided value is invalid: [color = '*']
√ returns an empty string when the provided value is undefined: [color = undefined]
And mockConsole:
export const mockConsole = () => {
const consoleError = jest.spyOn(console, 'error').mockImplementationOnce(() => undefined);
return { consoleError };
};
A:
RGB to Hex
Using padStart()
You can use this oneliner using padStart():
const rgb = (r, g, b) => {
return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
}
P.S. it isn't supported on legacy browsers, check its compatibility here.
Without padStart()
If you don't want to use padStart(), you can implement this function instead:
const rgb = (r, g, b) => {
return `#${[r, g, b]
.map((n) =>
n.toString(16).length === 1 ? "0" + n.toString(16) : n.toString(16)
)
.join("")}`;
};
Parameters validation
If you're not sure who is going to use your function, you have to use the parameters validations, that the values are valid (between 0 and 255), to do so, add these conditions before each return:
if (r > 255) r = 255; else if (r < 0) r = 0;
if (g > 255) g = 255; else if (g < 0) g = 0;
if (b > 255) b = 255; else if (b < 0) b = 0;
So the two above examples become:
const rgb = (r, g, b) => {
if (r > 255) r = 255; else if (r < 0) r = 0;
if (g > 255) g = 255; else if (g < 0) g = 0;
if (b > 255) b = 255; else if (b < 0) b = 0;
return `#${[r, g, b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
};
const rgb2 = (r, g, b) => {
if (r > 255) r = 255; else if (r < 0) r = 0;
if (g > 255) g = 255; else if (g < 0) g = 0;
if (b > 255) b = 255; else if (b < 0) b = 0;
return `#${[r, g, b]
.map((n) =>
n.toString(16).length === 1 ? "0" + n.toString(16) : n.toString(16)
)
.join("")}`;
};
Hex to RGB
For this, we are going to use some RegEx:
const hex = (h) => {
return h
.replace(
/^#?([a-f\d])([a-f\d])([a-f\d])$/i,
(_, r, g, b) => "#" + r + r + g + g + b + b
)
.substring(1)
.match(/.{2}/g)
.map((x) => parseInt(x, 16));
};
A:
Looks like you're looking for something like this:
function hexstr(number) {
var chars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
var low = number & 0xf;
var high = (number >> 4) & 0xf;
return "" + chars[high] + chars[low];
}
function rgb2hex(r, g, b) {
return "#" + hexstr(r) + hexstr(g) + hexstr(b);
}
A:
My example =)
color: {
toHex: function(num){
var str = num.toString(16);
return (str.length<6?'#00'+str:'#'+str);
},
toNum: function(hex){
return parseInt(hex.replace('#',''), 16);
},
rgbToHex: function(color)
{
color = color.replace(/\s/g,"");
var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i);
if(aRGB)
{
color = '';
for (var i=1; i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1');
}
else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3');
return '#'+color;
}
A:
I'm working with XAML data that has a hex format of #AARRGGBB (Alpha, Red, Green, Blue). Using the answers above, here's my solution:
function hexToRgba(hex) {
var bigint, r, g, b, a;
//Remove # character
var re = /^#?/;
var aRgb = hex.replace(re, '');
bigint = parseInt(aRgb, 16);
//If in #FFF format
if (aRgb.length == 3) {
r = (bigint >> 4) & 255;
g = (bigint >> 2) & 255;
b = bigint & 255;
return "rgba(" + r + "," + g + "," + b + ",1)";
}
//If in #RRGGBB format
if (aRgb.length >= 6) {
r = (bigint >> 16) & 255;
g = (bigint >> 8) & 255;
b = bigint & 255;
var rgb = r + "," + g + "," + b;
//If in #AARRBBGG format
if (aRgb.length == 8) {
a = ((bigint >> 24) & 255) / 255;
return "rgba(" + rgb + "," + a.toFixed(1) + ")";
}
}
return "rgba(" + rgb + ",1)";
}
http://jsfiddle.net/kvLyscs3/
A:
For convert directly from jQuery you can try:
function rgbToHex(color) {
var bg = color.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
}
rgbToHex($('.col-tab-bar .col-tab span').css('color'))
A:
function getRGB(color){
if(color.length == 7){
var r = parseInt(color.substr(1,2),16);
var g = parseInt(color.substr(3,2),16);
var b = parseInt(color.substr(5,2),16);
return 'rgb('+r+','+g+','+b+')' ;
}
else
console.log('Enter correct value');
}
var a = getRGB('#f0f0f0');
if(!a){
a = 'Enter correct value';
}
a;
A:
The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.
function RGBtoHex (red, green, blue) {
red = Math.max(0, Math.min(~~red, 255));
green = Math.max(0, Math.min(~~green, 255));
blue = Math.max(0, Math.min(~~blue, 255));
return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};
The use of left shift '<<' and or '|' operators make this a fun solution too.
A:
I found this and because I think it is pretty straight forward and has validation tests and supports alpha values (optional), this will fit the case.
Just comment out the regex line if you know what you're doing and it's a tiny bit faster.
function hexToRGBA(hex, alpha){
hex = (""+hex).trim().replace(/#/g,""); //trim and remove any leading # if there (supports number values as well)
if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) throw ("not a valid hex string"); //Regex Validator
if (hex.length==3){hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]} //support short form
var b_int = parseInt(hex, 16);
return "rgba("+[
(b_int >> 16) & 255, //R
(b_int >> 8) & 255, //G
b_int & 255, //B
alpha || 1 //add alpha if is set
].join(",")+")";
}
A:
Based on @MichałPerłakowski answer (EcmaScipt 6) and his answer based on Tim Down's answer
I wrote a modified version of the function of converting hexToRGB with the addition of safe checking if the r/g/b color components are between 0-255 and also the funtions can take Number r/g/b params or String r/g/b parameters and here it is:
function rgbToHex(r, g, b) {
r = Math.abs(r);
g = Math.abs(g);
b = Math.abs(b);
if ( r < 0 ) r = 0;
if ( g < 0 ) g = 0;
if ( b < 0 ) b = 0;
if ( r > 255 ) r = 255;
if ( g > 255 ) g = 255;
if ( b > 255 ) b = 255;
return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex
}).join('');
}
To use the function safely - you should ckeck whether the passing string is a real rbg string color - for example a very simple check could be:
if( rgbStr.substring(0,3) === 'rgb' ) {
let rgbColors = JSON.parse(rgbStr.replace('rgb(', '[').replace(')', ']'))
rgbStr = this.rgbToHex(rgbColors[0], rgbColors[1], rgbColors[2]);
.....
}
A:
A total different approach to convert hex color code to RGB without regex
It handles both #FFF and #FFFFFF format on the base of length of string. It removes # from beginning of string and divides each character of string and converts it to base10 and add it to respective index on the base of it's position.
//Algorithm of hex to rgb conversion in ES5
function hex2rgbSimple(str){
str = str.replace('#', '');
return str.split('').reduce(function(result, char, index, array){
var j = parseInt(index * 3/array.length);
var number = parseInt(char, 16);
result[j] = (array.length == 3? number : result[j]) * 16 + number;
return result;
},[0,0,0]);
}
//Same code in ES6
hex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]);
//hex to RGBA conversion
hex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]);
//hex to standard RGB conversion
hex2rgbStandard = str => `RGB(${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`;
console.log(hex2rgb('#aebece'));
console.log(hex2rgbSimple('#aebece'));
console.log(hex2rgb('#aabbcc'));
console.log(hex2rgb('#abc'));
console.log(hex2rgba('#abc', 0.7));
console.log(hex2rgbStandard('#abc'));
A:
When you're working in 3D environment (webGL, ThreeJS) you sometimes need to create 3 values for the different faces of meshes, the basic one (main color), a lighter one and a darker one :
material.color.set( 0x660000, 0xff0000, 0xff6666 ); // red cube
We can create these 3 values from the main RBG color : 255,0,0
function rgbToHex(rgb) {
var hex = Number(rgb).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
};
function convertToHex(r,g,b) {
var fact = 100; // contrast
var code = '0x';
// main color
var r_hexa = rgbToHex(r);
var g_hexa = rgbToHex(g);
var b_hexa = rgbToHex(b);
// lighter
var r_light = rgbToHex(Math.floor(r+((1-(r/255))*fact)));
var g_light = rgbToHex(Math.floor(g+((1-(g/255))*fact)));
var b_light = rgbToHex(Math.floor(b+((1-(b/255))*fact)));
// darker
var r_dark = rgbToHex(Math.floor(r-((r/255)*(fact*1.5)))); // increase contrast
var g_dark = rgbToHex(Math.floor(g-((g/255)*(fact*1.5))));
var b_dark = rgbToHex(Math.floor(b-((b/255)*(fact*1.5))));
var hexa = code+r_hexa+g_hexa+b_hexa;
var light = code+r_light+g_light+b_light;
var dark = code+r_dark+g_dark+b_dark;
console.log('HEXs -> '+dark+" + "+hexa+" + "+light)
var colors = [dark, hexa, light];
return colors;
}
In your ThreeJS code simply write:
var material = new THREE.MeshLambertMaterial();
var c = convertToHex(255,0,0); // red cube needed
material.color.set( Number(c[0]), Number(c[1]), Number(c[2]) );
Results:
// dark normal light
convertToHex(255,255,255) HEXs -> 0x696969 + 0xffffff + 0xffffff
convertToHex(255,0,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464
convertToHex(255,127,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464
convertToHex(100,100,100) HEXs -> 0x292929 + 0x646464 + 0xa0a0a0
convertToHex(10,10,10) HEXs -> 0x040404 + 0x0a0a0a + 0x6a6a6a
A:
Immutable and human understandable version without any bitwise magic:
Loop over array
Normalize value if value < 0 or value > 255 using Math.min() and Math.max()
Convert number to hex notation using String.toString()
Append leading zero and trim value to two characters
join mapped values to string
function rgbToHex(r, g, b) {
return [r, g, b]
.map(color => {
const normalizedColor = Math.max(0, Math.min(255, color));
const hexColor = normalizedColor.toString(16);
return `0${hexColor}`.slice(-2);
})
.join("");
}
Yes, it won't be as performant as bitwise operators but way more readable and immutable so it will not modify any input
A:
HTML converer :)
<!DOCTYPE html>
<html>
<body>
<p id="res"></p>
<script>
function hexToRgb(hex) {
var res = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return "(" + parseInt(res[1], 16) + "," + parseInt(res[2], 16) + "," + parseInt(res[3], 16) + ")";
};
document.getElementById("res").innerHTML = hexToRgb('#0080C0');
</script>
</body>
</html>
A:
To convert from HEX to RGB where RGB are float values within the range of 0 and 1:
#FFAA22 → {r: 0.5, g: 0, b:1}
I adapted @Tim Down’s answer:
function convertRange(value,oldMin,oldMax,newMin,newMax) {
return (Math.round(((((value - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin) * 10000)/10000)
}
function hexToRgbFloat(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: convertRange(parseInt(result[1],16), 0, 255, 0, 1),
g: convertRange(parseInt(result[2],16), 0, 255, 0, 1),
b: convertRange(parseInt(result[3],16), 0, 255, 0, 1)
} : null;
}
console.log(hexToRgbFloat("#FFAA22")) // {r: 1, g: 0.6667, b: 0.1333}
A:
A readable oneliner for rgb string to hex string:
rgb = "rgb(0,128,255)"
hex = '#' + rgb.slice(4,-1).split(',').map(x => (+x).toString(16).padStart(2,0)).join('')
which returns here "#0080ff".
A:
Surprised this answer hasn't come up.
Doesn't use any library #use-the-platform ✔️
3 Lines, and handles any color browsers support.
const toRGB = (color) => {
const { style } = new Option();
style.color = color;
return style.color;
}
// handles any color the browser supports and converts it.
console.log(toRGB("#333")) // rgb(51, 51, 51);
console.log(toRGB("hsl(30, 30%, 30%)"))
|
RGB to hex and hex to RGB
|
How to convert colors in RGB format to hex format and vice versa?
For example, convert '#0080C0' to (0, 128, 192).
|
[
"Note: both versions of rgbToHex expect integer values for r, g and b, so you'll need to do your own rounding if you have non-integer values.\nThe following will do to the RGB to hex conversion and add any required zero padding:\n\n\nfunction componentToHex(c) {\n var hex = c.toString(16);\n return hex.length == 1 ? \"0\" + hex : hex;\n}\n\nfunction rgbToHex(r, g, b) {\n return \"#\" + componentToHex(r) + componentToHex(g) + componentToHex(b);\n}\n\nalert(rgbToHex(0, 51, 255)); // #0033ff\n\n\n\nConverting the other way:\n\n\nfunction hexToRgb(hex) {\n var result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return result ? {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16)\n } : null;\n}\n\nalert(hexToRgb(\"#0033ff\").g); // \"51\";\n\n\n\nFinally, an alternative version of rgbToHex(), as discussed in @casablanca's answer and suggested in the comments by @cwolves:\n\n\nfunction rgbToHex(r, g, b) {\n return \"#\" + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1);\n}\n\nalert(rgbToHex(0, 51, 255)); // #0033ff\n\n\n\nUpdate 3 December 2012\nHere's a version of hexToRgb() that also parses a shorthand hex triplet such as \"#03F\":\n\n\nfunction hexToRgb(hex) {\n // Expand shorthand form (e.g. \"03F\") to full form (e.g. \"0033FF\")\n var shorthandRegex = /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i;\n hex = hex.replace(shorthandRegex, function(m, r, g, b) {\n return r + r + g + g + b + b;\n });\n\n var result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return result ? {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16)\n } : null;\n}\n\nalert(hexToRgb(\"#0033ff\").g); // \"51\";\nalert(hexToRgb(\"#03f\").g); // \"51\";\n\n\n\n",
"An alternative version of hexToRgb:\nfunction hexToRgb(hex) {\n var bigint = parseInt(hex, 16);\n var r = (bigint >> 16) & 255;\n var g = (bigint >> 8) & 255;\n var b = bigint & 255;\n\n return r + \",\" + g + \",\" + b;\n}\n\nEdit: 3/28/2017\nHere is another approach that seems to be even faster\nfunction hexToRgbNew(hex) {\n var arrBuff = new ArrayBuffer(4);\n var vw = new DataView(arrBuff);\n vw.setUint32(0,parseInt(hex, 16),false);\n var arrByte = new Uint8Array(arrBuff);\n\n return arrByte[1] + \",\" + arrByte[2] + \",\" + arrByte[3];\n}\n\nEdit: 8/11/2017\nThe new approach above after more testing is not faster :(. Though it is a fun alternate way.\n",
"ECMAScript 6 version of Tim Down's answer\nConverting RGB to hex\n\n\nconst rgbToHex = (r, g, b) => '#' + [r, g, b].map(x => {\r\n const hex = x.toString(16)\r\n return hex.length === 1 ? '0' + hex : hex\r\n}).join('')\r\n\r\nconsole.log(rgbToHex(0, 51, 255)); // '#0033ff'\n\n\n\nConverting hex to RGB\nReturns an array [r, g, b]. Works also with shorthand hex triplets such as \"#03F\".\n\n\nconst hexToRgb = hex =>\r\n hex.replace(/^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i\r\n ,(m, r, g, b) => '#' + r + r + g + g + b + b)\r\n .substring(1).match(/.{2}/g)\r\n .map(x => parseInt(x, 16))\r\n\r\nconsole.log(hexToRgb(\"#0033ff\")) // [0, 51, 255]\r\nconsole.log(hexToRgb(\"#03f\")) // [0, 51, 255]\n\n\n\nBonus: RGB to hex using padStart() method\n\n\nconst rgbToHex = (r, g, b) => '#' + [r, g, b]\r\n .map(x => x.toString(16).padStart(2, '0')).join('')\r\n\r\nconsole.log(rgbToHex(0, 51, 255)); // '#0033ff'\n\n\n\nNote that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.\n",
"Here's my version:\nfunction rgbToHex(red, green, blue) {\n const rgb = (red << 16) | (green << 8) | (blue << 0);\n return '#' + (0x1000000 + rgb).toString(16).slice(1);\n}\n\nfunction hexToRgb(hex) {\n const normal = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);\n if (normal) return normal.slice(1).map(e => parseInt(e, 16));\n\n const shorthand = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);\n if (shorthand) return shorthand.slice(1).map(e => 0x11 * parseInt(e, 16));\n\n return null;\n}\n\n",
"function hex2rgb(hex) {\n return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];\n}\n\n",
"I'm assuming you mean HTML-style hexadecimal notation, i.e. #rrggbb. Your code is almost correct, except you've got the order reversed. It should be:\nvar decColor = red * 65536 + green * 256 + blue;\n\nAlso, using bit-shifts might make it a bit easier to read:\nvar decColor = (red << 16) + (green << 8) + blue;\n\n",
"One-line functional HEX to RGBA\nSupports both short #fff and long #ffffff forms.\nSupports alpha channel (opacity).\nDoes not care if hash specified or not, works in both cases.\nfunction hexToRGBA(hex, opacity) {\n return 'rgba(' + (hex = hex.replace('#', '')).match(new RegExp('(.{' + hex.length/3 + '})', 'g')).map(function(l) { return parseInt(hex.length%2 ? l+l : l, 16) }).concat(isFinite(opacity) ? opacity : 1).join(',') + ')';\n}\n\nexamples:\nhexToRGBA('#fff') -> rgba(255,255,255,1) \nhexToRGBA('#ffffff') -> rgba(255,255,255,1) \nhexToRGBA('#fff', .2) -> rgba(255,255,255,0.2) \nhexToRGBA('#ffffff', .2) -> rgba(255,255,255,0.2) \nhexToRGBA('fff', .2) -> rgba(255,255,255,0.2) \nhexToRGBA('ffffff', .2) -> rgba(255,255,255,0.2)\n\nhexToRGBA('#ffffff', 0) -> rgba(255,255,255,0)\nhexToRGBA('#ffffff', .5) -> rgba(255,255,255,0.5)\nhexToRGBA('#ffffff', 1) -> rgba(255,255,255,1)\n\n",
"Try (bonus)\nlet hex2rgb= c=> `rgb(${c.match(/\\w\\w/g).map(x=>+`0x${x}`)})`\nlet rgb2hex=c=>'#'+c.match(/\\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``\n\n\n\nlet hex2rgb= c=> `rgb(${c.match(/\\w\\w/g).map(x=>+`0x${x}`)})`;\nlet rgb2hex= c=> '#'+c.match(/\\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``;\n\n// TEST\nconsole.log('#0080C0 -->', hex2rgb('#0080C0'));\nconsole.log('rgb(0, 128, 192) -->', rgb2hex('rgb(0, 128, 192)'));\n\n\n\n",
"This code accept #fff and #ffffff variants and opacity.\nfunction hex2rgb(hex, opacity) {\n var h=hex.replace('#', '');\n h = h.match(new RegExp('(.{'+h.length/3+'})', 'g'));\n\n for(var i=0; i<h.length; i++)\n h[i] = parseInt(h[i].length==1? h[i]+h[i]:h[i], 16);\n\n if (typeof opacity != 'undefined') h.push(opacity);\n\n return 'rgba('+h.join(',')+')';\n}\n\n",
"Bitwise solution normally is weird. But in this case I guess that is more elegant \nfunction hexToRGB(hexColor){\n return {\n red: (hexColor >> 16) & 0xFF,\n green: (hexColor >> 8) & 0xFF, \n blue: hexColor & 0xFF,\n }\n}\n\nUsage:\nconst {red, green, blue } = hexToRGB(0xFF00FF)\n\nconsole.log(red) // 255\nconsole.log(green) // 0\nconsole.log(blue) // 255\n\n",
"(2017) SIMPLE ES6 composable arrow functions\nI can't resist sharing this for those who may be writing some modern functional/compositional js using ES6. Here are some slick one-liners I am using in a color module that does color interpolation for data visualization.\nNote that this does not handle the alpha channel at all.\nconst arrayToRGBString = rgb => `rgb(${rgb.join(',')})`;\nconst hexToRGBArray = hex => hex.match(/[A-Za-z0-9]{2}/g).map(v => parseInt(v, 16));\nconst rgbArrayToHex = rgb => `#${rgb.map(v => v.toString(16).padStart(2, '0')).join('')}`;\nconst rgbStringToArray = rgb => rgb.match(/^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/).splice(1, 3)\n .map(v => Number(v));\nconst rgbStringToHex = rgb => rgbArrayToHex(rgbStringToArray(rgb));\n\nBTW, If you like this style/syntax, I wrote a full color module (modern-color) you can grab from npm. I made it so I could use prop getters for conversion and parse virtually anything (Color.parse(anything)). Worth a look if you deal with color a lot like I do.\n",
"This could be used for getting colors from computed style propeties:\nfunction rgbToHex(color) {\n color = \"\"+ color;\n if (!color || color.indexOf(\"rgb\") < 0) {\n return;\n }\n\n if (color.charAt(0) == \"#\") {\n return color;\n }\n\n var nums = /(.*?)rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)/i.exec(color),\n r = parseInt(nums[2], 10).toString(16),\n g = parseInt(nums[3], 10).toString(16),\n b = parseInt(nums[4], 10).toString(16);\n\n return \"#\"+ (\n (r.length == 1 ? \"0\"+ r : r) +\n (g.length == 1 ? \"0\"+ g : g) +\n (b.length == 1 ? \"0\"+ b : b)\n );\n}\n\n// not computed \n<div style=\"color: #4d93bc; border: 1px solid red;\">...</div> \n// computed \n<div style=\"color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);\">...</div>\n\nconsole.log( rgbToHex(color) ) // #4d93bc\nconsole.log( rgbToHex(borderTopColor) ) // #ff0000\n\nRef: https://github.com/k-gun/so/blob/master/so_util.js\n",
"Hex to RGB\n\n\nconst hex2rgb = (hex) => {\n const r = parseInt(hex.slice(1, 3), 16)\n const g = parseInt(hex.slice(3, 5), 16)\n const b = parseInt(hex.slice(5, 7), 16)\n // return {r, g, b} // return an object\n return [ r, g, b ]\n}\nconsole.log(hex2rgb(\"#0080C0\"))\n\n\n\nRGB to Hex\n\n\nconst rgb2hex = (r, g, b) => {\n var rgb = (r << 16) | (g << 8) | b\n // return '#' + rgb.toString(16) // #80c0\n // return '#' + (0x1000000 + rgb).toString(16).slice(1) // #0080c0\n // or use [padStart](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)\n return '#' + rgb.toString(16).padStart(6, 0) \n}\nconsole.log(rgb2hex(0, 128, 192))\n\n\n\nAlso if someone need online tool, I have built Hex to RGB and vice versa.\n",
"May you be after something like this?\nfunction RGB2HTML(red, green, blue)\n{\n return '#' + red.toString(16) +\n green.toString(16) +\n blue.toString(16);\n}\n\nalert(RGB2HTML(150, 135, 200));\n\ndisplays #9687c8\n",
"// Ignoring hsl notation, color values are commonly expressed as names, rgb, rgba or hex-\n// Hex can be 3 values or 6.\n// Rgb can be percentages as well as integer values.\n// Best to account for all of these formats, at least.\nString.prototype.padZero= function(len, c){\n var s= this, c= c || \"0\", len= len || 2;\n while(s.length < len) s= c + s;\n return s;\n}\nvar colors={\n colornames:{\n aqua: '#00ffff', black: '#000000', blue: '#0000ff', fuchsia: '#ff00ff',\n gray: '#808080', green: '#008000', lime: '#00ff00', maroon: '#800000',\n navy: '#000080', olive: '#808000', purple: '#800080', red: '#ff0000',\n silver: '#c0c0c0', teal: '#008080', white: '#ffffff', yellow: '#ffff00'\n },\n toRgb: function(c){\n c= '0x'+colors.toHex(c).substring(1);\n c= [(c>> 16)&255, (c>> 8)&255, c&255];\n return 'rgb('+c.join(',')+')';\n },\n toHex: function(c){\n var tem, i= 0, c= c? c.toString().toLowerCase(): '';\n if(/^#[a-f0-9]{3,6}$/.test(c)){\n if(c.length< 7){\n var A= c.split('');\n c= A[0]+A[1]+A[1]+A[2]+A[2]+A[3]+A[3];\n }\n return c;\n }\n if(/^[a-z]+$/.test(c)){\n return colors.colornames[c] || '';\n }\n c= c.match(/\\d+(\\.\\d+)?%?/g) || [];\n if(c.length<3) return '';\n c= c.slice(0, 3);\n while(i< 3){\n tem= c[i];\n if(tem.indexOf('%')!= -1){\n tem= Math.round(parseFloat(tem)*2.55);\n }\n else tem= parseInt(tem);\n if(tem< 0 || tem> 255) c.length= 0;\n else c[i++]= tem.toString(16).padZero(2);\n }\n if(c.length== 3) return '#'+c.join('').toLowerCase();\n return '';\n }\n}\n//var c='#dc149c';\n//var c='rgb(100%,25%,0)';\n//\nvar c= 'red';\nalert(colors.toRgb(c)+'\\n'+colors.toHex(c));\n\n",
"@ Tim, to add to your answer (its a little awkward fitting this into a comment).\nAs written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.\nI'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.\nfunction rgbToHex(r, g, b) {\n if(r < 0 || r > 255) alert(\"r is out of bounds; \"+r);\n if(g < 0 || g > 255) alert(\"g is out of bounds; \"+g);\n if(b < 0 || b > 255) alert(\"b is out of bounds; \"+b);\n return \"#\" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);\n}\n\n",
"If you need compare two color values (given as RGB, name color or hex value) or convert to HEX use HTML5 canvas object.\nvar canvas = document.createElement(\"canvas\");\nvar ctx = this.canvas.getContext('2d');\n\nctx.fillStyle = \"rgb(pass,some,value)\";\nvar temp = ctx.fillStyle;\nctx.fillStyle = \"someColor\";\n\nalert(ctx.fillStyle == temp);\n\n",
"2021 version\nYou can simply use rgb-hex & hex-rgb as it is battle-tested & has multiple options that are not available in other solutions.\nI was recently building a Color Picker & these 2 packages came in handy.\nUsage\nrgb-hex\nimport rgbHex from 'rgb-hex';\n\nrgbHex(65, 131, 196);\n//=> '4183c4'\n\nrgbHex('rgb(40, 42, 54)');\n//=> '282a36'\n\nrgbHex(65, 131, 196, 0.2);\n//=> '4183c433'\n\nrgbHex(40, 42, 54, '75%');\n//=> '282a36bf'\n\nrgbHex('rgba(40, 42, 54, 75%)');\n//=> '282a36bf'\n\nhex-rgb\nimport hexRgb from 'hex-rgb';\n\nhexRgb('4183c4');\n//=> {red: 65, green: 131, blue: 196, alpha: 1}\n\nhexRgb('#4183c4');\n//=> {red: 65, green: 131, blue: 196, alpha: 1}\n\nhexRgb('#fff');\n//=> {red: 255, green: 255, blue: 255, alpha: 1}\n\nhexRgb('#22222299');\n//=> {red: 34, green: 34, blue: 34, alpha: 0.6}\n\nhexRgb('#0006');\n//=> {red: 0, green: 0, blue: 0, alpha: 0.4}\n\nhexRgb('#cd2222cc');\n//=> {red: 205, green: 34, blue: 34, alpha: 0.8}\n\nhexRgb('#cd2222cc', {format: 'array'});\n//=> [205, 34, 34, 0.8]\n\nhexRgb('#cd2222cc', {format: 'css'});\n//=> 'rgb(205 34 34 / 80%)'\n\nhexRgb('#000', {format: 'css'});\n//=> 'rgb(0 0 0)'\n\nhexRgb('#22222299', {alpha: 1});\n//=> {red: 34, green: 34, blue: 34, alpha: 1}\n\nhexRgb('#fff', {alpha: 0.5});\n//=> {red: 255, green: 255, blue: 255, alpha: 0.5}\n\n",
"Shorthand version that accepts a string:\n\n\nfunction rgbToHex(a){\r\n a=a.replace(/[^\\d,]/g,\"\").split(\",\"); \r\n return\"#\"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)\r\n}\r\n\r\ndocument.write(rgbToHex(\"rgb(255,255,255)\"));\n\n\n\nTo check if it's not already hexadecimal\n\n\nfunction rgbToHex(a){\r\n if(~a.indexOf(\"#\"))return a;\r\n a=a.replace(/[^\\d,]/g,\"\").split(\",\"); \r\n return\"#\"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)\r\n}\r\n\r\ndocument.write(\"rgb: \"+rgbToHex(\"rgb(255,255,255)\")+ \" -- hex: \"+rgbToHex(\"#e2e2e2\"));\n\n\n\n",
"I came across this problem since I wanted to parse any color string value and be able to specify an opacity, so I wrote this function that uses the canvas API.\nvar toRGBA = function () {\n var canvas = document.createElement('canvas');\n var context = canvas.getContext('2d');\n\n canvas.width = 1;\n canvas.height = 1;\n\n return function (color) {\n context.fillStyle = color;\n context.fillRect(0, 0, 1, 1);\n\n var data = context.getImageData(0, 0, 1, 1).data;\n\n return {\n r: data[0],\n g: data[1],\n b: data[2],\n a: data[3]\n };\n };\n}();\n\nNote about context.fillStyle:\n\nIf parsing the value results in failure, then it must be ignored, and the attribute must retain its previous value.\n\nHere's a Stack Snippet demo you can use to test inputs:\n\n\nvar toRGBA = function () {\n var canvas = document.createElement('canvas');\n var context = canvas.getContext('2d');\n\n canvas.width = 1;\n canvas.height = 1;\n\n return function (color) {\n context.fillStyle = color;\n context.fillRect(0, 0, 1, 1);\n\n var data = context.getImageData(0, 0, 1, 1).data;\n\n return {\n r: data[0],\n g: data[1],\n b: data[2],\n a: data[3]\n };\n };\n}();\n\nvar inputs = document.getElementsByTagName('input');\n\nfunction setColor() {\n inputs[1].value = JSON.stringify(toRGBA(inputs[0].value));\n document.body.style.backgroundColor = inputs[0].value;\n}\n\ninputs[0].addEventListener('input', setColor);\nsetColor();\ninput {\n width: 200px;\n margin: 0.5rem;\n}\n<input value=\"cyan\" />\n<input readonly=\"readonly\" />\n\n\n\n",
"i needed a function that accepts invalid values too like\nrgb(-255, 255, 255)\nrgb(510, 255, 255)\nthis is a spin off of @cwolves answer\nfunction rgb(r, g, b) {\n this.c = this.c || function (n) {\n return Math.max(Math.min(n, 255), 0)\n };\n\n return ((1 << 24) + (this.c(r) << 16) + (this.c(g) << 8) + this.c(b)).toString(16).slice(1).toUpperCase();\n}\n\n",
"R = HexToR(\"#FFFFFF\");\nG = HexToG(\"#FFFFFF\");\nB = HexToB(\"#FFFFFF\");\n\nfunction HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}\nfunction HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}\nfunction HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}\nfunction cutHex(h) {return (h.charAt(0)==\"#\") ? h.substring(1,7):h}\n\nUse these Function to achive the result without any issue. :)\n",
"Instead of copy'n'pasting snippets found here and there, I'd recommend to use a well tested and maintained library: Colors.js (available for node.js and browser). It's just 7 KB (minified, gzipped even less).\n",
"A simple answer to convert RGB to hex. Here values of color channels are clamped between 0 and 255.\nfunction RGBToHex(r = 0, g = 0, b = 0) {\n // clamp and convert to hex\n let hr = Math.max(0, Math.min(255, Math.round(r))).toString(16);\n let hg = Math.max(0, Math.min(255, Math.round(g))).toString(16);\n let hb = Math.max(0, Math.min(255, Math.round(b))).toString(16);\n return \"#\" +\n (hr.length<2?\"0\":\"\") + hr +\n (hg.length<2?\"0\":\"\") + hg +\n (hb.length<2?\"0\":\"\") + hb;\n}\n\n",
"This snippet converts hex to rgb and rgb to hex.\nView demo\nfunction hexToRgb(str) { \n if ( /^#([0-9a-f]{3}|[0-9a-f]{6})$/ig.test(str) ) { \n var hex = str.substr(1);\n hex = hex.length == 3 ? hex.replace(/(.)/g, '$1$1') : hex;\n var rgb = parseInt(hex, 16); \n return 'rgb(' + [(rgb >> 16) & 255, (rgb >> 8) & 255, rgb & 255].join(',') + ')';\n } \n\n return false; \n}\n\nfunction rgbToHex(red, green, blue) {\n var out = '#';\n\n for (var i = 0; i < 3; ++i) {\n var n = typeof arguments[i] == 'number' ? arguments[i] : parseInt(arguments[i]);\n\n if (isNaN(n) || n < 0 || n > 255) {\n return false;\n }\n\n out += (n < 16 ? '0' : '') + n.toString(16);\n }\n return out\n}\n\n",
"My version of hex2rbg:\n\nAccept short hex like #fff \nAlgorithm compacity is o(n), should faster than using regex. e.g String.replace, String.split, String.match etc..\nUse constant space. \nSupport rgb and rgba. \n\nyou may need remove hex.trim() if you are using IE8.\ne.g. \nhex2rgb('#fff') //rgb(255,255,255) \nhex2rgb('#fff', 1) //rgba(255,255,255,1) \nhex2rgb('#ffffff') //rgb(255,255,255) \nhex2rgb('#ffffff', 1) //rgba(255,255,255,1)\n\ncode:\nfunction hex2rgb (hex, opacity) {\n hex = hex.trim();\n hex = hex[0] === '#' ? hex.substr(1) : hex;\n var bigint = parseInt(hex, 16), h = [];\n if (hex.length === 3) {\n h.push((bigint >> 4) & 255);\n h.push((bigint >> 2) & 255);\n } else {\n h.push((bigint >> 16) & 255);\n h.push((bigint >> 8) & 255);\n }\n h.push(bigint & 255);\n if (arguments.length === 2) {\n h.push(opacity);\n return 'rgba('+h.join()+')';\n } else {\n return 'rgb('+h.join()+')';\n }\n}\n\n",
"While this answer is unlikely to fit the question perfectly it may be very useful none the less.\n\nCreate any random element\n\nvar toRgb = document.createElement('div');\n\nSet any valid style to the color you want to convert\n\ntoRg.style.color = \"hsl(120, 60%, 70%)\";\n\nCall the style property again\n\n> toRgb.style.color;\n< \"rgb(133, 225, 133)\" Your color has been converted to Rgb\nWorks for: Hsl, Hex\nDoes not work for: Named colors\n",
"I realise there are lots of answers to this but if you're like me and you know your HEX is always going to be 6 characters with or without the # prefix then this is probably the simplest method if you want to do some quick inline stuff. It does not care if it starts with or without a hash.\nvar hex = \"#ffffff\";\nvar rgb = [\n parseInt(hex.substr(-6,2),16),\n parseInt(hex.substr(-4,2),16),\n parseInt(hex.substr(-2),16)\n];\n\n",
"2022: If you often manipulate colors and doesn't mind using a package,\nUse tinycolor2. It's a fast library (Around 400kb) for color manipulation and conversion in JavaScript.\nIt accepts various color string format. Like:\ntinycolor(\"#000\"); // Hex3\ntinycolor(\"#f0f0f6\"); // Hex6\ntinycolor(\"#f0f0f688\"); // Hex8\ntinycolor(\"f0f0f6\"); // Hex withouth the number sign '#'\ntinycolor(\"rgb (255, 0, 0)\"); // RGB\ntinycolor(\"rgba (255, 0, 0, .5)\"); // RGBA\ntinycolor({ r: 255, g: 0, b: 0 }); // RGB object\ntinycolor(\"hsl(0, 100%, 50%)\"); // HSL\ntinycolor(\"hsla(0, 100%, 50%, .5)\"); // HSLA\ntinycolor(\"red\"); // Named\n\nRGB to HEX\nvar color = tinycolor('rgb(0, 128, 192)');\ncolor.toHexString(); //#0080C0\n\nHEX to RGB\nvar color = tinycolor('#0080C0');\ncolor.toRgbString(); // rgb(0, 128, 192)\n\nVisit documentation for more demo.\n",
"HEX to RGB (ES6) + tests [2022]\nconvertHexToRgb.ts:\n/**\n * RGB color regexp\n */\nexport const RGB_REG_EXP = /rgb\\((\\d{1,3}), (\\d{1,3}), (\\d{1,3})\\)/;\n\n/**\n * HEX color regexp\n */\nexport const HEX_REG_EXP = /^#?(([\\da-f]){3}|([\\da-f]){6})$/i;\n\n/**\n * Converts HEX to RGB.\n *\n * Color must be only HEX string and must be:\n * - 7-characters starts with \"#\" symbol ('#ffffff')\n * - or 6-characters without \"#\" symbol ('ffffff')\n * - or 4-characters starts with \"#\" symbol ('#fff')\n * - or 3-characters without \"#\" symbol ('fff')\n *\n * @function { color: string => string } convertHexToRgb\n * @return { string } returns RGB color string or empty string\n */\nexport const convertHexToRgb = (color: string): string => {\n const errMessage = `\n Something went wrong while working with colors...\n \n Make sure the colors provided to the \"PieDonutChart\" meet the following requirements:\n \n Color must be only HEX string and must be \n 7-characters starts with \"#\" symbol ('#ffffff')\n or 6-characters without \"#\" symbol ('ffffff')\n or 4-characters starts with \"#\" symbol ('#fff')\n or 3-characters without \"#\" symbol ('fff')\n \n - - - - - - - - -\n \n Error in: \"convertHexToRgb\" function\n Received value: ${color}\n `;\n\n if (\n !color\n || typeof color !== 'string'\n || color.length < 3\n || color.length > 7\n ) {\n console.error(errMessage);\n return '';\n }\n\n const replacer = (...args: string[]) => {\n const [\n _,\n r,\n g,\n b,\n ] = args;\n\n return '' + r + r + g + g + b + b;\n };\n\n const rgbHexArr = color\n ?.replace(HEX_REG_EXP, replacer)\n .match(/.{2}/g)\n ?.map(x => parseInt(x, 16));\n\n /**\n * \"HEX_REG_EXP.test\" is here to create more strong tests\n */\n if (rgbHexArr && Array.isArray(rgbHexArr) && HEX_REG_EXP.test(color)) {\n return `rgb(${rgbHexArr[0]}, ${rgbHexArr[1]}, ${rgbHexArr[2]})`;\n }\n\n console.error(errMessage);\n return '';\n};\n\n\nI'm using Jest for tests\n\ncolor.spec.ts\ndescribe('function \"convertHexToRgb\"', () => {\n it('returns a valid RGB with the provided 3-digit HEX color: [color = \\'fff\\']', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n const rgb = convertHexToRgb('fff');\n\n expect(RGB_REG_EXP.test(rgb)).toBeTruthy();\n expect(consoleErrorMocked).not.toHaveBeenCalled();\n });\n\n it('returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = \\'#fff\\']', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n const rgb = convertHexToRgb('#fff');\n\n expect(RGB_REG_EXP.test(rgb)).toBeTruthy();\n expect(consoleErrorMocked).not.toHaveBeenCalled();\n });\n\n it('returns a valid RGB with the provided 6-digit HEX color: [color = \\'ffffff\\']', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n const rgb = convertHexToRgb('ffffff');\n\n expect(RGB_REG_EXP.test(rgb)).toBeTruthy();\n expect(consoleErrorMocked).not.toHaveBeenCalled();\n });\n\n it('returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = \\'#ffffff\\']', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n const rgb = convertHexToRgb(TEST_COLOR);\n\n expect(RGB_REG_EXP.test(rgb)).toBeTruthy();\n expect(consoleErrorMocked).not.toHaveBeenCalled();\n });\n\n it('returns an empty string when the provided value is not a string: [color = 1234]', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n\n // @ts-ignore\n const rgb = convertHexToRgb(1234);\n\n expect(rgb).toBe('');\n expect(consoleErrorMocked).toHaveBeenCalledTimes(1);\n });\n\n it('returns an empty string when the provided color is too short: [color = \\'FF\\']', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n\n const rgb = convertHexToRgb('FF');\n\n expect(rgb).toBe('');\n expect(consoleErrorMocked).toHaveBeenCalledTimes(1);\n });\n\n it('returns an empty string when the provided color is too long: [color = \\'#fffffff\\']', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n\n const rgb = convertHexToRgb('#fffffff');\n\n expect(rgb).toBe('');\n expect(consoleErrorMocked).toHaveBeenCalledTimes(1);\n });\n\n it('returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = \\'#fffffp\\']', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n const rgb = convertHexToRgb('#fffffp');\n\n expect(rgb).toBe('');\n expect(consoleErrorMocked).toHaveBeenCalledTimes(1);\n });\n\n it('returns an empty string when the provided value is invalid: [color = \\'*\\']', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n\n const rgb = convertHexToRgb('*');\n\n expect(rgb).toBe('');\n expect(consoleErrorMocked).toHaveBeenCalledTimes(1);\n });\n\n it('returns an empty string when the provided value is undefined: [color = undefined]', () => {\n expect.assertions(2);\n\n const { consoleErrorMocked } = mockConsole();\n\n // @ts-ignore\n const rgb = convertHexToRgb(undefined);\n\n expect(rgb).toBe('');\n expect(consoleErrorMocked).toHaveBeenCalledTimes(1);\n });\n});\n\ntests result:\nfunction \"convertHexToRgb\"\n √ returns a valid RGB with the provided 3-digit HEX color: [color = 'fff']\n √ returns a valid RGB with the provided 3-digit HEX color with hash symbol: [color = '#fff']\n √ returns a valid RGB with the provided 6-digit HEX color: [color = 'ffffff']\n √ returns a valid RGB with the provided 6-digit HEX color with the hash symbol: [color = '#ffffff']\n √ returns an empty string when the provided value is not a string: [color = 1234]\n √ returns an empty string when the provided color is too short: [color = 'FF']\n √ returns an empty string when the provided color is too long: [color = '#fffffff']\n √ returns an empty string when the provided value is looks like HEX color string but has invalid symbols: [color = '#fffffp']\n √ returns an empty string when the provided value is invalid: [color = '*']\n √ returns an empty string when the provided value is undefined: [color = undefined]\n\nAnd mockConsole:\nexport const mockConsole = () => {\n const consoleError = jest.spyOn(console, 'error').mockImplementationOnce(() => undefined);\n return { consoleError };\n};\n\n",
"RGB to Hex\nUsing padStart()\nYou can use this oneliner using padStart():\n\n\nconst rgb = (r, g, b) => {\n return `#${[r, g, b].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n\n\nP.S. it isn't supported on legacy browsers, check its compatibility here.\nWithout padStart()\nIf you don't want to use padStart(), you can implement this function instead:\n\n\nconst rgb = (r, g, b) => {\n return `#${[r, g, b]\n .map((n) =>\n n.toString(16).length === 1 ? \"0\" + n.toString(16) : n.toString(16)\n )\n .join(\"\")}`;\n};\n\n\n\nParameters validation\nIf you're not sure who is going to use your function, you have to use the parameters validations, that the values are valid (between 0 and 255), to do so, add these conditions before each return:\n\n\nif (r > 255) r = 255; else if (r < 0) r = 0;\nif (g > 255) g = 255; else if (g < 0) g = 0;\nif (b > 255) b = 255; else if (b < 0) b = 0;\n\n\n\nSo the two above examples become:\n\n\nconst rgb = (r, g, b) => {\n if (r > 255) r = 255; else if (r < 0) r = 0;\n if (g > 255) g = 255; else if (g < 0) g = 0;\n if (b > 255) b = 255; else if (b < 0) b = 0;\n return `#${[r, g, b].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\")}`;\n};\n\nconst rgb2 = (r, g, b) => {\n if (r > 255) r = 255; else if (r < 0) r = 0;\n if (g > 255) g = 255; else if (g < 0) g = 0;\n if (b > 255) b = 255; else if (b < 0) b = 0;\n return `#${[r, g, b]\n .map((n) =>\n n.toString(16).length === 1 ? \"0\" + n.toString(16) : n.toString(16)\n )\n .join(\"\")}`;\n};\n\n\n\n\nHex to RGB\nFor this, we are going to use some RegEx:\n\n\nconst hex = (h) => {\n return h\n .replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_, r, g, b) => \"#\" + r + r + g + g + b + b\n )\n .substring(1)\n .match(/.{2}/g)\n .map((x) => parseInt(x, 16));\n};\n\n\n\n",
"Looks like you're looking for something like this:\nfunction hexstr(number) {\n var chars = new Array(\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n var low = number & 0xf;\n var high = (number >> 4) & 0xf;\n return \"\" + chars[high] + chars[low];\n}\n\nfunction rgb2hex(r, g, b) {\n return \"#\" + hexstr(r) + hexstr(g) + hexstr(b);\n}\n\n",
"My example =)\n\n\ncolor: {\r\n toHex: function(num){\r\n var str = num.toString(16);\r\n return (str.length<6?'#00'+str:'#'+str);\r\n },\r\n toNum: function(hex){\r\n return parseInt(hex.replace('#',''), 16);\r\n },\r\n rgbToHex: function(color)\r\n {\r\n color = color.replace(/\\s/g,\"\");\r\n var aRGB = color.match(/^rgb\\((\\d{1,3}[%]?),(\\d{1,3}[%]?),(\\d{1,3}[%]?)\\)$/i);\r\n if(aRGB)\r\n {\r\n color = '';\r\n for (var i=1; i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]==\"%\"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1');\r\n }\r\n else color = color.replace(/^#?([\\da-f])([\\da-f])([\\da-f])$/i, '$1$1$2$2$3$3');\r\n return '#'+color;\r\n }\n\n\n\n",
"I'm working with XAML data that has a hex format of #AARRGGBB (Alpha, Red, Green, Blue). Using the answers above, here's my solution: \nfunction hexToRgba(hex) {\n var bigint, r, g, b, a;\n //Remove # character\n var re = /^#?/;\n var aRgb = hex.replace(re, '');\n bigint = parseInt(aRgb, 16);\n\n //If in #FFF format\n if (aRgb.length == 3) {\n r = (bigint >> 4) & 255;\n g = (bigint >> 2) & 255;\n b = bigint & 255;\n return \"rgba(\" + r + \",\" + g + \",\" + b + \",1)\";\n }\n\n //If in #RRGGBB format\n if (aRgb.length >= 6) {\n r = (bigint >> 16) & 255;\n g = (bigint >> 8) & 255;\n b = bigint & 255;\n var rgb = r + \",\" + g + \",\" + b;\n\n //If in #AARRBBGG format\n if (aRgb.length == 8) {\n a = ((bigint >> 24) & 255) / 255;\n return \"rgba(\" + rgb + \",\" + a.toFixed(1) + \")\";\n }\n }\n return \"rgba(\" + rgb + \",1)\";\n}\n\nhttp://jsfiddle.net/kvLyscs3/\n",
"For convert directly from jQuery you can try:\n function rgbToHex(color) {\n var bg = color.match(/^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/);\n function hex(x) {\n return (\"0\" + parseInt(x).toString(16)).slice(-2);\n }\n return \"#\" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);\n }\n\n rgbToHex($('.col-tab-bar .col-tab span').css('color'))\n\n",
"function getRGB(color){\n if(color.length == 7){\n var r = parseInt(color.substr(1,2),16);\n var g = parseInt(color.substr(3,2),16);\n var b = parseInt(color.substr(5,2),16); \n return 'rgb('+r+','+g+','+b+')' ;\n } \n else\n console.log('Enter correct value');\n}\nvar a = getRGB('#f0f0f0');\nif(!a){\n a = 'Enter correct value'; \n}\n\na;\n\n",
"The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.\nfunction RGBtoHex (red, green, blue) {\n red = Math.max(0, Math.min(~~red, 255));\n green = Math.max(0, Math.min(~~green, 255));\n blue = Math.max(0, Math.min(~~blue, 255));\n\n return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);\n};\n\nThe use of left shift '<<' and or '|' operators make this a fun solution too.\n",
"I found this and because I think it is pretty straight forward and has validation tests and supports alpha values (optional), this will fit the case.\nJust comment out the regex line if you know what you're doing and it's a tiny bit faster.\nfunction hexToRGBA(hex, alpha){\n hex = (\"\"+hex).trim().replace(/#/g,\"\"); //trim and remove any leading # if there (supports number values as well)\n if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) throw (\"not a valid hex string\"); //Regex Validator\n if (hex.length==3){hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]} //support short form\n var b_int = parseInt(hex, 16);\n return \"rgba(\"+[\n (b_int >> 16) & 255, //R\n (b_int >> 8) & 255, //G\n b_int & 255, //B\n alpha || 1 //add alpha if is set\n ].join(\",\")+\")\";\n}\n\n",
"Based on @MichałPerłakowski answer (EcmaScipt 6) and his answer based on Tim Down's answer\nI wrote a modified version of the function of converting hexToRGB with the addition of safe checking if the r/g/b color components are between 0-255 and also the funtions can take Number r/g/b params or String r/g/b parameters and here it is:\n function rgbToHex(r, g, b) {\n r = Math.abs(r);\n g = Math.abs(g);\n b = Math.abs(b);\n\n if ( r < 0 ) r = 0;\n if ( g < 0 ) g = 0;\n if ( b < 0 ) b = 0;\n\n if ( r > 255 ) r = 255;\n if ( g > 255 ) g = 255;\n if ( b > 255 ) b = 255;\n\n return '#' + [r, g, b].map(x => {\n const hex = x.toString(16);\n return hex.length === 1 ? '0' + hex : hex\n }).join('');\n }\n\nTo use the function safely - you should ckeck whether the passing string is a real rbg string color - for example a very simple check could be: \nif( rgbStr.substring(0,3) === 'rgb' ) {\n\n let rgbColors = JSON.parse(rgbStr.replace('rgb(', '[').replace(')', ']'))\n rgbStr = this.rgbToHex(rgbColors[0], rgbColors[1], rgbColors[2]);\n\n .....\n}\n\n",
"A total different approach to convert hex color code to RGB without regex\nIt handles both #FFF and #FFFFFF format on the base of length of string. It removes # from beginning of string and divides each character of string and converts it to base10 and add it to respective index on the base of it's position.\n\n\n//Algorithm of hex to rgb conversion in ES5\r\nfunction hex2rgbSimple(str){\r\n str = str.replace('#', '');\r\n return str.split('').reduce(function(result, char, index, array){\r\n var j = parseInt(index * 3/array.length);\r\n var number = parseInt(char, 16);\r\n result[j] = (array.length == 3? number : result[j]) * 16 + number;\r\n return result;\r\n },[0,0,0]);\r\n}\r\n\r\n//Same code in ES6\r\nhex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]);\r\n\r\n//hex to RGBA conversion\r\nhex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]);\r\n\r\n//hex to standard RGB conversion\r\nhex2rgbStandard = str => `RGB(${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`;\r\n\r\n\r\nconsole.log(hex2rgb('#aebece'));\r\nconsole.log(hex2rgbSimple('#aebece'));\r\n\r\nconsole.log(hex2rgb('#aabbcc'));\r\n\r\nconsole.log(hex2rgb('#abc'));\r\n\r\nconsole.log(hex2rgba('#abc', 0.7));\r\n\r\nconsole.log(hex2rgbStandard('#abc'));\n\n\n\n",
"When you're working in 3D environment (webGL, ThreeJS) you sometimes need to create 3 values for the different faces of meshes, the basic one (main color), a lighter one and a darker one : \nmaterial.color.set( 0x660000, 0xff0000, 0xff6666 ); // red cube\n\nWe can create these 3 values from the main RBG color : 255,0,0\nfunction rgbToHex(rgb) { \n var hex = Number(rgb).toString(16);\n if (hex.length < 2) {\n hex = \"0\" + hex;\n }\n return hex;\n};\n\nfunction convertToHex(r,g,b) { \n\n var fact = 100; // contrast \n var code = '0x';\n\n // main color\n var r_hexa = rgbToHex(r);\n var g_hexa = rgbToHex(g);\n var b_hexa = rgbToHex(b);\n\n // lighter\n var r_light = rgbToHex(Math.floor(r+((1-(r/255))*fact)));\n var g_light = rgbToHex(Math.floor(g+((1-(g/255))*fact)));\n var b_light = rgbToHex(Math.floor(b+((1-(b/255))*fact)));\n\n // darker\n var r_dark = rgbToHex(Math.floor(r-((r/255)*(fact*1.5)))); // increase contrast\n var g_dark = rgbToHex(Math.floor(g-((g/255)*(fact*1.5))));\n var b_dark = rgbToHex(Math.floor(b-((b/255)*(fact*1.5))));\n\n var hexa = code+r_hexa+g_hexa+b_hexa;\n var light = code+r_light+g_light+b_light;\n var dark = code+r_dark+g_dark+b_dark;\n\n console.log('HEXs -> '+dark+\" + \"+hexa+\" + \"+light)\n\n var colors = [dark, hexa, light]; \n return colors;\n\n}\n\nIn your ThreeJS code simply write:\nvar material = new THREE.MeshLambertMaterial();\nvar c = convertToHex(255,0,0); // red cube needed\nmaterial.color.set( Number(c[0]), Number(c[1]), Number(c[2]) );\n\nResults:\n// dark normal light\nconvertToHex(255,255,255) HEXs -> 0x696969 + 0xffffff + 0xffffff\nconvertToHex(255,0,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464\nconvertToHex(255,127,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464\nconvertToHex(100,100,100) HEXs -> 0x292929 + 0x646464 + 0xa0a0a0\nconvertToHex(10,10,10) HEXs -> 0x040404 + 0x0a0a0a + 0x6a6a6a\n\n\n",
"Immutable and human understandable version without any bitwise magic:\n\nLoop over array\nNormalize value if value < 0 or value > 255 using Math.min() and Math.max()\nConvert number to hex notation using String.toString()\nAppend leading zero and trim value to two characters\njoin mapped values to string\n\nfunction rgbToHex(r, g, b) {\n return [r, g, b]\n .map(color => {\n const normalizedColor = Math.max(0, Math.min(255, color));\n const hexColor = normalizedColor.toString(16);\n\n return `0${hexColor}`.slice(-2);\n })\n .join(\"\");\n}\n\nYes, it won't be as performant as bitwise operators but way more readable and immutable so it will not modify any input\n",
"HTML converer :)\n<!DOCTYPE html>\n<html>\n<body>\n\n<p id=\"res\"></p>\n\n<script>\nfunction hexToRgb(hex) {\n var res = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return \"(\" + parseInt(res[1], 16) + \",\" + parseInt(res[2], 16) + \",\" + parseInt(res[3], 16) + \")\";\n};\n\ndocument.getElementById(\"res\").innerHTML = hexToRgb('#0080C0');\n</script>\n\n</body>\n</html>\n\n",
"To convert from HEX to RGB where RGB are float values within the range of 0 and 1:\n#FFAA22 → {r: 0.5, g: 0, b:1} \nI adapted @Tim Down’s answer:\n\nfunction convertRange(value,oldMin,oldMax,newMin,newMax) {\n return (Math.round(((((value - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin) * 10000)/10000)\n}\n\nfunction hexToRgbFloat(hex) {\n var result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return result ? {\n r: convertRange(parseInt(result[1],16), 0, 255, 0, 1),\n g: convertRange(parseInt(result[2],16), 0, 255, 0, 1),\n b: convertRange(parseInt(result[3],16), 0, 255, 0, 1)\n } : null;\n}\n\nconsole.log(hexToRgbFloat(\"#FFAA22\")) // {r: 1, g: 0.6667, b: 0.1333}\n\n",
"A readable oneliner for rgb string to hex string:\nrgb = \"rgb(0,128,255)\"\nhex = '#' + rgb.slice(4,-1).split(',').map(x => (+x).toString(16).padStart(2,0)).join('')\n\nwhich returns here \"#0080ff\".\n",
"Surprised this answer hasn't come up.\n\nDoesn't use any library #use-the-platform ✔️\n3 Lines, and handles any color browsers support.\n\n\n\r\n\r\nconst toRGB = (color) => {\n const { style } = new Option();\n style.color = color;\n return style.color;\n}\n// handles any color the browser supports and converts it.\nconsole.log(toRGB(\"#333\")) // rgb(51, 51, 51);\nconsole.log(toRGB(\"hsl(30, 30%, 30%)\")) \r\n\r\n\r\n\n\n\n"
] |
[
1573,
187,
125,
67,
34,
30,
26,
26,
22,
16,
13,
12,
11,
6,
6,
5,
4,
4,
3,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
"A clean coffeescript version of the above (thanks @TimDown):\nrgbToHex = (rgb) ->\n a = rgb.match /\\d+/g\n rgb unless a.length is 3\n \"##{ ((1 << 24) + (parseInt(a[0]) << 16) + (parseInt(a[1]) << 8) + parseInt(a[2])).toString(16).slice(1) }\"\n\n",
"Using combining anonymous functions and Array.map for a cleaner; more streamlined look.\n\n\nvar write=function(str){document.body.innerHTML=JSON.stringify(str,null,' ');};\r\n\r\nfunction hexToRgb(hex, asObj) {\r\n return (function(res) {\r\n return res == null ? null : (function(parts) {\r\n return !asObj ? parts : { r : parts[0], g : parts[1], b : parts[2] }\r\n }(res.slice(1,4).map(function(val) { return parseInt(val, 16); })));\r\n }(/^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex)));\r\n}\r\n\r\nfunction rgbToHex(r, g, b) {\r\n return (function(values) {\r\n return '#' + values.map(function(intVal) {\r\n return (function(hexVal) {\r\n return hexVal.length == 1 ? \"0\" + hexVal : hexVal;\r\n }(intVal.toString(16)));\r\n }).join('');\r\n }(arguments.length === 1 ? Array.isArray(r) ? r : [r.r, r.g, r.b] : [r, g, b]))\r\n}\r\n\r\n// Prints: { r: 255, g: 127, b: 92 }\r\nwrite(hexToRgb(rgbToHex(hexToRgb(rgbToHex(255, 127, 92), true)), true));\nbody{font-family:monospace;white-space:pre}\n\n\n\n",
"I found this...\nhttp://jsfiddle.net/Mottie/xcqpF/1/light/\nfunction rgb2hex(rgb){\n rgb = rgb.match(/^rgba?[\\s+]?\\([\\s+]?(\\d+)[\\s+]?,[\\s+]?(\\d+)[\\s+]?,[\\s+]?(\\d+)[\\s+]?/i);\n return (rgb && rgb.length === 4) ? \"#\" +\n (\"0\" + parseInt(rgb[1],10).toString(16)).slice(-2) +\n (\"0\" + parseInt(rgb[2],10).toString(16)).slice(-2) +\n (\"0\" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';\n}\n\n",
"Here is the Javascript code to change HEX Color value to the Red, Green, Blue individually.\nR = hexToR(\"#FFFFFF\");\nG = hexToG(\"#FFFFFF\");\nB = hexToB(\"#FFFFFF\");\n\nfunction hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}\nfunction hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}\nfunction hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}\nfunction cutHex(h) {return (h.charAt(0)==\"#\") ? h.substring(1,7):h}\n\n",
"CSS Level 4 side note: Generally, the reason you'd want to be able to convert Hex to RGB is for the alpha channel, in which case you can soon do that with CSS4 by adding a trailing hex. Example: #FF8800FF or #f80f for fully transparent orange.\nThat aside, the code below answers both the questions in a single function, going from and to another. This accepts an optional alpha channel, supports both string an array formats, parses 3,4,6,7 character hex's, and rgb/a complete or partial strings (with exception of percent-defined rgb/a values) without a flag.\n(Replace the few ES6 syntaxes if supporting IE)\nIn a line:\nfunction rgbaHex(c,a,i){return(Array.isArray(c)||(typeof c==='string'&&/,/.test(c)))?((c=(Array.isArray(c)?c:c.replace(/[\\sa-z\\(\\);]+/gi,'').split(',')).map(s=>parseInt(s).toString(16).replace(/^([a-z\\d])$/i,'0$1'))),'#'+c[0]+c[1]+c[2]):(c=c.replace(/#/,''),c=c.length%6?c.replace(/(.)(.)(.)/,'$1$1$2$2$3$3'):c,a=parseFloat(a)||null,`rgb${a?'a':''}(${[(i=parseInt(c,16))>>16&255,i>>8&255,i&255,a].join().replace(/,$/,'')})`);}\n\nReadable version:\nfunction rgbaHex(c, a) {\n // RGBA to Hex\n if (Array.isArray(c) || (typeof c === 'string' && /,/.test(c))) {\n c = Array.isArray(c) ? c : c.replace(/[\\sa-z\\(\\);]+/gi, '').split(',');\n c = c.map(s => window.parseInt(s).toString(16).replace(/^([a-z\\d])$/i, '0$1'));\n\n return '#' + c[0] + c[1] + c[2];\n }\n // Hex to RGBA\n else {\n c = c.replace(/#/, '');\n c = c.length % 6 ? c.replace(/(.)(.)(.)/, '$1$1$2$2$3$3') : c;\n c = window.parseInt(c, 16);\n\n a = window.parseFloat(a) || null;\n\n const r = (c >> 16) & 255;\n const g = (c >> 08) & 255;\n const b = (c >> 00) & 255;\n\n return `rgb${a ? 'a' : ''}(${[r, g, b, a].join().replace(/,$/,'')})`;\n }\n}\n\nUsages:\nrgbaHex('#a8f')\nrgbaHex('#aa88ff')\nrgbaHex('#A8F')\nrgbaHex('#AA88FF')\nrgbaHex('#AA88FF', 0.5)\nrgbaHex('#a8f', '0.85')\n// etc.\nrgbaHex('rgba(170,136,255,0.8);')\nrgbaHex('rgba(170,136,255,0.8)')\nrgbaHex('rgb(170,136,255)')\nrgbaHex('rg170,136,255')\nrgbaHex(' 170, 136, 255 ')\nrgbaHex([170,136,255,0.8])\nrgbaHex([170,136,255])\n// etc.\n",
"I made a small Javascript color class for RGB and Hex colors, this class also includes RGB and Hex validation functions. I've added the code as a snippet to this answer.\n\n\nvar colorClass = function() {\r\n this.validateRgb = function(color) {\r\n return typeof color === 'object' &&\r\n color.length === 3 &&\r\n Math.min.apply(null, color) >= 0 &&\r\n Math.max.apply(null, color) <= 255;\r\n };\r\n this.validateHex = function(color) {\r\n return color.match(/^\\#?(([0-9a-f]{3}){1,2})$/i);\r\n };\r\n this.hexToRgb = function(color) {\r\n var hex = color.replace(/^\\#/, '');\r\n var length = hex.length;\r\n return [\r\n parseInt(length === 6 ? hex['0'] + hex['1'] : hex['0'] + hex['0'], 16),\r\n parseInt(length === 6 ? hex['2'] + hex['3'] : hex['1'] + hex['1'], 16),\r\n parseInt(length === 6 ? hex['4'] + hex['5'] : hex['2'] + hex['2'], 16)\r\n ];\r\n };\r\n this.rgbToHex = function(color) {\r\n return '#' +\r\n ('0' + parseInt(color['0'], 10).toString(16)).slice(-2) +\r\n ('0' + parseInt(color['1'], 10).toString(16)).slice(-2) +\r\n ('0' + parseInt(color['2'], 10).toString(16)).slice(-2);\r\n };\r\n};\r\n\r\nvar colors = new colorClass();\r\nconsole.log(colors.hexToRgb('#FFFFFF'));// [255, 255, 255]\r\nconsole.log(colors.rgbToHex([255, 255, 255]));// #FFFFFF\n\n\n\n",
"Fairly straightforward one liner. Splits the rgb by commas, ignores non numerics, converts to hex, pads a 0, and finishes off with a hashbang.\n\n\nvar yellow = 'rgb(255, 255, 0)';\r\nvar rgb2hex = str => \"#\"+str.split(',').map(s => (s.replace(/\\D/g,'')|0).toString(16)).map(s => s.length < 2 ? \"0\"+s : s).join('');\r\n\r\nconsole.log(rgb2hex(yellow));\n\n\n\n",
"Short arrow functions\nFor those who value short arrow function.\nHex2rgb\nA arrow function version of David's Answer\nconst hex2rgb = h => [(x=parseInt(h,16)) >> 16 & 255,x >> 8 & 255, x & 255];\n\nA more flexible solution that supports shortand hex or the hash #\nconst hex2rgb = h => {\n if(h[0] == '#') {h = h.slice(1)};\n if(h.length <= 3) {h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2]};\n h = parseInt(h,16);\n return [h >> 16 & 255,h >> 8 & 255, h & 255];\n};\n\nRgb2hex\nconst rgb2hex = (r,g,b) => ((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);\n\n",
"I whipped up this for use with lodash. It will convert an RGB string such as \"30,209,19\" to its corresponding hex string \"#1ed113\":\nvar rgb = '30,209,19';\n\nvar hex = _.reduce(rgb.split(','), function(hexAccumulator, rgbValue) {\n var intColor = _.parseInt(rgbValue);\n\n if (_.isNaN(intColor)) {\n throw new Error('The value ' + rgbValue + ' was not able to be converted to int');\n }\n\n // Ensure a value such as 2 is converted to \"02\".\n var hexColor = _.padLeft(intColor.toString(16), 2, '0');\n\n return hexAccumulator + hexColor;\n}, '#');\n\n",
"You can try this simple piece of code below. \nFor HEX to RGB\nlist($r, $g, $b) = sscanf(#7bde84, \"#%02x%02x%02x\");\necho $r . \",\" . $g . \",\" . $b;\n\nThis will return 123,222,132\nFor RGB to HEX\n$rgb = (123,222,132),\n$rgbarr = explode(\",\",$rgb,3);\necho sprintf(\"#%02x%02x%02x\", $rgbarr[0], $rgbarr[1], $rgbarr[2]);\n\nThis will return #7bde84\n",
"Built my own hex to RGB converter. I hope this can help someone out.\nIve used react to sandbox it.\nUsage:\nInstall React from the official documentation or alternatively if you have npx installed globally, run npx create-react-app hex-to-rgb\nimport React, { Component, Fragment } from 'react';\nconst styles = {\n display: 'block',\n margin: '20px auto',\n input: {\n width: 170,\n },\n button: {\n margin: '0 auto'\n }\n}\n\n// test case 1\n// #f0f\n// test case 2\n// #ff00ff\n\nclass HexToRGBColorConverter extends Component {\n\n state = {\n result: false,\n color: \"#ff00ff\",\n }\n \n hexToRgb = color => { \n let container = [[], [], []];\n // check for shorthand hax string\n if (color.length >= 3) {\n // remove hash from string\n // convert string to array\n color = color.substring(1).split(\"\");\n for (let key = 0; key < color.length; key++) { \n let value = color[key];\n container[2].push(value);\n // if the length is 3 we \n // we need to add the value \n // to the index we just updated\n if (color.length === 3) container[2][key] += value;\n }\n \n for (let index = 0; index < color.length; index++) {\n let isEven = index % 2 === 0;\n // If index is odd an number \n // push the value into the first\n // index in our container\n if (isEven) container[0].push(color[index]);\n // If index is even an number \n if (!isEven) {\n // again, push the value into the\n // first index in the container\n container[0] += color[index];\n // Push the containers first index\n // into the second index of the container\n container[1].push(container[0]);\n // Flush the first index of\n // of the container \n // before starting a new set\n container[0] = [];\n }\n }\n // Check container length\n if (container.length === 3) {\n // Remove only one element of the array\n // Starting at the array's first index\n container.splice(0, 1);\n let values = container[color.length % 2];\n return {\n r: parseInt(values[0], 16),\n g: parseInt(values[1], 16),\n b: parseInt(values[2], 16)\n }\n }\n }\n return false;\n } \n\n handleOnClick = event => {\n event.preventDefault();\n const { color } = this.state;\n const state = Object.assign({}, this.state);\n state.result = this.hexToRgb(color);\n this.setState(state);\n }\n\n handleOnChange = event => {\n event.preventDefault();\n const { value } = event.currentTarget;\n const pattern = /^([a-zA-Z0-9])/;\n const boundaries = [3, 6];\n if (\n pattern.test(value) &&\n boundaries.includes(value.length)\n ) {\n const state = Object.assign({}, this.state);\n state.color = `#${value}`;\n this.setState(state);\n }\n }\n\n render() {\n const { color, result } = this.state;\n console.log('this.state ', color, result);\n\n return (\n <Fragment>\n <input \n type=\"text\" \n onChange={this.handleOnChange} \n style={{ ...styles, ...styles.input }} />\n <button \n onClick={this.handleOnClick}\n style={{ ...styles, ...styles.button }}>\n Convert hex to rgba\n </button>\n { \n !!result && \n <div style={{ textAlign: 'center' }}>\n Converted { color } to { JSON.stringify(result) }\n </div> \n }\n </Fragment>\n )\n }\n}\nexport default App;\n\nHappy Coding =)\n",
"In case this helps anyone, my API has functions for those conversions.\n<script src=\"http://api.xlww.net/xQuery/xQuery.js\"></script>\n<script>\n x.init();\n var rgb=new x.rgb(37,255,83);\n alert(rgb.hex);\n var hex=new x.hex(\"#ffa500\");\n alert(\"(\"+hex.rgb[0]+\",\"+hex.rgb[1]+\",\"+hex.rgb[2]+\")\");\n</script>\n\n"
] |
[
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-2,
-2,
-2,
-3
] |
[
"colors",
"hex",
"javascript",
"rgb"
] |
stackoverflow_0005623838_colors_hex_javascript_rgb.txt
|
Q:
Place a Window behind desktop icons using PyQt on Ubuntu/GNOME
I'm trying to develop a simple cross-platform Wallpaper manager, but I am not able to find any method to place my PyQt Window between the current wallpaper and the desktop icons using XLib (on windows and macOS it's way easier and works perfectly).
This works right on Cinnamon (with a little workround just simulating a click), but not on GNOME. Can anyone help or give me any clue? (I'm providing all this code just to provide a minimum executable piece, but the key part, I guess, is right after 'if "GNOME"...' sentence)
import os
import time
import Xlib
import ewmh
import pywinctl
from pynput import mouse
DISP = Xlib.display.Display()
SCREEN = DISP.screen()
ROOT = DISP.screen().root
EWMH = ewmh.EWMH(_display=DISP, root=ROOT)
def sendBehind(hWnd):
w = DISP.create_resource_object('window', hWnd)
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_STATE_BELOW', False), ], Xlib.X.PropModeReplace)
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_STATE_SKIP_TASKBAR', False), ], Xlib.X.PropModeAppend)
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_STATE_SKIP_PAGER', False), ], Xlib.X.PropModeAppend)
DISP.flush()
# This sends window below all others, but not behind the desktop icons
w.change_property(DISP.intern_atom('_NET_WM_WINDOW_TYPE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_WINDOW_TYPE_DESKTOP', False), ],Xlib.X.PropModeReplace)
DISP.flush()
if "GNOME" in os.environ.get('XDG_CURRENT_DESKTOP', ""):
# This sends the window "too far behind" (below all others, including Wallpaper, like unmapped)
# Trying to figure out how to raise it on top of wallpaper but behind desktop icons
desktop = _xlibGetAllWindows(title="gnome-shell")
if desktop:
w.reparent(desktop[-1], 0, 0)
DISP.flush()
else:
# Mint/Cinnamon: just clicking on the desktop, it raises, sending the window/wallpaper to the bottom!
m = mouse.Controller()
m.move(SCREEN.width_in_pixels - 1, 100)
m.click(mouse.Button.left, 1)
return '_NET_WM_WINDOW_TYPE_DESKTOP' in EWMH.getWmWindowType(hWnd, str=True)
def bringBack(hWnd, parent):
w = DISP.create_resource_object('window', hWnd)
if parent:
w.reparent(parent, 0, 0)
DISP.flush()
w.unmap()
w.change_property(DISP.intern_atom('_NET_WM_WINDOW_TYPE', False), Xlib.Xatom.ATOM,
32, [DISP.intern_atom('_NET_WM_WINDOW_TYPE_NORMAL', False), ],
Xlib.X.PropModeReplace)
DISP.flush()
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM,
32, [DISP.intern_atom('_NET_WM_STATE_FOCUSED', False), ],
Xlib.X.PropModeReplace)
DISP.flush()
w.map()
EWMH.setActiveWindow(hWnd)
EWMH.display.flush()
return '_NET_WM_WINDOW_TYPE_NORMAL' in EWMH.getWmWindowType(hWnd, str=True)
def _xlibGetAllWindows(parent: int = None, title: str = ""):
if not parent:
parent = ROOT
allWindows = [parent]
def findit(hwnd):
query = hwnd.query_tree()
for child in query.children:
allWindows.append(child)
findit(child)
findit(parent)
if not title:
matches = allWindows
else:
matches = []
for w in allWindows:
if w.get_wm_name() == title:
matches.append(w)
return matches
hWnd = pywinctl.getActiveWindow()
parent = hWnd._hWnd.query_tree().parent
sendBehind(hWnd._hWnd)
time.sleep(3)
bringBack(hWnd._hWnd, parent)
A:
Eureka!!! Last Ubuntu version (22.04) seems to have brought the solution by itself. It now has a "layer" for desktop icons you can interact with. This also gave me the clue to find a smarter solution on Mint/Cinnamon (testing in other OS is still pending). This is the code which seems to work OK, for those with the same issue:
import time
import Xlib.display
import ewmh
import pywinctl
DISP = Xlib.display.Display()
SCREEN = DISP.screen()
ROOT = DISP.screen().root
EWMH = ewmh.EWMH(_display=DISP, root=ROOT)
def sendBehind(hWnd):
w = DISP.create_resource_object('window', hWnd.id)
w.unmap()
w.change_property(DISP.intern_atom('_NET_WM_WINDOW_TYPE', False), Xlib.Xatom.ATOM,
32, [DISP.intern_atom('_NET_WM_WINDOW_TYPE_DESKTOP', False), ],
Xlib.X.PropModeReplace)
DISP.flush()
w.map()
# This will try to raise the desktop icons layer on top of the window
# Ubuntu: "@!0,0;BDHF" is the new desktop icons NG extension
# Mint: "Desktop" name is language-dependent. Using its class (nemo-desktop)
desktop = _xlibGetAllWindows(title="@!0,0;BDHF", klass=('nemo-desktop', 'Nemo-desktop'))
for d in desktop:
w = DISP.create_resource_object('window', d)
w.raise_window()
return '_NET_WM_WINDOW_TYPE_DESKTOP' in EWMH.getWmWindowType(hWnd, str=True)
def bringBack(hWnd):
w = DISP.create_resource_object('window', hWnd.id)
w.unmap()
w.change_property(DISP.intern_atom('_NET_WM_WINDOW_TYPE', False), Xlib.Xatom.ATOM,
32, [DISP.intern_atom('_NET_WM_WINDOW_TYPE_NORMAL', False), ],
Xlib.X.PropModeReplace)
DISP.flush()
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM,
32, [DISP.intern_atom('_NET_WM_STATE_FOCUSED', False), ],
Xlib.X.PropModeReplace)
DISP.flush()
w.map()
EWMH.setActiveWindow(hWnd)
EWMH.display.flush()
return '_NET_WM_WINDOW_TYPE_NORMAL' in EWMH.getWmWindowType(hWnd, str=True)
def _xlibGetAllWindows(parent=None, title: str = "", klass=None):
parent = parent or ROOT
allWindows = [parent]
def findit(hwnd):
query = hwnd.query_tree()
for child in query.children:
allWindows.append(child)
findit(child)
findit(parent)
if not title and not klass:
return allWindows
else:
return [window for window in allWindows if ((title and window.get_wm_name() == title) or
(klass and window.get_wm_class() == klass))]
hWnd = pywinctl.getActiveWindow()
sendBehind(hWnd._hWnd)
time.sleep(3)
bringBack(hWnd._hWnd)
|
Place a Window behind desktop icons using PyQt on Ubuntu/GNOME
|
I'm trying to develop a simple cross-platform Wallpaper manager, but I am not able to find any method to place my PyQt Window between the current wallpaper and the desktop icons using XLib (on windows and macOS it's way easier and works perfectly).
This works right on Cinnamon (with a little workround just simulating a click), but not on GNOME. Can anyone help or give me any clue? (I'm providing all this code just to provide a minimum executable piece, but the key part, I guess, is right after 'if "GNOME"...' sentence)
import os
import time
import Xlib
import ewmh
import pywinctl
from pynput import mouse
DISP = Xlib.display.Display()
SCREEN = DISP.screen()
ROOT = DISP.screen().root
EWMH = ewmh.EWMH(_display=DISP, root=ROOT)
def sendBehind(hWnd):
w = DISP.create_resource_object('window', hWnd)
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_STATE_BELOW', False), ], Xlib.X.PropModeReplace)
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_STATE_SKIP_TASKBAR', False), ], Xlib.X.PropModeAppend)
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_STATE_SKIP_PAGER', False), ], Xlib.X.PropModeAppend)
DISP.flush()
# This sends window below all others, but not behind the desktop icons
w.change_property(DISP.intern_atom('_NET_WM_WINDOW_TYPE', False), Xlib.Xatom.ATOM, 32, [DISP.intern_atom('_NET_WM_WINDOW_TYPE_DESKTOP', False), ],Xlib.X.PropModeReplace)
DISP.flush()
if "GNOME" in os.environ.get('XDG_CURRENT_DESKTOP', ""):
# This sends the window "too far behind" (below all others, including Wallpaper, like unmapped)
# Trying to figure out how to raise it on top of wallpaper but behind desktop icons
desktop = _xlibGetAllWindows(title="gnome-shell")
if desktop:
w.reparent(desktop[-1], 0, 0)
DISP.flush()
else:
# Mint/Cinnamon: just clicking on the desktop, it raises, sending the window/wallpaper to the bottom!
m = mouse.Controller()
m.move(SCREEN.width_in_pixels - 1, 100)
m.click(mouse.Button.left, 1)
return '_NET_WM_WINDOW_TYPE_DESKTOP' in EWMH.getWmWindowType(hWnd, str=True)
def bringBack(hWnd, parent):
w = DISP.create_resource_object('window', hWnd)
if parent:
w.reparent(parent, 0, 0)
DISP.flush()
w.unmap()
w.change_property(DISP.intern_atom('_NET_WM_WINDOW_TYPE', False), Xlib.Xatom.ATOM,
32, [DISP.intern_atom('_NET_WM_WINDOW_TYPE_NORMAL', False), ],
Xlib.X.PropModeReplace)
DISP.flush()
w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM,
32, [DISP.intern_atom('_NET_WM_STATE_FOCUSED', False), ],
Xlib.X.PropModeReplace)
DISP.flush()
w.map()
EWMH.setActiveWindow(hWnd)
EWMH.display.flush()
return '_NET_WM_WINDOW_TYPE_NORMAL' in EWMH.getWmWindowType(hWnd, str=True)
def _xlibGetAllWindows(parent: int = None, title: str = ""):
if not parent:
parent = ROOT
allWindows = [parent]
def findit(hwnd):
query = hwnd.query_tree()
for child in query.children:
allWindows.append(child)
findit(child)
findit(parent)
if not title:
matches = allWindows
else:
matches = []
for w in allWindows:
if w.get_wm_name() == title:
matches.append(w)
return matches
hWnd = pywinctl.getActiveWindow()
parent = hWnd._hWnd.query_tree().parent
sendBehind(hWnd._hWnd)
time.sleep(3)
bringBack(hWnd._hWnd, parent)
|
[
"Eureka!!! Last Ubuntu version (22.04) seems to have brought the solution by itself. It now has a \"layer\" for desktop icons you can interact with. This also gave me the clue to find a smarter solution on Mint/Cinnamon (testing in other OS is still pending). This is the code which seems to work OK, for those with the same issue:\nimport time\n\nimport Xlib.display\nimport ewmh\nimport pywinctl\n\nDISP = Xlib.display.Display()\nSCREEN = DISP.screen()\nROOT = DISP.screen().root\nEWMH = ewmh.EWMH(_display=DISP, root=ROOT)\n\n\ndef sendBehind(hWnd):\n w = DISP.create_resource_object('window', hWnd.id)\n w.unmap()\n w.change_property(DISP.intern_atom('_NET_WM_WINDOW_TYPE', False), Xlib.Xatom.ATOM,\n 32, [DISP.intern_atom('_NET_WM_WINDOW_TYPE_DESKTOP', False), ],\n Xlib.X.PropModeReplace)\n DISP.flush()\n w.map()\n\n # This will try to raise the desktop icons layer on top of the window\n # Ubuntu: \"@!0,0;BDHF\" is the new desktop icons NG extension\n # Mint: \"Desktop\" name is language-dependent. Using its class (nemo-desktop)\n desktop = _xlibGetAllWindows(title=\"@!0,0;BDHF\", klass=('nemo-desktop', 'Nemo-desktop'))\n for d in desktop:\n w = DISP.create_resource_object('window', d)\n w.raise_window()\n\n return '_NET_WM_WINDOW_TYPE_DESKTOP' in EWMH.getWmWindowType(hWnd, str=True)\n\n\ndef bringBack(hWnd):\n\n w = DISP.create_resource_object('window', hWnd.id)\n\n w.unmap()\n w.change_property(DISP.intern_atom('_NET_WM_WINDOW_TYPE', False), Xlib.Xatom.ATOM,\n 32, [DISP.intern_atom('_NET_WM_WINDOW_TYPE_NORMAL', False), ],\n Xlib.X.PropModeReplace)\n DISP.flush()\n w.change_property(DISP.intern_atom('_NET_WM_STATE', False), Xlib.Xatom.ATOM,\n 32, [DISP.intern_atom('_NET_WM_STATE_FOCUSED', False), ],\n Xlib.X.PropModeReplace)\n DISP.flush()\n w.map()\n EWMH.setActiveWindow(hWnd)\n EWMH.display.flush()\n return '_NET_WM_WINDOW_TYPE_NORMAL' in EWMH.getWmWindowType(hWnd, str=True)\n\n\ndef _xlibGetAllWindows(parent=None, title: str = \"\", klass=None):\n\n parent = parent or ROOT\n allWindows = [parent]\n\n def findit(hwnd):\n query = hwnd.query_tree()\n for child in query.children:\n allWindows.append(child)\n findit(child)\n\n findit(parent)\n if not title and not klass:\n return allWindows\n else:\n return [window for window in allWindows if ((title and window.get_wm_name() == title) or\n (klass and window.get_wm_class() == klass))]\n\n\nhWnd = pywinctl.getActiveWindow()\nsendBehind(hWnd._hWnd)\ntime.sleep(3)\nbringBack(hWnd._hWnd)\n\n"
] |
[
1
] |
[] |
[] |
[
"gnome",
"pyqt5",
"python",
"ubuntu",
"xlib"
] |
stackoverflow_0071241339_gnome_pyqt5_python_ubuntu_xlib.txt
|
Q:
Automatic token refresh after 1 hour . React-adal
import { AuthenticationContext } from "react-adal";
import config from "./config.json"
const { clientId, tenantID, redirectUrl, logoutUrl } = config;
const adalConfig = {
tenant: "abc.xyz.com",
clientId: clientId,
redirectUri: redirectUrl,
endpoints: {
api: tenantID,
},
postLogoutRedirectUri: logoutUrl,
cacheLocation: "sessionStorage",
};
export const authContext = new AuthenticationContext(adalConfig);
This is my adalConfig.js file. As of now the token gets expired after an hour which is the default property and i do not want that to happen in my use case. I want the token to be valid atleast for a day or it should get refreshed automatically when it expires. I have not used react-adal ever before. Do not we have any property like cacheLocation, postLogOutRedirectUri, CliendId etc like mentioned in the above code for the token expiry time ?? named Please help me with this. Thanks in advance. Any sort of lead is appreciated.
A:
When expired a new ID token should be acquired silently if the session or KMSI cookie is present. You can control the former using Conditional Access User sign-in frequency. Since this is a paid feature, please take a look to the License requirements.
|
Automatic token refresh after 1 hour . React-adal
|
import { AuthenticationContext } from "react-adal";
import config from "./config.json"
const { clientId, tenantID, redirectUrl, logoutUrl } = config;
const adalConfig = {
tenant: "abc.xyz.com",
clientId: clientId,
redirectUri: redirectUrl,
endpoints: {
api: tenantID,
},
postLogoutRedirectUri: logoutUrl,
cacheLocation: "sessionStorage",
};
export const authContext = new AuthenticationContext(adalConfig);
This is my adalConfig.js file. As of now the token gets expired after an hour which is the default property and i do not want that to happen in my use case. I want the token to be valid atleast for a day or it should get refreshed automatically when it expires. I have not used react-adal ever before. Do not we have any property like cacheLocation, postLogOutRedirectUri, CliendId etc like mentioned in the above code for the token expiry time ?? named Please help me with this. Thanks in advance. Any sort of lead is appreciated.
|
[
"When expired a new ID token should be acquired silently if the session or KMSI cookie is present. You can control the former using Conditional Access User sign-in frequency. Since this is a paid feature, please take a look to the License requirements.\n"
] |
[
0
] |
[] |
[] |
[
"adal",
"authentication",
"reactjs"
] |
stackoverflow_0074442093_adal_authentication_reactjs.txt
|
Q:
How to save .xlsx data to file as a blob
I have a similar question to this question(Javascript: Exporting large text/csv file crashes Google Chrome):
I am trying to save the data created by excelbuilder.js's EB.createFile() function. If I put the file data as the href attribute value of a link, it works. However, when data is big, it crashes Chrome browser. Codes are like this:
//generate a temp <a /> tag
var link = document.createElement("a");
link.href = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + encodeURIComponent(data);
link.style = "visibility:hidden";
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
My codes to create the data using excelbuilder.js is like follows:
var artistWorkbook = EB.createWorkbook();
var albumList = artistWorkbook.createWorksheet({name: 'Album List'});
albumList.setData(originalData);
artistWorkbook.addWorksheet(albumList);
var data = EB.createFile(artistWorkbook);
As suggested by the answer of the similar question (Javascript: Exporting large text/csv file crashes Google Chrome), a blob needs to be created.
My problem is, what is saved in the file isn't a valid Excel file that can be opened by Excel. The codes that I use to save the blob is like this:
var blob = new Blob(
[data],
{type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,"}
);
// Programatically create a link and click it:
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = fileName;
a.click();
If I replace the [data] in the above codes with [Base64.decode(data)], the contents in the file saved looks more like the expected excel data, but still cannot be opened by Excel.
Thanks!
A:
I had the same problem as you. It turns out you need to convert the Excel data file to an ArrayBuffer.
var blob = new Blob([s2ab(atob(data))], {
type: ''
});
href = URL.createObjectURL(blob);
The s2ab (string to array buffer) method (which I got from https://github.com/SheetJS/js-xlsx/blob/master/README.md) is:
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
A:
The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data.
Here's what I did on the server side (asp.net mvc core):
string path = Path.Combine(folder, fileName);
Byte[] bytes = System.IO.File.ReadAllBytes(path);
string base64 = Convert.ToBase64String(bytes);
On the client side, I did the following code:
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onload = () => {
var bin = atob(xhr.response);
var ab = s2ab(bin); // from example above
var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'demo.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
xhr.send();
And it works perfectly for me.
A:
I've found a solution worked for me:
const handleDownload = async () => {
const req = await axios({
method: "get",
url: `/companies/${company.id}/data`,
responseType: "blob",
});
var blob = new Blob([req.data], {
type: req.headers["content-type"],
});
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = `report_${new Date().getTime()}.xlsx`;
link.click();
};
I just point a responseType: "blob"
A:
This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx
/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });
A:
Here's my implementation using the fetch api. The server endpoint sends a stream of bytes and the client receives a byte array and creates a blob out of it. A .xlsx file will then be generated.
return fetch(fullUrlEndpoint, options)
.then((res) => {
if (!res.ok) {
const responseStatusText = res.statusText
const errorMessage = `${responseStatusText}`
throw new Error(errorMessage);
}
return res.arrayBuffer();
})
.then((ab) => {
// BE endpoint sends a readable stream of bytes
const byteArray = new Uint8Array(ab);
const a = window.document.createElement('a');
a.href = window.URL.createObjectURL(
new Blob([byteArray], {
type:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
}),
);
a.download = `${fileName}.XLSX`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
})
.catch(error => {
throw new Error('Error occurred:' + error);
});
A:
Solution for me.
Step: 1
<a onclick="exportAsExcel()">Export to excel</a>
Step: 2
I'm using file-saver lib.
Read more: https://www.npmjs.com/package/file-saver
npm i file-saver
Step: 3
let FileSaver = require('file-saver'); // path to file-saver
function exportAsExcel() {
let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
this.downloadFile(dataBlob);
}
function downloadFile(blobContent){
let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
FileSaver.saveAs(blob, 'report.xlsx');
}
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
let sliceSize = 1024;
let byteCharacters = atob(base64Data);
let bytesLength = byteCharacters.length;
let slicesCount = Math.ceil(bytesLength / sliceSize);
let byteArrays = new Array(slicesCount);
for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
let begin = sliceIndex * sliceSize;
let end = Math.min(begin + sliceSize, bytesLength);
let bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Work for me. ^^
A:
try FileSaver.js library. it might help.
https://github.com/eligrey/FileSaver.js/
A:
This answer depends on both the frontend and backend having a compatible return object, so giving both frontend & backend logic. Make sure backend return data is base64 encoded for the following logic to work.
// Backend code written in nodejs to generate XLS from CSV
import * as XLSX from 'xlsx';
export const convertCsvToExcelBuffer = (csvString: string) => {
const arrayOfArrayCsv = csvString.split("\n").map((row: string) => {
return row.split(",")
});
const wb = XLSX.utils.book_new();
const newWs = XLSX.utils.aoa_to_sheet(arrayOfArrayCsv);
XLSX.utils.book_append_sheet(wb, newWs);
const rawExcel = XLSX.write(wb, { type: 'base64' })
// set res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
// to include content type information to frontend.
return rawExcel
}
//frontend logic to get the backend response and download file.
// function from Ron T's answer which gets a string from ArrayBuffer.
const s2ab = (s) => {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
};
const downloadExcelInBrowser = ()=>{
const excelFileData = await backendCall();
const decodedFileData = atob(excelFileData.data);
const arrayBufferContent = s2ab(decodedFileData); // from example above
const blob = new Blob([arrayBufferContent], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(fileBlob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement('a');
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = 'test.xlsx';
document.body.appendChild(a);
a.click();
}
} else {
window.location.href = downloadUrl;
}
}
A:
if you are using typescript then here is a working example of how to convert array to xlsx and download it.
const fileName = "CustomersTemplate";
const fileExtension = ".xlsx";
const fullFileName = fileName.concat(fileExtension);
const workBook : WorkBook = utils.book_new();
const content : WorkSheet = utils.json_to_sheet([{"column 1": "data", "column 2": "data"}]);
utils.book_append_sheet(workBook, content, fileName);
const buffer : any = writeFile(workBook, fullFileName);
const data : Blob = new Blob(buffer, { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;" });
const url = URL.createObjectURL(data); //some browser may use window.URL
const a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = fullFileName;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0);
|
How to save .xlsx data to file as a blob
|
I have a similar question to this question(Javascript: Exporting large text/csv file crashes Google Chrome):
I am trying to save the data created by excelbuilder.js's EB.createFile() function. If I put the file data as the href attribute value of a link, it works. However, when data is big, it crashes Chrome browser. Codes are like this:
//generate a temp <a /> tag
var link = document.createElement("a");
link.href = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + encodeURIComponent(data);
link.style = "visibility:hidden";
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
My codes to create the data using excelbuilder.js is like follows:
var artistWorkbook = EB.createWorkbook();
var albumList = artistWorkbook.createWorksheet({name: 'Album List'});
albumList.setData(originalData);
artistWorkbook.addWorksheet(albumList);
var data = EB.createFile(artistWorkbook);
As suggested by the answer of the similar question (Javascript: Exporting large text/csv file crashes Google Chrome), a blob needs to be created.
My problem is, what is saved in the file isn't a valid Excel file that can be opened by Excel. The codes that I use to save the blob is like this:
var blob = new Blob(
[data],
{type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,"}
);
// Programatically create a link and click it:
var a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = fileName;
a.click();
If I replace the [data] in the above codes with [Base64.decode(data)], the contents in the file saved looks more like the expected excel data, but still cannot be opened by Excel.
Thanks!
|
[
"I had the same problem as you. It turns out you need to convert the Excel data file to an ArrayBuffer.\nvar blob = new Blob([s2ab(atob(data))], {\n type: ''\n});\n\nhref = URL.createObjectURL(blob);\n\nThe s2ab (string to array buffer) method (which I got from https://github.com/SheetJS/js-xlsx/blob/master/README.md) is:\nfunction s2ab(s) {\n var buf = new ArrayBuffer(s.length);\n var view = new Uint8Array(buf);\n for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;\n return buf;\n}\n\n",
"The answer above is correct. Please be sure that you have a string data in base64 in the data variable without any prefix or stuff like that just raw data. \nHere's what I did on the server side (asp.net mvc core):\nstring path = Path.Combine(folder, fileName);\nByte[] bytes = System.IO.File.ReadAllBytes(path);\nstring base64 = Convert.ToBase64String(bytes);\n\nOn the client side, I did the following code:\nconst xhr = new XMLHttpRequest();\n\nxhr.open(\"GET\", url);\nxhr.setRequestHeader(\"Content-Type\", \"text/plain\");\n\nxhr.onload = () => {\n var bin = atob(xhr.response);\n var ab = s2ab(bin); // from example above\n var blob = new Blob([ab], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });\n\n var link = document.createElement('a');\n link.href = window.URL.createObjectURL(blob);\n link.download = 'demo.xlsx';\n\n document.body.appendChild(link);\n\n link.click();\n\n document.body.removeChild(link);\n};\n\nxhr.send();\n\nAnd it works perfectly for me.\n",
"I've found a solution worked for me:\nconst handleDownload = async () => {\n const req = await axios({\n method: \"get\",\n url: `/companies/${company.id}/data`,\n responseType: \"blob\",\n });\n var blob = new Blob([req.data], {\n type: req.headers[\"content-type\"],\n });\n const link = document.createElement(\"a\");\n link.href = window.URL.createObjectURL(blob);\n link.download = `report_${new Date().getTime()}.xlsx`;\n link.click();\n };\n\nI just point a responseType: \"blob\"\n",
"This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx\n/* generate array buffer */\nvar wbout = XLSX.write(wb, {type:\"array\", bookType:'xlsx'});\n/* create data URL */\nvar url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));\n/* trigger download with chrome API */\nchrome.downloads.download({ url: url, filename: \"testsheet.xlsx\", saveAs: true });\n\n",
"Here's my implementation using the fetch api. The server endpoint sends a stream of bytes and the client receives a byte array and creates a blob out of it. A .xlsx file will then be generated.\nreturn fetch(fullUrlEndpoint, options)\n .then((res) => {\n if (!res.ok) {\n const responseStatusText = res.statusText\n const errorMessage = `${responseStatusText}`\n throw new Error(errorMessage);\n }\n return res.arrayBuffer();\n })\n .then((ab) => {\n // BE endpoint sends a readable stream of bytes\n const byteArray = new Uint8Array(ab);\n const a = window.document.createElement('a');\n a.href = window.URL.createObjectURL(\n new Blob([byteArray], {\n type:\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n }),\n );\n a.download = `${fileName}.XLSX`;\n document.body.appendChild(a);\n a.click();\n document.body.removeChild(a);\n })\n .catch(error => {\n throw new Error('Error occurred:' + error);\n });\n\n",
"Solution for me.\nStep: 1\n<a onclick=\"exportAsExcel()\">Export to excel</a>\n\nStep: 2\nI'm using file-saver lib.\nRead more: https://www.npmjs.com/package/file-saver\nnpm i file-saver\n\nStep: 3 \nlet FileSaver = require('file-saver'); // path to file-saver\n\nfunction exportAsExcel() {\n let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only\n this.downloadFile(dataBlob);\n}\n\nfunction downloadFile(blobContent){\n let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});\n FileSaver.saveAs(blob, 'report.xlsx');\n}\n\nfunction base64toBlob(base64Data, contentType) {\n contentType = contentType || '';\n let sliceSize = 1024;\n let byteCharacters = atob(base64Data);\n let bytesLength = byteCharacters.length;\n let slicesCount = Math.ceil(bytesLength / sliceSize);\n let byteArrays = new Array(slicesCount);\n for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {\n let begin = sliceIndex * sliceSize;\n let end = Math.min(begin + sliceSize, bytesLength);\n\n let bytes = new Array(end - begin);\n for (var offset = begin, i = 0; offset < end; ++i, ++offset) {\n bytes[i] = byteCharacters[offset].charCodeAt(0);\n }\n byteArrays[sliceIndex] = new Uint8Array(bytes);\n }\n return new Blob(byteArrays, { type: contentType });\n}\n\nWork for me. ^^\n",
"try FileSaver.js library. it might help.\nhttps://github.com/eligrey/FileSaver.js/\n",
"This answer depends on both the frontend and backend having a compatible return object, so giving both frontend & backend logic. Make sure backend return data is base64 encoded for the following logic to work.\n// Backend code written in nodejs to generate XLS from CSV\nimport * as XLSX from 'xlsx';\n\nexport const convertCsvToExcelBuffer = (csvString: string) => {\n const arrayOfArrayCsv = csvString.split(\"\\n\").map((row: string) => {\n return row.split(\",\")\n });\n const wb = XLSX.utils.book_new();\n const newWs = XLSX.utils.aoa_to_sheet(arrayOfArrayCsv);\n XLSX.utils.book_append_sheet(wb, newWs);\n const rawExcel = XLSX.write(wb, { type: 'base64' })\n // set res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') \n // to include content type information to frontend. \n return rawExcel\n}\n\n//frontend logic to get the backend response and download file. \n\n// function from Ron T's answer which gets a string from ArrayBuffer. \nconst s2ab = (s) => {\n var buf = new ArrayBuffer(s.length);\n var view = new Uint8Array(buf);\n for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;\n return buf;\n};\n\nconst downloadExcelInBrowser = ()=>{\n const excelFileData = await backendCall();\n const decodedFileData = atob(excelFileData.data);\n const arrayBufferContent = s2ab(decodedFileData); // from example above\n const blob = new Blob([arrayBufferContent], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;' });\n var URL = window.URL || window.webkitURL;\n var downloadUrl = URL.createObjectURL(fileBlob);\n if (filename) {\n // use HTML5 a[download] attribute to specify filename\n var a = document.createElement('a');\n // safari doesn't support this yet\n if (typeof a.download === 'undefined') {\n window.location.href = downloadUrl;\n } else {\n a.href = downloadUrl;\n a.download = 'test.xlsx';\n document.body.appendChild(a);\n a.click();\n }\n } else {\n window.location.href = downloadUrl;\n }\n}\n\n",
"if you are using typescript then here is a working example of how to convert array to xlsx and download it.\nconst fileName = \"CustomersTemplate\";\n const fileExtension = \".xlsx\";\n const fullFileName = fileName.concat(fileExtension);\n\n const workBook : WorkBook = utils.book_new();\n\n const content : WorkSheet = utils.json_to_sheet([{\"column 1\": \"data\", \"column 2\": \"data\"}]);\n\n utils.book_append_sheet(workBook, content, fileName);\n\n const buffer : any = writeFile(workBook, fullFileName);\n\n const data : Blob = new Blob(buffer, { type: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;\" });\n\n const url = URL.createObjectURL(data); //some browser may use window.URL\n \n const a = document.createElement(\"a\");\n document.body.appendChild(a);\n a.href = url;\n a.download = fullFileName;\n a.click();\n \n setTimeout(() => {\n window.URL.revokeObjectURL(url);\n document.body.removeChild(a);\n }, 0);\n\n"
] |
[
59,
19,
11,
9,
6,
4,
2,
0,
0
] |
[] |
[] |
[
"bloburls",
"javascript",
"xlsx"
] |
stackoverflow_0034993292_bloburls_javascript_xlsx.txt
|
Q:
Running a loop 10,000 times in order to test expected value
Playing a 2 person game where player A and B take turns drawing stones out of a bag.
10 stones, 9 white, 1 black
You lose if you draw the black stone.
Assuming you alternate drawing stones, is going first an advantage, disadvantage, or neutral?
I'm aware that this can be solved using conditional probability, but I'd like to also prove it by using significant sample size data
import random
import os
import sys
stones = 4
player1Wins = 0
player2Wins = 0
no_games = 100000
gameCount = 0
fatal_stone = random.randint(1, int(stones))
picked_stone = random.randint(1, int(stones))
def pick_stone(self, stones):
for x in range(1, int(stones) + 1):
if picked_stone == fatal_stone:
if (picked_stone % 2) == 0:
player2Wins += 1 print("Player 2 won")
break
if (picked_stone % 2) == 1:
player1Wins += 1
print("Player 1 won")
break
else:
stones -= 1 picked_stone = random.randint(1, int(stones))
self.pick_stone()
pick_stone()
# def run_games(self, no_games): #for i in range(1, int(no_games) + 1): #gameCount = i #self.pick_stone()
print(fatal_stone)
print(picked_stone)
print(int(fatal_stone % 2))
print(int(picked_stone % 2))
print(gameCount)
print("Player 1 won this many times: " + str(player1Wins))
print("Player 2 won this many times: " + str(player2Wins))
A:
The following code works. And it suggests that both players' chances of winning are equal, regardless of who plays first.
import random
import os
import sys
num_stones = 4
no_games = 100000
player1Wins = 0
player2Wins = 0
def pick_stone(player: int, stones: list, fatal_stone: int):
global player1Wins, player2Wins
picked_stone = random.choice(stones)
stones.remove(picked_stone)
if (picked_stone == fatal_stone):
if player == 1:
player2Wins += 1
else:
player1Wins += 1
return False
return True
def run_games(no_games: int):
for _ in range(no_games):
stones = [i for i in range(num_stones)]
fatal_stone = random.choice(stones)
# player 1 and 2 pick stones in turn
player = 1
playing = True
while playing:
playing = pick_stone(player, stones, fatal_stone)
player = player % 2 + 1
print(f"Total rounds: {no_games}")
print("Player 1 won this many times: " + str(player1Wins))
print("Player 2 won this many times: " + str(player2Wins))
run_games(no_games)
|
Running a loop 10,000 times in order to test expected value
|
Playing a 2 person game where player A and B take turns drawing stones out of a bag.
10 stones, 9 white, 1 black
You lose if you draw the black stone.
Assuming you alternate drawing stones, is going first an advantage, disadvantage, or neutral?
I'm aware that this can be solved using conditional probability, but I'd like to also prove it by using significant sample size data
import random
import os
import sys
stones = 4
player1Wins = 0
player2Wins = 0
no_games = 100000
gameCount = 0
fatal_stone = random.randint(1, int(stones))
picked_stone = random.randint(1, int(stones))
def pick_stone(self, stones):
for x in range(1, int(stones) + 1):
if picked_stone == fatal_stone:
if (picked_stone % 2) == 0:
player2Wins += 1 print("Player 2 won")
break
if (picked_stone % 2) == 1:
player1Wins += 1
print("Player 1 won")
break
else:
stones -= 1 picked_stone = random.randint(1, int(stones))
self.pick_stone()
pick_stone()
# def run_games(self, no_games): #for i in range(1, int(no_games) + 1): #gameCount = i #self.pick_stone()
print(fatal_stone)
print(picked_stone)
print(int(fatal_stone % 2))
print(int(picked_stone % 2))
print(gameCount)
print("Player 1 won this many times: " + str(player1Wins))
print("Player 2 won this many times: " + str(player2Wins))
|
[
"The following code works. And it suggests that both players' chances of winning are equal, regardless of who plays first.\nimport random\nimport os\nimport sys\n\n\nnum_stones = 4\n\nno_games = 100000\n\nplayer1Wins = 0\nplayer2Wins = 0\n\n\ndef pick_stone(player: int, stones: list, fatal_stone: int):\n global player1Wins, player2Wins\n \n picked_stone = random.choice(stones)\n stones.remove(picked_stone)\n if (picked_stone == fatal_stone):\n if player == 1:\n player2Wins += 1\n else:\n player1Wins += 1\n return False\n return True\n\n\n\ndef run_games(no_games: int): \n for _ in range(no_games): \n stones = [i for i in range(num_stones)]\n fatal_stone = random.choice(stones)\n \n # player 1 and 2 pick stones in turn\n player = 1\n playing = True\n while playing:\n playing = pick_stone(player, stones, fatal_stone)\n player = player % 2 + 1\n\n print(f\"Total rounds: {no_games}\")\n print(\"Player 1 won this many times: \" + str(player1Wins))\n print(\"Player 2 won this many times: \" + str(player2Wins))\n\n\nrun_games(no_games)\n\n"
] |
[
0
] |
[] |
[] |
[
"loops",
"nested_loops",
"probability_theory",
"python_3.x"
] |
stackoverflow_0074651942_loops_nested_loops_probability_theory_python_3.x.txt
|
Q:
Proximity prompt cooldown - Roblox studio
How could I add a cooldown to my Proximity Prompt to press it again??
press key,after wait any seconds for press it again
Roblox studio
i don't know how to make this script,i need help
A:
This is just a matter of using the function ProximityPrompt.Triggered and then disabling the prompt for a certain period of time before reenabling it again.
local prompt = script.Parent
prompt.Triggered:Connect(function()
print("triggered") --Action
prompt.Enabled = false
wait(5) --However long you want
prompt.Enabled = true
end)
|
Proximity prompt cooldown - Roblox studio
|
How could I add a cooldown to my Proximity Prompt to press it again??
press key,after wait any seconds for press it again
Roblox studio
i don't know how to make this script,i need help
|
[
"This is just a matter of using the function ProximityPrompt.Triggered and then disabling the prompt for a certain period of time before reenabling it again.\nlocal prompt = script.Parent\n\nprompt.Triggered:Connect(function()\n print(\"triggered\") --Action\n \n prompt.Enabled = false\n wait(5) --However long you want\n prompt.Enabled = true\nend)\n\n"
] |
[
0
] |
[] |
[] |
[
"roblox"
] |
stackoverflow_0074648184_roblox.txt
|
Q:
Plotting two variable in the same bar plot
I have a dataset having gdp of countries and their biofuel production named "Merging2". I am trying to plot a bar chart of top 5 countries in gdp and in the same plot have the bar chart of their biofuel_production.
I plotted the top gdp's using :
yr=Merging2.groupby(by='Years')
access1=yr.get_group(2019)
sorted=access1.sort_values(["rgdpe"], ascending=[False]) #sorting it
highest_gdp_2019=sorted.head(10) # taking the top 5 rgdpe
fig, ax=plt.subplots()
plt.bar(highest_gdp_2019.Countries,highest_gdp_2019.rgdpe, color ='black',width = 0.8,alpha=0.8)
ax.set_xlabel("Countries")
ax.set_ylabel("Real GDP")
plt.xticks(rotation = 90)
Is there a way to do that in Python ?
A:
Do you want two subplots, or do you want both bars next to each other? Either way, check out this other thread which should give you the answer to both. In the second case, you would want a secondary Y-axis (as illustrated in the post)
|
Plotting two variable in the same bar plot
|
I have a dataset having gdp of countries and their biofuel production named "Merging2". I am trying to plot a bar chart of top 5 countries in gdp and in the same plot have the bar chart of their biofuel_production.
I plotted the top gdp's using :
yr=Merging2.groupby(by='Years')
access1=yr.get_group(2019)
sorted=access1.sort_values(["rgdpe"], ascending=[False]) #sorting it
highest_gdp_2019=sorted.head(10) # taking the top 5 rgdpe
fig, ax=plt.subplots()
plt.bar(highest_gdp_2019.Countries,highest_gdp_2019.rgdpe, color ='black',width = 0.8,alpha=0.8)
ax.set_xlabel("Countries")
ax.set_ylabel("Real GDP")
plt.xticks(rotation = 90)
Is there a way to do that in Python ?
|
[
"Do you want two subplots, or do you want both bars next to each other? Either way, check out this other thread which should give you the answer to both. In the second case, you would want a secondary Y-axis (as illustrated in the post)\n"
] |
[
0
] |
[] |
[] |
[
"data_cleaning",
"data_science",
"pandas",
"python"
] |
stackoverflow_0074662109_data_cleaning_data_science_pandas_python.txt
|
Q:
How do I clone Git repos within a local network?
I have given a computer within my local network, which for all practical purposes can only be controlled via BASH (Ubuntu Server 22.0.4), a static IP address, and created a Git repository on it. Should I expect to be able to clone that repo right away, or are there some tools I need before I can actually have a URL?
I have read How to find a url for a local GIT repo, and $git config --get remote.origin.url, less .shh/config, git remote show do not show me anything.
I am currently only able to access this computer within my local network, it has not been registered on any DNS. I want to establish that I can use it as a local Git server before I take the following steps and get DNS registration.
I would expect that I should be able to open GitHub on another computer in the network and tell it to clone https://192.168.0.225/[something]. I saw a mention of Gitosis. Is that sufficient to make a locally created repo accessible to other computers?
A:
You'll be connecting via ssh, so all you need is the IP address and the path to the repository.
git clone 192.168.0.225:/path/to/repository
should work fine. The above is shorthand for a more formal URL like
git clone ssh://192.168.0.225/path/to/repository
|
How do I clone Git repos within a local network?
|
I have given a computer within my local network, which for all practical purposes can only be controlled via BASH (Ubuntu Server 22.0.4), a static IP address, and created a Git repository on it. Should I expect to be able to clone that repo right away, or are there some tools I need before I can actually have a URL?
I have read How to find a url for a local GIT repo, and $git config --get remote.origin.url, less .shh/config, git remote show do not show me anything.
I am currently only able to access this computer within my local network, it has not been registered on any DNS. I want to establish that I can use it as a local Git server before I take the following steps and get DNS registration.
I would expect that I should be able to open GitHub on another computer in the network and tell it to clone https://192.168.0.225/[something]. I saw a mention of Gitosis. Is that sufficient to make a locally created repo accessible to other computers?
|
[
"You'll be connecting via ssh, so all you need is the IP address and the path to the repository.\ngit clone 192.168.0.225:/path/to/repository\n\nshould work fine. The above is shorthand for a more formal URL like\ngit clone ssh://192.168.0.225/path/to/repository\n\n"
] |
[
1
] |
[] |
[] |
[
"git",
"lan"
] |
stackoverflow_0074662155_git_lan.txt
|
Q:
Jetpack compose single number text field
I am trying to create a phone verification screen where the user must enter 5 numbers each in their own text field like below.
I have two questions:
Is there a way to limit a TextField to 1 character. I can set single line and max lines, but don't see a way to limit to character length like 'Ms' from the view system. I can easily limit the character length in code by ignoring characters after the first one, but this still lets the user 'scroll' to the left and right even though there is only 1 character.
Is there a way to wrap the width to the 1 character? Currently the only way I have found to limit the width is to set it specifically, but then if the system text size is changed it could break.
Here is some code incase it helps, this is some very jumbled together solution so apologies if something is incorrect:
@Composable
fun CodeTextFields(
modifier: Modifier = Modifier,
length: Int = 5,
onFilled: (code: String) -> Unit
) {
var code: List<Char> by remember {
mutableStateOf(listOf())
}
val focusRequesters: List<FocusRequester> = remember {
val temp = mutableListOf<FocusRequester>()
repeat(length) {
temp.add(FocusRequester())
}
temp
}
Row(modifier = modifier) {
(0 until length).forEach { index ->
OutlinedTextField(
modifier = Modifier
.weight(1f)
.padding(vertical = 2.dp)
.focusRequester(focusRequesters[index]),
textStyle = MaterialTheme.typography.h4.copy(textAlign = TextAlign.Center),
singleLine = true,
value = code.getOrNull(index)?.takeIf { it.isDigit() }?.toString() ?: "",
onValueChange = { value: String ->
if (focusRequesters[index].freeFocus()) { //For some reason this fixes the issue of focusrequestor causing on value changed to call twice
val temp = code.toMutableList()
if (value == "") {
if (temp.size > index) {
temp.removeAt(index)
code = temp
focusRequesters.getOrNull(index - 1)?.requestFocus()
}
} else {
if (code.size > index) {
temp[index] = value.getOrNull(0) ?: ' '
} else if (value.getOrNull(0)?.isDigit() == true) {
temp.add(value.getOrNull(0) ?: ' ')
code = temp
focusRequesters.getOrNull(index + 1)?.requestFocus() ?: onFilled(
code.joinToString(separator = "")
)
}
}
}
},
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next
),
)
Spacer(modifier = Modifier.width(16.dp))
}
}
}
A:
To limit to 1 number you can use something like:
@Composable
fun Field (modifier: Modifier = Modifier,
onValueChange: (String, String) -> String = { _, new -> new }){
val state = rememberSaveable { mutableStateOf("") }
OutlinedTextField(
modifier = modifier.requiredWidth(75.dp),
singleLine = true,
value = state.value,
onValueChange = {
val value = onValueChange(state.value, it)
state.value = value
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next),
)
}
and then use:
Field(onValueChange = { old, new ->
if (new.length > 1 || new.any { !it.isDigit() }) old else new
})
A:
To solve this usecase you can use decoration box in BasicTextfield.
@Composable
fun InputField(
modifier: Modifier = Modifier,
text: String = "",
length: Int = 5,
keyboardOptions: KeyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
onFocusChanged: () -> Unit = {},
onTextChange: (String) -> Unit
) {
val BoxHeight = 40.dp
val BoxWidth = 40.dp
var textValue by remember { mutableStateOf(text) }
val focusRequester = remember { FocusRequester() }
val focusManager = LocalFocusManager.current
var isFocused by remember { mutableStateOf(false) }
if (text.length == length) {
textValue = text
}
BasicTextField(
modifier = modifier
.focusRequester(focusRequester)
.onFocusChanged {
isFocused = it.isFocused
onFocusChanged(it)
},
value = textValue,
singleLine = true,
onValueChange = {
textValue = it
if (it.length <= length) {
onTextChange.invoke(it)
}
},
enabled = enabled,
keyboardOptions = keyboardOptions,
decorationBox = {
Row(Modifier.fillMaxWidth()) {
repeat(length) { index ->
Text(
text = textValue,
modifier = Modifier
.size(
width =
BoxWidth,
height = BoxHeight
)
.clip(RoundedCornerShape(4.dp))
,
)
Spacer(modifier = Modifier.width(8.dp))
}
}
}
)
if (acquireFocus && textValue.length != length) {
focusRequester.requestFocus()
}
}
This will create a boxes as shown below length number of times(5 here). This is just a simple TextField with decoration as multiple boxes. You can use this text in viewModel.
TextField Examples: https://developer.android.com/jetpack/compose/text
A:
set your keyboard option number password type see the below code
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword)
below the keyboard output
A:
It might be late but hopefully, this will help someone.
I came here to find a solution but found @Nikhil code which gave me an idea of how to do it (But failed to do it). So based on his answer I have improved the composable and fixed the issues. Have not heavily tested it yet but it acts the same as you want:
@Composable
fun DecoratedTextField(
value: String,
length: Int,
modifier: Modifier = Modifier,
boxWidth: Dp = 38.dp,
boxHeight: Dp = 38.dp,
enabled: Boolean = true,
keyboardOptions: KeyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
keyboardActions: KeyboardActions = KeyboardActions(),
onValueChange: (String) -> Unit,
) {
val spaceBetweenBoxes = 8.dp
BasicTextField(modifier = modifier,
value = value,
singleLine = true,
onValueChange = {
if (it.length <= length) {
onValueChange(it)
}
},
enabled = enabled,
keyboardOptions = keyboardOptions,
keyboardActions = keyboardActions,
decorationBox = {
Row(
Modifier.size(width = (boxWidth + spaceBetweenBoxes) * length, height = boxHeight),
horizontalArrangement = Arrangement.spacedBy(spaceBetweenBoxes),
) {
repeat(length) { index ->
Box(
modifier = Modifier
.size(boxWidth, boxHeight)
.border(
1.dp,
color = MaterialTheme.colors.primary,
shape = RoundedCornerShape(4.dp)
),
contentAlignment = Alignment.Center
) {
Text(
text = value.getOrNull(index)?.toString() ?: "",
textAlign = TextAlign.Center,
style = MaterialTheme.typography.h6
)
}
}
}
})
}
Here is what it looks like:
You can customize the size of the font + the border color to your liking.
The only drawback is that you don't have a cursor and cannot edit each box separately. Will try to fix these issues and if I do, I will update my answer
|
Jetpack compose single number text field
|
I am trying to create a phone verification screen where the user must enter 5 numbers each in their own text field like below.
I have two questions:
Is there a way to limit a TextField to 1 character. I can set single line and max lines, but don't see a way to limit to character length like 'Ms' from the view system. I can easily limit the character length in code by ignoring characters after the first one, but this still lets the user 'scroll' to the left and right even though there is only 1 character.
Is there a way to wrap the width to the 1 character? Currently the only way I have found to limit the width is to set it specifically, but then if the system text size is changed it could break.
Here is some code incase it helps, this is some very jumbled together solution so apologies if something is incorrect:
@Composable
fun CodeTextFields(
modifier: Modifier = Modifier,
length: Int = 5,
onFilled: (code: String) -> Unit
) {
var code: List<Char> by remember {
mutableStateOf(listOf())
}
val focusRequesters: List<FocusRequester> = remember {
val temp = mutableListOf<FocusRequester>()
repeat(length) {
temp.add(FocusRequester())
}
temp
}
Row(modifier = modifier) {
(0 until length).forEach { index ->
OutlinedTextField(
modifier = Modifier
.weight(1f)
.padding(vertical = 2.dp)
.focusRequester(focusRequesters[index]),
textStyle = MaterialTheme.typography.h4.copy(textAlign = TextAlign.Center),
singleLine = true,
value = code.getOrNull(index)?.takeIf { it.isDigit() }?.toString() ?: "",
onValueChange = { value: String ->
if (focusRequesters[index].freeFocus()) { //For some reason this fixes the issue of focusrequestor causing on value changed to call twice
val temp = code.toMutableList()
if (value == "") {
if (temp.size > index) {
temp.removeAt(index)
code = temp
focusRequesters.getOrNull(index - 1)?.requestFocus()
}
} else {
if (code.size > index) {
temp[index] = value.getOrNull(0) ?: ' '
} else if (value.getOrNull(0)?.isDigit() == true) {
temp.add(value.getOrNull(0) ?: ' ')
code = temp
focusRequesters.getOrNull(index + 1)?.requestFocus() ?: onFilled(
code.joinToString(separator = "")
)
}
}
}
},
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next
),
)
Spacer(modifier = Modifier.width(16.dp))
}
}
}
|
[
"To limit to 1 number you can use something like:\n@Composable\nfun Field (modifier: Modifier = Modifier,\n onValueChange: (String, String) -> String = { _, new -> new }){\n\n val state = rememberSaveable { mutableStateOf(\"\") }\n\n OutlinedTextField(\n modifier = modifier.requiredWidth(75.dp),\n singleLine = true,\n value = state.value,\n onValueChange = {\n val value = onValueChange(state.value, it)\n state.value = value\n },\n keyboardOptions = KeyboardOptions(\n keyboardType = KeyboardType.Number,\n imeAction = ImeAction.Next),\n )\n}\n\nand then use:\nField(onValueChange = { old, new ->\n if (new.length > 1 || new.any { !it.isDigit() }) old else new\n})\n\n\n",
"To solve this usecase you can use decoration box in BasicTextfield.\n@Composable\nfun InputField(\n modifier: Modifier = Modifier,\n text: String = \"\",\n length: Int = 5,\n keyboardOptions: KeyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),\n onFocusChanged: () -> Unit = {},\n onTextChange: (String) -> Unit\n) {\n val BoxHeight = 40.dp\n val BoxWidth = 40.dp\n var textValue by remember { mutableStateOf(text) }\n val focusRequester = remember { FocusRequester() }\n val focusManager = LocalFocusManager.current\n var isFocused by remember { mutableStateOf(false) }\n\n if (text.length == length) {\n textValue = text\n }\n\n BasicTextField(\n modifier = modifier\n .focusRequester(focusRequester)\n .onFocusChanged {\n isFocused = it.isFocused\n onFocusChanged(it)\n },\n value = textValue,\n singleLine = true,\n onValueChange = {\n textValue = it\n if (it.length <= length) {\n onTextChange.invoke(it)\n }\n },\n enabled = enabled,\n keyboardOptions = keyboardOptions,\n decorationBox = {\n Row(Modifier.fillMaxWidth()) {\n repeat(length) { index ->\n Text(\n text = textValue,\n modifier = Modifier\n .size(\n width = \n BoxWidth,\n height = BoxHeight\n )\n .clip(RoundedCornerShape(4.dp))\n ,\n )\n Spacer(modifier = Modifier.width(8.dp))\n }\n }\n }\n )\n\n if (acquireFocus && textValue.length != length) {\n focusRequester.requestFocus()\n }\n}\n\nThis will create a boxes as shown below length number of times(5 here). This is just a simple TextField with decoration as multiple boxes. You can use this text in viewModel.\nTextField Examples: https://developer.android.com/jetpack/compose/text\n\n",
"set your keyboard option number password type see the below code\nkeyboardOptions = KeyboardOptions(keyboardType = KeyboardType.NumberPassword)\n\nbelow the keyboard output\n\n",
"It might be late but hopefully, this will help someone.\nI came here to find a solution but found @Nikhil code which gave me an idea of how to do it (But failed to do it). So based on his answer I have improved the composable and fixed the issues. Have not heavily tested it yet but it acts the same as you want:\n@Composable\nfun DecoratedTextField(\n value: String,\n length: Int,\n modifier: Modifier = Modifier,\n boxWidth: Dp = 38.dp,\n boxHeight: Dp = 38.dp,\n enabled: Boolean = true,\n keyboardOptions: KeyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),\n keyboardActions: KeyboardActions = KeyboardActions(),\n onValueChange: (String) -> Unit,\n) {\n val spaceBetweenBoxes = 8.dp\n BasicTextField(modifier = modifier,\n value = value,\n singleLine = true,\n onValueChange = {\n if (it.length <= length) {\n onValueChange(it)\n }\n },\n enabled = enabled,\n keyboardOptions = keyboardOptions,\n keyboardActions = keyboardActions,\n decorationBox = {\n Row(\n Modifier.size(width = (boxWidth + spaceBetweenBoxes) * length, height = boxHeight),\n horizontalArrangement = Arrangement.spacedBy(spaceBetweenBoxes),\n ) {\n repeat(length) { index ->\n Box(\n modifier = Modifier\n .size(boxWidth, boxHeight)\n .border(\n 1.dp,\n color = MaterialTheme.colors.primary,\n shape = RoundedCornerShape(4.dp)\n ),\n contentAlignment = Alignment.Center\n ) {\n Text(\n text = value.getOrNull(index)?.toString() ?: \"\",\n textAlign = TextAlign.Center,\n style = MaterialTheme.typography.h6\n )\n }\n }\n }\n })\n}\n\nHere is what it looks like:\n\nYou can customize the size of the font + the border color to your liking.\nThe only drawback is that you don't have a cursor and cannot edit each box separately. Will try to fix these issues and if I do, I will update my answer\n"
] |
[
3,
3,
0,
0
] |
[] |
[] |
[
"android",
"android_jetpack",
"android_jetpack_compose",
"textfield"
] |
stackoverflow_0067025661_android_android_jetpack_android_jetpack_compose_textfield.txt
|
Q:
How to change the row selection checkbox icon from "tick mark" to "xmark" in reactable?
I would like to change checkbox icon for row selection from "tick mark" to "xmark" on reactable in shiny. Not sure how to do this.
Here is my attempt:
library(shiny)
library(reactable)
library(shinyWidgets)
ui <- fluidPage(
titlePanel("row selection example"),
reactableOutput("table"),
verbatimTextOutput("selected")
)
server <- function(input, output, session) {
selected <- reactive(getReactableState("table", "selected"))
output$table <- renderReactable({
reactable(iris, selection = "multiple", onClick = "select",
columns = list(
.selection = colDef(
sticky = "left",
cell = function (value,index) prettyCheckbox(inputId=paste0("cb",index),
label="",
value = FALSE,
icon = icon('times')))
)
)
})
observe({
print(iris[selected(), ])
})
}
shinyApp(ui, server)
A:
Use following CSS:
library(shiny)
library(reactable)
library(shinyWidgets)
ui <- fluidPage(
titlePanel("row selection example"),
reactableOutput("table"),
verbatimTextOutput("selected"),
tags$style(
'
.rt-table input[type="checkbox"]:checked:after {
content: "X";
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: #4399f3;
color: white;
width: 15px;
height: 15px;
text-align: center;
font-weight: 900;
border-radius: 3px;
}
'
)
)
server <- function(input, output, session) {
selected <- reactive(getReactableState("table", "selected"))
output$table <- renderReactable({
reactable(iris, selection = "multiple", onClick = "select",
columns = list(
.selection = colDef(
sticky = "left",
cell = function (value,index) prettyCheckbox(inputId=paste0("cb",index),
label="",
value = FALSE,
icon = icon('times')))
)
)
})
observe({
print(iris[selected(), ])
})
}
shinyApp(ui, server)
A trick is used here. :after content with X inside overlaps on the original box when checked.
|
How to change the row selection checkbox icon from "tick mark" to "xmark" in reactable?
|
I would like to change checkbox icon for row selection from "tick mark" to "xmark" on reactable in shiny. Not sure how to do this.
Here is my attempt:
library(shiny)
library(reactable)
library(shinyWidgets)
ui <- fluidPage(
titlePanel("row selection example"),
reactableOutput("table"),
verbatimTextOutput("selected")
)
server <- function(input, output, session) {
selected <- reactive(getReactableState("table", "selected"))
output$table <- renderReactable({
reactable(iris, selection = "multiple", onClick = "select",
columns = list(
.selection = colDef(
sticky = "left",
cell = function (value,index) prettyCheckbox(inputId=paste0("cb",index),
label="",
value = FALSE,
icon = icon('times')))
)
)
})
observe({
print(iris[selected(), ])
})
}
shinyApp(ui, server)
|
[
"Use following CSS:\nlibrary(shiny)\nlibrary(reactable)\nlibrary(shinyWidgets)\nui <- fluidPage(\n titlePanel(\"row selection example\"),\n reactableOutput(\"table\"),\n verbatimTextOutput(\"selected\"),\n tags$style(\n '\n .rt-table input[type=\"checkbox\"]:checked:after {\n content: \"X\";\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%,-50%);\n background-color: #4399f3;\n color: white;\n width: 15px;\n height: 15px;\n text-align: center;\n font-weight: 900;\n border-radius: 3px;\n }\n '\n )\n)\n\nserver <- function(input, output, session) {\n selected <- reactive(getReactableState(\"table\", \"selected\"))\n \n output$table <- renderReactable({\n reactable(iris, selection = \"multiple\", onClick = \"select\",\n columns = list(\n .selection = colDef(\n sticky = \"left\",\n cell = function (value,index) prettyCheckbox(inputId=paste0(\"cb\",index),\n label=\"\",\n value = FALSE,\n icon = icon('times')))\n )\n \n )\n })\n \n \n \n observe({\n print(iris[selected(), ])\n })\n}\n\nshinyApp(ui, server)\n\nA trick is used here. :after content with X inside overlaps on the original box when checked.\n\n"
] |
[
0
] |
[] |
[] |
[
"checkbox",
"dt",
"r",
"reactable",
"shiny"
] |
stackoverflow_0074660900_checkbox_dt_r_reactable_shiny.txt
|
Q:
How do CSS triangles work?
There're plenty of different CSS shapes over at CSS Tricks - Shapes of CSS and I'm particularly puzzled with a triangle:
#triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
<div id="triangle-up"></div>
How and why does it work?
A:
CSS Triangles: A Tragedy in Five Acts
As alex said, borders of equal width butt up against each other at 45 degree angles:
When you have no top border, it looks like this:
Then you give it a width of 0...
...and a height of 0...
...and finally, you make the two side borders transparent:
That results in a triangle.
A:
The borders use an angled edge where they intersect (45° angle with equal width borders, but changing the border widths can skew the angle).
div {
width: 60px;
border-width: 30px;
border-color: red blue green yellow;
border-style: solid;
}
<div></div>
Have a look to the jsFiddle.
By hiding certain borders, you can get the triangle effect (as you can see above by making the different portions different colours). transparent is often used as an edge colour to achieve the triangle shape.
A:
Start with a basic square and borders. Each border will be given a different color so we can tell them apart:
.triangle {
border-color: yellow blue red green;
border-style: solid;
border-width: 200px 200px 200px 200px;
height: 0px;
width: 0px;
}
<div class="triangle"></div>
which gives you this:
But there's no need for the top border, so set its width to 0px. Now our border-bottom of 200px will make our triangle 200px tall.
.triangle {
border-color: yellow blue red green;
border-style: solid;
border-width: 0px 200px 200px 200px;
height: 0px;
width: 0px;
}
<div class="triangle"></div>
and we will get this:
Then to hide the two side triangles, set the border-color to transparent. Since the top-border has been effectively deleted, we can set the border-top-color to transparent as well.
.triangle {
border-color: transparent transparent red transparent;
border-style: solid;
border-width: 0px 200px 200px 200px;
height: 0px;
width: 0px;
}
<div class="triangle"></div>
finally we get this:
A:
Different approach:
CSS3 triangles with transform rotate
Triangular shape is pretty easy to make using this technique. For people who prefer to see an animation explaining how this technique works here it is :
Link to the ANIMATION : How to make a CSS3 triangle.
And DEMO : CSS3 triangles made with transform rotate.
Otherwise, here is detailed explanation in 4 acts (this is not a tragedy) of how to make an isosceles right-angled triangle with one element.
Note 1 : for non isosceles triangles and fancy stuff, you can see step 4.
Note 2 : in the following snippets, the vendor prefixes aren't included. they are included in the codepen demos.
Note 3 : the HTML for the following explanation is always : <div class="tr"></div>
STEP 1 : Make a div
Easy, just make sure that width = 1.41 x height. You may use any techinque (see here) including the use of percentages and padding-bottom to maintain the aspect ratio and make a responsive triangle. In the following image, the div has a golden yellow border.
In that div, insert a pseudo element and give it 100% width and height of parent. The pseudo element has a blue background in the following image.
At this point, we have this CSS :
.tr {
width: 30%;
padding-bottom: 21.27%; /* = width / 1.41 */
position: relative;
}
.tr: before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #0079C6;
}
STEP 2 : Let's rotate
First, most important : define a transform origin. The default origin is in the center of the pseudo element and we need it at the bottom left. By adding this CSS to the pseudo element :
transform-origin:0 100%; or transform-origin: left bottom;
Now we can rotate the pseudo element 45 degrees clockwise with transform : rotate(45deg);
At this point, we have this CSS :
.tr {
width: 30%;
padding-bottom: 21.27%; /* = width / 1.41 */
position: relative;
}
.tr:before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #0079C6;
transform-origin: 0 100%;
transform: rotate(45deg);
}
STEP 3 : hide it
To hide the unwanted parts of the pseudo element (everything that overflows the div with the yellow border) you just need to set overflow:hidden; on the container. after removing the yellow border, you get... a TRIANGLE! :
DEMO
CSS :
.tr {
width: 30%;
padding-bottom: 21.27%; /* = width / 1.41 */
position: relative;
overflow: hidden;
}
.tr:before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #0079C6;
transform-origin: 0 100%;
transform: rotate(45deg);
}
STEP 4 : go further...
As shown in the demo, you can customize the triangles :
Make them thinner or flatter by playing with skewX().
Make them point left, right or any other direction by playing with the transform orign and rotation direction.
Make some reflexion with 3D transform property.
Give the triangle borders
Put an image inside the triangle
Much more... Unleash the powers of CSS3!
Why use this technique?
Triangle can easily be responsive.
You can make a triangle with border.
You can maintain the boundaries of the triangle. This means that you can trigger the hover state or click event only when the cursor is inside the triangle. This can become very handy in some situations like this one where each triangle can't overlay it's neighbours so each triangle has it's own hover state.
You can make some fancy effects like reflections.
It will help you understand 2d and 3d transform properties.
Why not use this technique?
The main drawback is the browser compatibility, the 2d transform properties are supported by IE9+ and therefore you can't use this technique if you plan on supporting IE8. See CanIuse for more info. For some fancy effects using 3d transforms like the reflection browser support is IE10+ (see canIuse for more info).
You don't need anything responsive and a plain triangle is fine for you then you should go for the border technique explained here : better browser compatibility and easier to understand thanks to the amazing posts here.
A:
Here is an animation in JSFiddle I created for demonstration.
Also see snippet below.
This is an Animated GIF made from a Screencast
transforms = [
{'border-left-width' :'30', 'margin-left': '70'},
{'border-bottom-width' :'80'},
{'border-right-width' :'30'},
{'border-top-width' :'0', 'margin-top': '70'},
{'width' :'0'},
{'height' :'0', 'margin-top': '120'},
{'borderLeftColor' :'transparent'},
{'borderRightColor' :'transparent'}
];
$('#a').click(function() {$('.border').trigger("click");});
(function($) {
var duration = 1000
$('.border').click(function() {
for ( var i=0; i < transforms.length; i++ ) {
$(this)
.animate(transforms[i], duration)
}
}).end()
}(jQuery))
.border {
margin: 20px 50px;
width: 50px;
height: 50px;
border-width: 50px;
border-style: solid;
border-top-color: green;
border-right-color: yellow;
border-bottom-color: red;
border-left-color: blue;
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
Click it!<br>
<div class="border"></div>
Random version
/**
* Randomize array element order in-place.
* Using Durstenfeld shuffle algorithm.
*/
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
transforms = [
{'border-left-width' :'30', 'margin-left': '70'},
{'border-bottom-width' :'80'},
{'border-right-width' :'30'},
{'border-top-width' :'0', 'margin-top': '70'},
{'width' :'0'},
{'height' :'0'},
{'borderLeftColor' :'transparent'},
{'borderRightColor' :'transparent'}
];
transforms = shuffleArray(transforms)
$('#a').click(function() {$('.border').trigger("click");});
(function($) {
var duration = 1000
$('.border').click(function() {
for ( var i=0; i < transforms.length; i++ ) {
$(this)
.animate(transforms[i], duration)
}
}).end()
}(jQuery))
.border {
margin: 50px;
width: 50px;
height: 50px;
border-width: 50px;
border-style: solid;
border-top-color: green;
border-right-color: yellow;
border-bottom-color: red;
border-left-color: blue;
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
Click it!<br>
<div class="border"></div>
All at once version
$('#a').click(function() {$('.border').trigger("click");});
(function($) {
var duration = 1000
$('.border').click(function() {
$(this)
.animate({'border-top-width': 0 ,
'border-left-width': 30 ,
'border-right-width': 30 ,
'border-bottom-width': 80 ,
'width': 0 ,
'height': 0 ,
'margin-left': 100,
'margin-top': 150,
'borderTopColor': 'transparent',
'borderRightColor': 'transparent',
'borderLeftColor': 'transparent'}, duration)
}).end()
}(jQuery))
.border {
margin: 50px;
width: 50px;
height: 50px;
border-width: 50px;
border-style: solid;
border-top-color: green;
border-right-color: yellow;
border-bottom-color: red;
border-left-color: blue;
cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
Click it!<br>
<div class="border"></div>
A:
Lets say we have the following div:
<div id="triangle" />
Now Edit the CSS step-by-step, so you will get clear idea what is happening around
STEP 1:
JSfiddle Link:
#triangle {
background: purple;
width :150px;
height:150PX;
border-left: 50px solid black ;
border-right: 50px solid black;
border-bottom: 50px solid black;
border-top: 50px solid black;
}
This is a simple div. With a very simple CSS. So a layman can understand. Div has dimensions 150 x 150 pixels with the border 50 pixels. The image is attached:
STEP 2: JSfiddle Link:
#triangle {
background: purple;
width :150px;
height:150PX;
border-left: 50px solid yellow ;
border-right: 50px solid green;
border-bottom: 50px solid red;
border-top: 50px solid blue;
}
Now I just changed the border-color of all 4 sides. The image is attached.
STEP:3 JSfiddle Link:
#triangle {
background: purple;
width :0;
height:0;
border-left: 50px solid yellow ;
border-right: 50px solid green;
border-bottom: 50px solid red;
border-top: 50px solid blue;
}
Now I just changed the height & width of div from 150 pixels to zero. The image is attached
STEP 4: JSfiddle:
#triangle {
background: purple;
width :0px;
height:0px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid red;
border-top: 50px solid transparent;
}
Now I have made all the borders transparent apart from the bottom border. The image is attached below.
STEP 5: JSfiddle Link:
#triangle {
background: white;
width :0px;
height:0px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid red;
border-top: 50px solid transparent;
}
Now I just changed the background color to white. The image is attached.
Hence we got the triangle we needed.
A:
And now something completely different...
Instead of using css tricks don't forget about solutions as simple as html entities:
▲
Result:
▲
See: What are the HTML entities for up and down triangles?
A:
Consider the below triangle
.triangle {
border-bottom:15px solid #000;
border-left:10px solid transparent;
border-right:10px solid transparent;
width:0;
height:0;
}
This is what we are given:
Why it came out in this shape? The below diagram explains the dimensions, note that 15px was used for the bottom border and 10px was used for left and right.
It's pretty easy to make a right-angle triangle also by removing the right border.
A:
Taking it one step further, using css based on this I added arrows to my back and next buttons (yes I know its not 100% cross-browser, but slick none the less).
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
margin:20px auto;
}
.triangle-down {
border-bottom:none;
border-top: 100px solid red;
}
.triangle-left {
border-left:none;
border-right: 100px solid red;
border-bottom: 50px solid transparent;
border-top: 50px solid transparent;
}
.triangle-right {
border-right:none;
border-left: 100px solid red;
border-bottom: 50px solid transparent;
border-top: 50px solid transparent;
}
.triangle-after:after {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid red;
margin:0 5px;
content:"";
display:inline-block;
}
.triangle-after-right:after {
border-right:none;
border-left: 5px solid blue;
border-bottom: 5px solid transparent;
border-top: 5px solid transparent;
}
.triangle-before:before {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid blue;
margin:0 5px;
content:"";
display:inline-block;
}
.triangle-before-left:before {
border-left:none;
border-right: 5px solid blue;
border-bottom: 5px solid transparent;
border-top: 5px solid transparent;
}
<div class="triangle"></div>
<div class="triangle triangle-down"></div>
<div class="triangle triangle-left"></div>
<div class="triangle triangle-right"></div>
<a class="triangle-before triangle-before-left" href="#">Back</a>
<a class="triangle-after triangle-after-right" href="#">Next</a>
A:
Different approach. With linear gradient (for IE, only IE 10+).
You can use any angle:
.triangle {
margin: 50px auto;
width: 100px;
height: 100px;
/* linear gradient */
background: -moz-linear-gradient(-45deg, rgba(255,0,0,0) 0%, rgba(255,0,0,0) 50%, rgba(255,0,0,1) 50%, rgba(255,0,0,1) 100%);
/* FF3.6+ */
background: -webkit-gradient(linear, left top, right bottom, color-stop(0%,rgba(255,0,0,0)), color-stop(50%,rgba(255,0,0,0)), color-stop(50%,rgba(255,0,0,1)), color-stop(100%,rgba(255,0,0,1)));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(-45deg, rgba(255,0,0,0) 0%,rgba(255,0,0,0) 50%,rgba(255,0,0,1) 50%,rgba(255,0,0,1) 100%);
/* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(-45deg, rgba(255,0,0,0) 0%,rgba(255,0,0,0) 50%,rgba(255,0,0,1) 50%,rgba(255,0,0,1) 100%);
/* Opera 11.10+ */
background: -ms-linear-gradient(-45deg, rgba(255,0,0,0) 0%,rgba(255,0,0,0) 50%,rgba(255,0,0,1) 50%,rgba(255,0,0,1) 100%);
/* IE10+ */
background: linear-gradient(135deg, rgba(255,0,0,0) 0%,rgba(255,0,0,0) 50%,rgba(255,0,0,1) 50%,rgba(255,0,0,1) 100%);
/* W3C */;
}
<div class="triangle"></div>
Here is jsfiddle
A:
CSS clip-path
This is something I feel this question has missed; clip-path
clip-path in a nutshell
Clipping, with the clip-path property, is akin to cutting a shape (like a circle or a pentagon) from a rectangular piece of paper. The property belongs to the “CSS Masking Module Level 1” specification. The spec states, “CSS masking provides two means for partially or fully hiding portions of visual elements: masking and clipping”.
Extract from Smashing Magazine
clip-path will use the element itself rather than its borders to cut the shape you specify in its parameters. It uses a super simple percentage based co-ordinate system which makes editing it very easy and means you can pick it up and create weird and wonderful shapes in a matter of minutes.
Triangle Shape Example
div {
-webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
background: red;
width: 100px;
height: 100px;
}
<div></div>
Downside
It does have a major downside at the moment, one being it's major lack of support, only really being covered within -webkit- browsers and having no support on IE and only very partial in FireFox.
Resources
Here are some useful resources and material to help better understand clip-path and also start creating your own.
Clippy - A clip-path generator
The W3C Candidate Recommendation File
MDN clip-path documentation
clip-path Browser Support
A:
OK, this triangle will get created because of the way that borders of the elements work together in HTML and CSS...
As we usually use 1 or 2px borders, we never notice that borders make a 45° angles to each others with the same width and if the width changes, the angle degree get changed as well, run the CSS code I created below:
.triangle {
width: 100px;
height: 100px;
border-left: 50px solid black;
border-right: 50px solid black;
border-bottom: 100px solid red;
}
<div class="triangle">
</div>
Then in the next step, we don't have any width or height, something like this:
.triangle {
width: 0;
height: 0;
border-left: 50px solid black;
border-right: 50px solid black;
border-bottom: 100px solid red;
}
<div class="triangle">
</div>
And now we make the left and right borders invisible to make our desirable triangle as below:
.triangle {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
<div class="triangle"></div>
If you not willing to run the snippet to see the steps, I've created an image sequence to have a look at all steps in one image:
A:
This is an old question, but I think will worth it to share how to create an arrow using this triangle technique.
Step 1:
Lets create 2 triangles, for the second one we will use the :after pseudo class and position it just below the other:
.arrow{
width: 0;
height: 0;
border-radius: 50px;
display: inline-block;
position: relative;
}
.arrow:after{
content: "";
width: 0;
height: 0;
position: absolute;
}
.arrow-up{
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #333;
}
.arrow-up:after{
top: 5px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #ccc;
right: -50px;
}
<div class="arrow arrow-up"> </div>
Step 2
Now we just have to set the predominant border color of the second triangle to the same color of the background:
.arrow{
width: 0;
height: 0;
border-radius: 50px;
display: inline-block;
position: relative;
}
.arrow:after{
content: "";
width: 0;
height: 0;
position: absolute;
}
.arrow-up{
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #333;
}
.arrow-up:after{
top: 5px;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 50px solid #fff;
right: -50px;
}
<div class="arrow arrow-up"> </div>
Fiddle with all the arrows:
http://jsfiddle.net/tomsarduy/r0zksgeu/
A:
If you want to apply border to the triangle read this: Create a triangle with CSS?
Almost all the answers focus on the triangle built using border so I am going to elaborate the linear-gradient method (as started in the answer of @lima_fil).
Using a degree value like 45° will force us to respect a specific ratio of height/width in order to obtain the triangle we want and this won't be responsive:
.tri {
width:100px;
height:100px;
background:linear-gradient(45deg, transparent 49.5%,red 50%);
/*To illustrate*/
border:1px solid;
}
Good one
<div class="tri"></div>
bad one
<div class="tri" style="width:150px"></div>
bad one
<div class="tri" style="height:30px"></div>
Instead of doing this we should consider predefined values of direction like to bottom, to top, etc. In this case we can obtain any kind of triangle shape while keeping it responsive.
1) Rectangle triangle
To obtain such triangle we need one linear-gradient and a diagonal direction like to bottom right, to top left, to bottom left, etc
.tri-1,.tri-2 {
display:inline-block;
width:100px;
height:100px;
background:linear-gradient(to bottom left, transparent 49.5%,red 50%);
border:1px solid;
animation:change 2s linear infinite alternate;
}
.tri-2 {
background:linear-gradient(to top right, transparent 49.5%,red 50%);
border:none;
}
@keyframes change {
from {
width:100px;
height:100px;
}
to {
height:50px;
width:180px;
}
}
<div class="tri-1"></div>
<div class="tri-2"></div>
2) isosceles triangle
For this one we will need 2 linear-gradient like above and each one will take half the width (or the height). It's like we create a mirror image of the first triangle.
.tri {
display:inline-block;
width:100px;
height:100px;
background-image:
linear-gradient(to bottom right, transparent 49.5%,red 50%),
linear-gradient(to bottom left, transparent 49.5%,red 50%);
background-size:50.3% 100%; /* I use a value slightly bigger than 50% to avoid having a small gap between both gradient*/
background-position:left,right;
background-repeat:no-repeat;
animation:change 2s linear infinite alternate;
}
@keyframes change {
from {
width:100px;
height:100px;
}
to {
height:50px;
width:180px;
}
}
<div class="tri"></div>
3) equilateral triangle
This one is a bit tricky to handle as we need to keep a relation between the height and width of the gradient. We will have the same triangle as above but we will make the calculation more complex in order to transform the isosceles triangle to an equilateral one.
To make it easy, we will consider that the width of our div is known and the height is big enough to be able to draw our triangle inside (height >= width).
We have our two gradient g1 and g2, the blue line is the width of the div w and each gradient will have 50% of it (w/2) and each side of the triangle sould be equal to w. The green line is the height of both gradient hg and we can easily obtain the formula below:
(w/2)² + hg² = w² ---> hg = (sqrt(3)/2) * w ---> hg = 0.866 * w
We can rely on calc() in order to do our calculation and to obtain the needed result:
.tri {
--w:100px;
width:var(--w);
height:100px;
display:inline-block;
background-image:
linear-gradient(to bottom right, transparent 49.5%,red 50%),
linear-gradient(to bottom left, transparent 49.5%,red 50%);
background-size:calc(var(--w)/2 + 0.5px) calc(0.866 * var(--w));
background-position:
left bottom,right bottom;
background-repeat:no-repeat;
}
<div class="tri"></div>
<div class="tri" style="--w:80px"></div>
<div class="tri" style="--w:50px"></div>
Another way is to control the height of div and keep the syntax of gradient easy:
.tri {
--w:100px;
width:var(--w);
height:calc(0.866 * var(--w));
display:inline-block;
background:
linear-gradient(to bottom right, transparent 49.8%,red 50%) left,
linear-gradient(to bottom left, transparent 49.8%,red 50%) right;
background-size:50.2% 100%;
background-repeat:no-repeat;
}
<div class="tri"></div>
<div class="tri" style="--w:80px"></div>
<div class="tri" style="--w:50px"></div>
4) Random triangle
To obtain a random triangle, it's easy as we simply need to remove the condition of 50% of each one BUT we should keep two condition (both should have the same height and the sum of both width should be 100%).
.tri-1 {
width:100px;
height:100px;
display:inline-block;
background-image:
linear-gradient(to bottom right, transparent 50%,red 0),
linear-gradient(to bottom left, transparent 50%,red 0);
background-size:20% 60%,80% 60%;
background-position:
left bottom,right bottom;
background-repeat:no-repeat;
}
<div class="tri-1"></div>
But what if we want to define a value for each side? We simply need to do calculation again!
Let's define hg1 and hg2 as the height of our gradient (both are equal to the red line) then wg1 and wg2 as the width of our gradient (wg1 + wg2 = a). I will not going to detail the calculation but at then end we will have:
wg2 = (a²+c²-b²)/(2a)
wg1 = a - wg2
hg1 = hg2 = sqrt(b² - wg1²) = sqrt(c² - wg2²)
Now we have reached the limit of CSS as even with calc() we won't be able to implement this so we simply need to gather the final result manually and use them as fixed size:
.tri {
--wg1: 20px;
--wg2: 60px;
--hg:30px;
width:calc(var(--wg1) + var(--wg2));
height:100px;
display:inline-block;
background-image:
linear-gradient(to bottom right, transparent 49.5%,red 50%),
linear-gradient(to bottom left, transparent 49.5%,red 50%);
background-size:var(--wg1) var(--hg),var(--wg2) var(--hg);
background-position:
left bottom,right bottom;
background-repeat:no-repeat;
}
<div class="tri" ></div>
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;" ></div>
Bonus
We should not forget that we can also apply rotation and/or skew and we have more option to obtain more triangle:
.tri {
--wg1: 20px;
--wg2: 60px;
--hg:30px;
width:calc(var(--wg1) + var(--wg2) - 0.5px);
height:100px;
display:inline-block;
background-image:
linear-gradient(to bottom right, transparent 49%,red 50%),
linear-gradient(to bottom left, transparent 49%,red 50%);
background-size:var(--wg1) var(--hg),var(--wg2) var(--hg);
background-position:
left bottom,right bottom;
background-repeat:no-repeat;
}
<div class="tri" ></div>
<div class="tri" style="transform:skewY(25deg)"></div>
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;" ></div>
<div class="tri" style="--wg1:80px;--wg2:60px;--hg:100px;transform:rotate(20deg)" ></div>
And of course we should keep in mind the SVG solution which can be more suitable in some situation:
svg {
width:100px;
height:100px;
}
polygon {
fill:red;
}
<svg viewBox="0 0 100 100"><polygon points="0,100 0,0 100,100" /></svg>
<svg viewBox="0 0 100 100"><polygon points="0,100 50,0 100,100" /></svg>
<svg viewBox="0 0 100 100"><polygon points="0,100 50,23 100,100" /></svg>
<svg viewBox="0 0 100 100"><polygon points="20,60 50,43 80,100" /></svg>
A:
SASS (SCSS) triangle mixin
I wrote this to make it easier (and DRY) to automatically generate a CSS triangle:
// Triangle helper mixin (by Yair Even-Or)
// @param {Direction} $direction - either `top`, `right`, `bottom` or `left`
// @param {Color} $color [currentcolor] - Triangle color
// @param {Length} $size [1em] - Triangle size
@mixin triangle($direction, $color: currentcolor, $size: 1em) {
$size: $size/2;
$transparent: rgba($color, 0);
$opposite: (top:bottom, right:left, left:right, bottom:top);
content: '';
display: inline-block;
width: 0;
height: 0;
border: $size solid $transparent;
border-#{map-get($opposite, $direction)}-color: $color;
margin-#{$direction}: -$size;
}
use-case example:
span {
@include triangle(bottom, red, 10px);
}
Playground page
Important note: if the triangle seems pixelated in some browsers, try one of the methods described here.
A:
If you want to play around with border-size, width and height and see how those can create different shapes, try this:
const sizes = [32, 32, 32, 32];
const triangle = document.getElementById('triangle');
function update({ target }) {
let index = null;
if (target) {
index = parseInt(target.id);
if (!isNaN(index)) {
sizes[index] = target.value;
}
}
window.requestAnimationFrame(() => {
triangle.style.borderWidth = sizes.map(size => `${ size }px`).join(' ');
if (isNaN(index)) {
triangle.style[target.id] = `${ target.value }px`;
}
});
}
document.querySelectorAll('input').forEach(input => {
input.oninput = update;
});
update({});
body {
margin: 0;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
}
#triangle {
border-style: solid;
border-color: yellow magenta blue black;
background: cyan;
height: 0px;
width: 0px;
}
#controls {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: white;
display: flex;
box-shadow: 0 0 32px rgba(0, 0, 0, .125);
}
#controls > div {
position: relative;
width: 25%;
padding: 8px;
box-sizing: border-box;
display: flex;
}
input {
margin: 0;
width: 100%;
position: relative;
}
<div id="triangle" style="border-width: 32px 32px 32px 32px;"></div>
<div id="controls">
<div><input type="range" min="0" max="128" value="32" id="0" /></div>
<div><input type="range" min="0" max="128" value="32" id="1" /></div>
<div><input type="range" min="0" max="128" value="32" id="2" /></div>
<div><input type="range" min="0" max="128" value="32" id="3" /></div>
<div><input type="range" min="0" max="128" value="0" id="width" /></div>
<div><input type="range" min="0" max="128" value="0" id="height" /></div>
</div>
A:
here is another fiddle:
.container:after {
position: absolute;
right: 0;
content: "";
margin-right:-50px;
margin-bottom: -8px;
border-width: 25px;
border-style: solid;
border-color: transparent transparent transparent #000;
width: 0;
height: 0;
z-index: 10;
-webkit-transition: visibility 50ms ease-in-out,opacity 50ms ease-in-out;
transition: visibility 50ms ease-in-out,opacity 50ms ease-in-out;
bottom: 21px;
}
.container {
float: left;
margin-top: 100px;
position: relative;
width: 150px;
height: 80px;
background-color: #000;
}
.containerRed {
float: left;
margin-top: 100px;
position: relative;
width: 100px;
height: 80px;
background-color: red;
}
https://jsfiddle.net/qdhvdb17/
A:
Others have already explained this well. Let me give you an animation which will explain this quickly: http://codepen.io/chriscoyier/pen/lotjh
Here is some code for you to play with and learn the concepts.
HTML:
<html>
<body>
<div id="border-demo">
</div>
</body>
</html>
CSS:
/*border-width is border thickness*/
#border-demo {
background: gray;
border-color: yellow blue red green;/*top right bottom left*/
border-style: solid;
border-width: 25px 25px 25px 25px;/*top right bottom left*/
height: 50px;
width: 50px;
}
Play with this and see what happens. Set height and width to zero. Then remove top border and make left and right transparent, or just look at the code below to make a css triangle:
#border-demo {
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid blue;
}
A:
I know this is an old one, but I'd like to add to this discussion that There are at least 5 different methods for creating a triangle using HTML & CSS alone.
Using borders
Using linear-gradient
Using conic-gradient
Using
transform and overflow
Using clip-path
I think that all have been covered here except for method 3, using the conic-gradient, so I will share it here:
.triangle{
width: 40px;
height: 40px;
background: conic-gradient(at 50% 50%,transparent 135deg,green 0,green 225deg, transparent 0);
}
<div class="triangle"></div>
A:
use clip-path: polygon(50% 0%, 100% 100%, 0% 100%); for creating easy to Triangle
<div class="triangle"></div>
.triangle{width:200px; height:200px;background:#000;clip-path: polygon(50% 0%, 100% 100%, 0% 100%);}
A:
After reading through the other answers here I see there are great explanations as to why the CSS triangle works the way it does. I would consider it to be somewhat of a trick, versus something that you could apply generically.
For something that's easier to read and maintain, I would recommend you define your geometry in SVG.
Then you can convert that SVG using data uri by adding the data:image/svg+xml, prefix. As a data uri, it can now be used as a background-image in a CSS. Because the SVG is in clear text, you can readily make updates to the geometry, stroke, and fill color.
div.tri {
width: 100px;
height: 100px;
display: inline-block;
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path fill="red" d="M31.345 29H1.655L16.5 1.96z"/></svg>');
}
<div>
<div class="tri"></div>
<div class="tri"></div>
<div class="tri"></div>
</div>
|
How do CSS triangles work?
|
There're plenty of different CSS shapes over at CSS Tricks - Shapes of CSS and I'm particularly puzzled with a triangle:
#triangle-up {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
<div id="triangle-up"></div>
How and why does it work?
|
[
"CSS Triangles: A Tragedy in Five Acts\nAs alex said, borders of equal width butt up against each other at 45 degree angles:\n\nWhen you have no top border, it looks like this:\n\nThen you give it a width of 0...\n\n...and a height of 0...\n\n...and finally, you make the two side borders transparent:\n\nThat results in a triangle.\n",
"The borders use an angled edge where they intersect (45° angle with equal width borders, but changing the border widths can skew the angle).\n\n\n\ndiv {\r\n width: 60px;\r\n border-width: 30px;\r\n border-color: red blue green yellow;\r\n border-style: solid;\r\n}\n<div></div>\n\n\n\nHave a look to the jsFiddle.\nBy hiding certain borders, you can get the triangle effect (as you can see above by making the different portions different colours). transparent is often used as an edge colour to achieve the triangle shape.\n",
"Start with a basic square and borders. Each border will be given a different color so we can tell them apart:\n\n\n.triangle {\n border-color: yellow blue red green;\n border-style: solid;\n border-width: 200px 200px 200px 200px;\n height: 0px;\n width: 0px;\n}\n<div class=\"triangle\"></div>\n\n\n\nwhich gives you this:\n\nBut there's no need for the top border, so set its width to 0px. Now our border-bottom of 200px will make our triangle 200px tall.\n\n\n.triangle {\n border-color: yellow blue red green;\n border-style: solid;\n border-width: 0px 200px 200px 200px;\n height: 0px;\n width: 0px;\n}\n<div class=\"triangle\"></div>\n\n\n\nand we will get this:\n\nThen to hide the two side triangles, set the border-color to transparent. Since the top-border has been effectively deleted, we can set the border-top-color to transparent as well.\n\n\n.triangle {\n border-color: transparent transparent red transparent;\n border-style: solid;\n border-width: 0px 200px 200px 200px;\n height: 0px;\n width: 0px;\n}\n<div class=\"triangle\"></div>\n\n\n\nfinally we get this:\n\n",
"Different approach:\nCSS3 triangles with transform rotate\nTriangular shape is pretty easy to make using this technique. For people who prefer to see an animation explaining how this technique works here it is :\n\n\nLink to the ANIMATION : How to make a CSS3 triangle.\nAnd DEMO : CSS3 triangles made with transform rotate.\n\nOtherwise, here is detailed explanation in 4 acts (this is not a tragedy) of how to make an isosceles right-angled triangle with one element.\n\nNote 1 : for non isosceles triangles and fancy stuff, you can see step 4.\nNote 2 : in the following snippets, the vendor prefixes aren't included. they are included in the codepen demos.\nNote 3 : the HTML for the following explanation is always : <div class=\"tr\"></div>\n\n\nSTEP 1 : Make a div\nEasy, just make sure that width = 1.41 x height. You may use any techinque (see here) including the use of percentages and padding-bottom to maintain the aspect ratio and make a responsive triangle. In the following image, the div has a golden yellow border.\nIn that div, insert a pseudo element and give it 100% width and height of parent. The pseudo element has a blue background in the following image.\n\nAt this point, we have this CSS :\n.tr {\n width: 30%;\n padding-bottom: 21.27%; /* = width / 1.41 */\n position: relative;\n}\n\n.tr: before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: #0079C6;\n}\n\nSTEP 2 : Let's rotate\nFirst, most important : define a transform origin. The default origin is in the center of the pseudo element and we need it at the bottom left. By adding this CSS to the pseudo element :\ntransform-origin:0 100%; or transform-origin: left bottom;\nNow we can rotate the pseudo element 45 degrees clockwise with transform : rotate(45deg);\n\nAt this point, we have this CSS :\n.tr {\n width: 30%;\n padding-bottom: 21.27%; /* = width / 1.41 */\n position: relative;\n}\n\n.tr:before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background: #0079C6;\n transform-origin: 0 100%; \n transform: rotate(45deg);\n}\n\nSTEP 3 : hide it\nTo hide the unwanted parts of the pseudo element (everything that overflows the div with the yellow border) you just need to set overflow:hidden; on the container. after removing the yellow border, you get... a TRIANGLE! :\nDEMO\n\nCSS :\n.tr {\n width: 30%;\n padding-bottom: 21.27%; /* = width / 1.41 */\n position: relative;\n overflow: hidden;\n}\n\n.tr:before {\n content: '';\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: #0079C6;\n transform-origin: 0 100%;\n transform: rotate(45deg);\n}\n\nSTEP 4 : go further...\nAs shown in the demo, you can customize the triangles :\n\nMake them thinner or flatter by playing with skewX().\nMake them point left, right or any other direction by playing with the transform orign and rotation direction.\nMake some reflexion with 3D transform property.\nGive the triangle borders\nPut an image inside the triangle\nMuch more... Unleash the powers of CSS3!\n\n\nWhy use this technique?\n\nTriangle can easily be responsive.\nYou can make a triangle with border.\nYou can maintain the boundaries of the triangle. This means that you can trigger the hover state or click event only when the cursor is inside the triangle. This can become very handy in some situations like this one where each triangle can't overlay it's neighbours so each triangle has it's own hover state.\nYou can make some fancy effects like reflections.\nIt will help you understand 2d and 3d transform properties.\n\nWhy not use this technique?\n\nThe main drawback is the browser compatibility, the 2d transform properties are supported by IE9+ and therefore you can't use this technique if you plan on supporting IE8. See CanIuse for more info. For some fancy effects using 3d transforms like the reflection browser support is IE10+ (see canIuse for more info).\nYou don't need anything responsive and a plain triangle is fine for you then you should go for the border technique explained here : better browser compatibility and easier to understand thanks to the amazing posts here.\n\n",
"Here is an animation in JSFiddle I created for demonstration.\nAlso see snippet below. \nThis is an Animated GIF made from a Screencast\n\n\n\ntransforms = [\r\n {'border-left-width' :'30', 'margin-left': '70'},\r\n {'border-bottom-width' :'80'},\r\n {'border-right-width' :'30'},\r\n {'border-top-width' :'0', 'margin-top': '70'},\r\n {'width' :'0'},\r\n {'height' :'0', 'margin-top': '120'},\r\n {'borderLeftColor' :'transparent'},\r\n {'borderRightColor' :'transparent'}\r\n];\r\n\r\n\r\n$('#a').click(function() {$('.border').trigger(\"click\");});\r\n(function($) {\r\n var duration = 1000\r\n $('.border').click(function() {\r\n for ( var i=0; i < transforms.length; i++ ) {\r\n $(this)\r\n .animate(transforms[i], duration)\r\n }\r\n }).end()\r\n}(jQuery))\n.border {\r\n margin: 20px 50px;\r\n width: 50px;\r\n height: 50px;\r\n border-width: 50px;\r\n border-style: solid;\r\n border-top-color: green;\r\n border-right-color: yellow;\r\n border-bottom-color: red;\r\n border-left-color: blue;\r\n cursor: pointer\r\n}\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></script>\r\n<script src=\"https://code.jquery.com/color/jquery.color-2.1.2.min.js\"></script>\r\nClick it!<br>\r\n<div class=\"border\"></div>\n\n\n\n\nRandom version\n\n\n/**\r\n * Randomize array element order in-place.\r\n * Using Durstenfeld shuffle algorithm.\r\n */\r\nfunction shuffleArray(array) {\r\n for (var i = array.length - 1; i > 0; i--) {\r\n var j = Math.floor(Math.random() * (i + 1));\r\n var temp = array[i];\r\n array[i] = array[j];\r\n array[j] = temp;\r\n }\r\n return array;\r\n}\r\n\r\ntransforms = [\r\n {'border-left-width' :'30', 'margin-left': '70'},\r\n {'border-bottom-width' :'80'},\r\n {'border-right-width' :'30'},\r\n {'border-top-width' :'0', 'margin-top': '70'},\r\n {'width' :'0'},\r\n {'height' :'0'},\r\n {'borderLeftColor' :'transparent'},\r\n {'borderRightColor' :'transparent'}\r\n];\r\ntransforms = shuffleArray(transforms)\r\n\r\n\r\n\r\n$('#a').click(function() {$('.border').trigger(\"click\");});\r\n(function($) {\r\n var duration = 1000\r\n $('.border').click(function() {\r\n for ( var i=0; i < transforms.length; i++ ) {\r\n $(this)\r\n .animate(transforms[i], duration)\r\n }\r\n }).end()\r\n}(jQuery))\n.border {\r\n margin: 50px;\r\n width: 50px;\r\n height: 50px;\r\n border-width: 50px;\r\n border-style: solid;\r\n border-top-color: green;\r\n border-right-color: yellow;\r\n border-bottom-color: red;\r\n border-left-color: blue;\r\n cursor: pointer\r\n}\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></script>\r\n<script src=\"https://code.jquery.com/color/jquery.color-2.1.2.min.js\"></script>\r\nClick it!<br>\r\n<div class=\"border\"></div>\n\n\n\n\nAll at once version\n\n\n$('#a').click(function() {$('.border').trigger(\"click\");});\r\n(function($) {\r\n var duration = 1000\r\n $('.border').click(function() {\r\n $(this)\r\n .animate({'border-top-width': 0 ,\r\n 'border-left-width': 30 ,\r\n 'border-right-width': 30 ,\r\n 'border-bottom-width': 80 ,\r\n 'width': 0 ,\r\n 'height': 0 ,\r\n 'margin-left': 100,\r\n 'margin-top': 150,\r\n 'borderTopColor': 'transparent',\r\n 'borderRightColor': 'transparent',\r\n 'borderLeftColor': 'transparent'}, duration)\r\n }).end()\r\n}(jQuery))\n.border {\r\n margin: 50px;\r\n width: 50px;\r\n height: 50px;\r\n border-width: 50px;\r\n border-style: solid;\r\n border-top-color: green;\r\n border-right-color: yellow;\r\n border-bottom-color: red;\r\n border-left-color: blue;\r\n cursor: pointer\r\n}\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js\"></script>\r\n<script src=\"https://code.jquery.com/color/jquery.color-2.1.2.min.js\"></script>\r\nClick it!<br>\r\n<div class=\"border\"></div>\n\n\n\n",
"Lets say we have the following div:\n<div id=\"triangle\" />\n\nNow Edit the CSS step-by-step, so you will get clear idea what is happening around\nSTEP 1:\nJSfiddle Link:\n #triangle {\n background: purple;\n width :150px;\n height:150PX;\n border-left: 50px solid black ;\n border-right: 50px solid black;\n border-bottom: 50px solid black;\n border-top: 50px solid black;\n }\n\nThis is a simple div. With a very simple CSS. So a layman can understand. Div has dimensions 150 x 150 pixels with the border 50 pixels. The image is attached:\n\nSTEP 2: JSfiddle Link:\n#triangle {\n background: purple;\n width :150px;\n height:150PX;\n border-left: 50px solid yellow ;\n border-right: 50px solid green;\n border-bottom: 50px solid red;\n border-top: 50px solid blue;\n}\n\nNow I just changed the border-color of all 4 sides. The image is attached.\n\nSTEP:3 JSfiddle Link:\n#triangle {\n background: purple;\n width :0;\n height:0;\n border-left: 50px solid yellow ;\n border-right: 50px solid green;\n border-bottom: 50px solid red;\n border-top: 50px solid blue;\n}\n\nNow I just changed the height & width of div from 150 pixels to zero. The image is attached \n\nSTEP 4: JSfiddle:\n#triangle {\n background: purple;\n width :0px;\n height:0px;\n border-left: 50px solid transparent;\n border-right: 50px solid transparent;\n border-bottom: 50px solid red;\n border-top: 50px solid transparent;\n}\n\nNow I have made all the borders transparent apart from the bottom border. The image is attached below.\n\nSTEP 5: JSfiddle Link:\n#triangle {\n background: white;\n width :0px;\n height:0px;\n border-left: 50px solid transparent;\n border-right: 50px solid transparent;\n border-bottom: 50px solid red;\n border-top: 50px solid transparent;\n}\n\nNow I just changed the background color to white. The image is attached.\n\nHence we got the triangle we needed.\n",
"And now something completely different...\nInstead of using css tricks don't forget about solutions as simple as html entities:\n▲\n\nResult:\n▲\nSee: What are the HTML entities for up and down triangles?\n",
"Consider the below triangle\n.triangle {\n border-bottom:15px solid #000;\n border-left:10px solid transparent;\n border-right:10px solid transparent;\n width:0;\n height:0;\n}\n\nThis is what we are given:\n\nWhy it came out in this shape? The below diagram explains the dimensions, note that 15px was used for the bottom border and 10px was used for left and right.\n\nIt's pretty easy to make a right-angle triangle also by removing the right border.\n\n",
"Taking it one step further, using css based on this I added arrows to my back and next buttons (yes I know its not 100% cross-browser, but slick none the less).\n\n\n.triangle {\r\n width: 0;\r\n height: 0;\r\n border-left: 50px solid transparent;\r\n border-right: 50px solid transparent;\r\n border-bottom: 100px solid red;\r\n margin:20px auto;\r\n}\r\n\r\n.triangle-down {\r\n border-bottom:none;\r\n border-top: 100px solid red;\r\n}\r\n\r\n.triangle-left {\r\n border-left:none;\r\n border-right: 100px solid red;\r\n border-bottom: 50px solid transparent;\r\n border-top: 50px solid transparent;\r\n}\r\n\r\n.triangle-right {\r\n border-right:none;\r\n border-left: 100px solid red;\r\n border-bottom: 50px solid transparent;\r\n border-top: 50px solid transparent;\r\n}\r\n\r\n.triangle-after:after {\r\n width: 0;\r\n height: 0;\r\n border-left: 5px solid transparent;\r\n border-right: 5px solid transparent;\r\n border-bottom: 5px solid red;\r\n margin:0 5px;\r\n content:\"\";\r\n display:inline-block;\r\n}\r\n\r\n.triangle-after-right:after {\r\n border-right:none;\r\n border-left: 5px solid blue;\r\n border-bottom: 5px solid transparent;\r\n border-top: 5px solid transparent;\r\n\r\n}\r\n\r\n.triangle-before:before {\r\n width: 0;\r\n height: 0;\r\n border-left: 5px solid transparent;\r\n border-right: 5px solid transparent;\r\n border-bottom: 5px solid blue;\r\n margin:0 5px;\r\n content:\"\";\r\n display:inline-block;\r\n}\r\n\r\n.triangle-before-left:before {\r\n border-left:none;\r\n border-right: 5px solid blue;\r\n border-bottom: 5px solid transparent;\r\n border-top: 5px solid transparent;\r\n\r\n}\n<div class=\"triangle\"></div>\r\n<div class=\"triangle triangle-down\"></div>\r\n<div class=\"triangle triangle-left\"></div>\r\n<div class=\"triangle triangle-right\"></div>\r\n\r\n<a class=\"triangle-before triangle-before-left\" href=\"#\">Back</a>\r\n<a class=\"triangle-after triangle-after-right\" href=\"#\">Next</a>\n\n\n\n",
"Different approach. With linear gradient (for IE, only IE 10+).\nYou can use any angle:\n\n\n.triangle {\r\n margin: 50px auto;\r\n width: 100px;\r\n height: 100px;\r\n/* linear gradient */\r\n background: -moz-linear-gradient(-45deg, rgba(255,0,0,0) 0%, rgba(255,0,0,0) 50%, rgba(255,0,0,1) 50%, rgba(255,0,0,1) 100%);\r\n /* FF3.6+ */\r\n background: -webkit-gradient(linear, left top, right bottom, color-stop(0%,rgba(255,0,0,0)), color-stop(50%,rgba(255,0,0,0)), color-stop(50%,rgba(255,0,0,1)), color-stop(100%,rgba(255,0,0,1)));\r\n /* Chrome,Safari4+ */\r\n background: -webkit-linear-gradient(-45deg, rgba(255,0,0,0) 0%,rgba(255,0,0,0) 50%,rgba(255,0,0,1) 50%,rgba(255,0,0,1) 100%);\r\n /* Chrome10+,Safari5.1+ */\r\n background: -o-linear-gradient(-45deg, rgba(255,0,0,0) 0%,rgba(255,0,0,0) 50%,rgba(255,0,0,1) 50%,rgba(255,0,0,1) 100%);\r\n /* Opera 11.10+ */\r\n background: -ms-linear-gradient(-45deg, rgba(255,0,0,0) 0%,rgba(255,0,0,0) 50%,rgba(255,0,0,1) 50%,rgba(255,0,0,1) 100%);\r\n /* IE10+ */\r\n background: linear-gradient(135deg, rgba(255,0,0,0) 0%,rgba(255,0,0,0) 50%,rgba(255,0,0,1) 50%,rgba(255,0,0,1) 100%);\r\n /* W3C */;\r\n}\n<div class=\"triangle\"></div>\n\n\n\nHere is jsfiddle\n",
"CSS clip-path\nThis is something I feel this question has missed; clip-path\n\nclip-path in a nutshell\nClipping, with the clip-path property, is akin to cutting a shape (like a circle or a pentagon) from a rectangular piece of paper. The property belongs to the “CSS Masking Module Level 1” specification. The spec states, “CSS masking provides two means for partially or fully hiding portions of visual elements: masking and clipping”.\n\nExtract from Smashing Magazine\n\n\n\nclip-path will use the element itself rather than its borders to cut the shape you specify in its parameters. It uses a super simple percentage based co-ordinate system which makes editing it very easy and means you can pick it up and create weird and wonderful shapes in a matter of minutes.\n\nTriangle Shape Example\n\n\ndiv {\r\n -webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);\r\n clip-path: polygon(50% 0%, 0% 100%, 100% 100%);\r\n background: red;\r\n width: 100px;\r\n height: 100px;\r\n}\n<div></div>\n\n\n\n\nDownside\nIt does have a major downside at the moment, one being it's major lack of support, only really being covered within -webkit- browsers and having no support on IE and only very partial in FireFox.\n\nResources\nHere are some useful resources and material to help better understand clip-path and also start creating your own.\n\nClippy - A clip-path generator\nThe W3C Candidate Recommendation File\nMDN clip-path documentation\nclip-path Browser Support \n\n",
"OK, this triangle will get created because of the way that borders of the elements work together in HTML and CSS... \nAs we usually use 1 or 2px borders, we never notice that borders make a 45° angles to each others with the same width and if the width changes, the angle degree get changed as well, run the CSS code I created below:\n\n\n.triangle {\r\n width: 100px;\r\n height: 100px;\r\n border-left: 50px solid black;\r\n border-right: 50px solid black;\r\n border-bottom: 100px solid red;\r\n}\n<div class=\"triangle\">\r\n</div>\n\n\n\nThen in the next step, we don't have any width or height, something like this:\n\n\n.triangle {\r\n width: 0;\r\n height: 0;\r\n border-left: 50px solid black;\r\n border-right: 50px solid black;\r\n border-bottom: 100px solid red;\r\n}\n<div class=\"triangle\">\r\n</div>\n\n\n\nAnd now we make the left and right borders invisible to make our desirable triangle as below:\n\n\n.triangle {\r\n width: 0;\r\n height: 0;\r\n border-left: 50px solid transparent;\r\n border-right: 50px solid transparent;\r\n border-bottom: 100px solid red;\r\n}\n<div class=\"triangle\"></div>\n\n\n\nIf you not willing to run the snippet to see the steps, I've created an image sequence to have a look at all steps in one image:\n\n",
"This is an old question, but I think will worth it to share how to create an arrow using this triangle technique.\nStep 1:\nLets create 2 triangles, for the second one we will use the :after pseudo class and position it just below the other:\n\n\n\n.arrow{\n width: 0;\n height: 0;\n border-radius: 50px;\n display: inline-block;\n position: relative;\n}\n\n .arrow:after{\n content: \"\";\n width: 0;\n height: 0;\n position: absolute;\n }\n\n\n.arrow-up{\n border-left: 50px solid transparent;\n border-right: 50px solid transparent;\n border-bottom: 50px solid #333;\n}\n .arrow-up:after{\n top: 5px;\n border-left: 50px solid transparent;\n border-right: 50px solid transparent;\n border-bottom: 50px solid #ccc;\n right: -50px;\n }\n<div class=\"arrow arrow-up\"> </div>\n\n\n\nStep 2\nNow we just have to set the predominant border color of the second triangle to the same color of the background:\n\n\n\n.arrow{\n width: 0;\n height: 0;\n border-radius: 50px;\n display: inline-block;\n position: relative;\n}\n\n .arrow:after{\n content: \"\";\n width: 0;\n height: 0;\n position: absolute;\n }\n\n\n.arrow-up{\n border-left: 50px solid transparent;\n border-right: 50px solid transparent;\n border-bottom: 50px solid #333;\n}\n .arrow-up:after{\n top: 5px;\n border-left: 50px solid transparent;\n border-right: 50px solid transparent;\n border-bottom: 50px solid #fff;\n right: -50px;\n }\n<div class=\"arrow arrow-up\"> </div>\n\n\n\nFiddle with all the arrows:\nhttp://jsfiddle.net/tomsarduy/r0zksgeu/\n",
"If you want to apply border to the triangle read this: Create a triangle with CSS?\n\nAlmost all the answers focus on the triangle built using border so I am going to elaborate the linear-gradient method (as started in the answer of @lima_fil).\nUsing a degree value like 45° will force us to respect a specific ratio of height/width in order to obtain the triangle we want and this won't be responsive:\n\n\n.tri {\r\n width:100px;\r\n height:100px;\r\n background:linear-gradient(45deg, transparent 49.5%,red 50%);\r\n \r\n /*To illustrate*/\r\n border:1px solid;\r\n}\nGood one\r\n<div class=\"tri\"></div>\r\nbad one\r\n<div class=\"tri\" style=\"width:150px\"></div>\r\nbad one\r\n<div class=\"tri\" style=\"height:30px\"></div>\n\n\n\nInstead of doing this we should consider predefined values of direction like to bottom, to top, etc. In this case we can obtain any kind of triangle shape while keeping it responsive.\n1) Rectangle triangle\nTo obtain such triangle we need one linear-gradient and a diagonal direction like to bottom right, to top left, to bottom left, etc\n\n\n.tri-1,.tri-2 {\r\n display:inline-block;\r\n width:100px;\r\n height:100px;\r\n background:linear-gradient(to bottom left, transparent 49.5%,red 50%);\r\n border:1px solid;\r\n animation:change 2s linear infinite alternate;\r\n}\r\n.tri-2 {\r\n background:linear-gradient(to top right, transparent 49.5%,red 50%);\r\n border:none;\r\n}\r\n\r\n@keyframes change {\r\n from {\r\n width:100px;\r\n height:100px;\r\n }\r\n to {\r\n height:50px;\r\n width:180px;\r\n }\r\n}\n<div class=\"tri-1\"></div>\r\n<div class=\"tri-2\"></div>\n\n\n\n2) isosceles triangle\nFor this one we will need 2 linear-gradient like above and each one will take half the width (or the height). It's like we create a mirror image of the first triangle.\n\n\n.tri {\r\n display:inline-block;\r\n width:100px;\r\n height:100px;\r\n background-image:\r\n linear-gradient(to bottom right, transparent 49.5%,red 50%),\r\n linear-gradient(to bottom left, transparent 49.5%,red 50%);\r\n background-size:50.3% 100%; /* I use a value slightly bigger than 50% to avoid having a small gap between both gradient*/\r\n background-position:left,right;\r\n background-repeat:no-repeat;\r\n \r\n animation:change 2s linear infinite alternate;\r\n}\r\n\r\n\r\n@keyframes change {\r\n from {\r\n width:100px;\r\n height:100px;\r\n }\r\n to {\r\n height:50px;\r\n width:180px;\r\n }\r\n}\n<div class=\"tri\"></div>\n\n\n\n3) equilateral triangle\nThis one is a bit tricky to handle as we need to keep a relation between the height and width of the gradient. We will have the same triangle as above but we will make the calculation more complex in order to transform the isosceles triangle to an equilateral one.\nTo make it easy, we will consider that the width of our div is known and the height is big enough to be able to draw our triangle inside (height >= width).\n\nWe have our two gradient g1 and g2, the blue line is the width of the div w and each gradient will have 50% of it (w/2) and each side of the triangle sould be equal to w. The green line is the height of both gradient hg and we can easily obtain the formula below:\n(w/2)² + hg² = w² ---> hg = (sqrt(3)/2) * w ---> hg = 0.866 * w\nWe can rely on calc() in order to do our calculation and to obtain the needed result:\n\n\n.tri {\r\n --w:100px;\r\n width:var(--w);\r\n height:100px;\r\n display:inline-block;\r\n background-image:\r\n linear-gradient(to bottom right, transparent 49.5%,red 50%),\r\n linear-gradient(to bottom left, transparent 49.5%,red 50%);\r\n background-size:calc(var(--w)/2 + 0.5px) calc(0.866 * var(--w));\r\n background-position:\r\n left bottom,right bottom;\r\n background-repeat:no-repeat;\r\n \r\n}\n<div class=\"tri\"></div>\r\n<div class=\"tri\" style=\"--w:80px\"></div>\r\n<div class=\"tri\" style=\"--w:50px\"></div>\n\n\n\nAnother way is to control the height of div and keep the syntax of gradient easy:\n\n\n.tri {\r\n --w:100px;\r\n width:var(--w);\r\n height:calc(0.866 * var(--w));\r\n display:inline-block;\r\n background:\r\n linear-gradient(to bottom right, transparent 49.8%,red 50%) left,\r\n linear-gradient(to bottom left, transparent 49.8%,red 50%) right;\r\n background-size:50.2% 100%;\r\n background-repeat:no-repeat;\r\n \r\n}\n<div class=\"tri\"></div>\r\n<div class=\"tri\" style=\"--w:80px\"></div>\r\n<div class=\"tri\" style=\"--w:50px\"></div>\n\n\n\n4) Random triangle\nTo obtain a random triangle, it's easy as we simply need to remove the condition of 50% of each one BUT we should keep two condition (both should have the same height and the sum of both width should be 100%).\n\n\n.tri-1 {\r\n width:100px;\r\n height:100px;\r\n display:inline-block;\r\n background-image:\r\n linear-gradient(to bottom right, transparent 50%,red 0),\r\n linear-gradient(to bottom left, transparent 50%,red 0);\r\n background-size:20% 60%,80% 60%;\r\n background-position:\r\n left bottom,right bottom;\r\n background-repeat:no-repeat;\r\n \r\n \r\n}\n<div class=\"tri-1\"></div>\n\n\n\nBut what if we want to define a value for each side? We simply need to do calculation again!\n\nLet's define hg1 and hg2 as the height of our gradient (both are equal to the red line) then wg1 and wg2 as the width of our gradient (wg1 + wg2 = a). I will not going to detail the calculation but at then end we will have:\nwg2 = (a²+c²-b²)/(2a)\nwg1 = a - wg2\nhg1 = hg2 = sqrt(b² - wg1²) = sqrt(c² - wg2²)\n\nNow we have reached the limit of CSS as even with calc() we won't be able to implement this so we simply need to gather the final result manually and use them as fixed size:\n\n\n.tri {\r\n --wg1: 20px; \r\n --wg2: 60px;\r\n --hg:30px; \r\n width:calc(var(--wg1) + var(--wg2));\r\n height:100px;\r\n display:inline-block;\r\n background-image:\r\n linear-gradient(to bottom right, transparent 49.5%,red 50%),\r\n linear-gradient(to bottom left, transparent 49.5%,red 50%);\r\n\r\n background-size:var(--wg1) var(--hg),var(--wg2) var(--hg);\r\n background-position:\r\n left bottom,right bottom;\r\n background-repeat:no-repeat;\r\n \r\n}\n<div class=\"tri\" ></div>\r\n\r\n<div class=\"tri\" style=\"--wg1:80px;--wg2:60px;--hg:100px;\" ></div>\n\n\n\nBonus\nWe should not forget that we can also apply rotation and/or skew and we have more option to obtain more triangle:\n\n\n.tri {\r\n --wg1: 20px; \r\n --wg2: 60px;\r\n --hg:30px; \r\n width:calc(var(--wg1) + var(--wg2) - 0.5px);\r\n height:100px;\r\n display:inline-block;\r\n background-image:\r\n linear-gradient(to bottom right, transparent 49%,red 50%),\r\n linear-gradient(to bottom left, transparent 49%,red 50%);\r\n\r\n background-size:var(--wg1) var(--hg),var(--wg2) var(--hg);\r\n background-position:\r\n left bottom,right bottom;\r\n background-repeat:no-repeat;\r\n \r\n}\n<div class=\"tri\" ></div>\r\n\r\n<div class=\"tri\" style=\"transform:skewY(25deg)\"></div>\r\n\r\n<div class=\"tri\" style=\"--wg1:80px;--wg2:60px;--hg:100px;\" ></div>\r\n\r\n\r\n<div class=\"tri\" style=\"--wg1:80px;--wg2:60px;--hg:100px;transform:rotate(20deg)\" ></div>\n\n\n\nAnd of course we should keep in mind the SVG solution which can be more suitable in some situation:\n\n\nsvg {\r\n width:100px;\r\n height:100px;\r\n}\r\n\r\npolygon {\r\n fill:red;\r\n}\n<svg viewBox=\"0 0 100 100\"><polygon points=\"0,100 0,0 100,100\" /></svg>\r\n<svg viewBox=\"0 0 100 100\"><polygon points=\"0,100 50,0 100,100\" /></svg>\r\n<svg viewBox=\"0 0 100 100\"><polygon points=\"0,100 50,23 100,100\" /></svg>\r\n<svg viewBox=\"0 0 100 100\"><polygon points=\"20,60 50,43 80,100\" /></svg>\n\n\n\n",
"SASS (SCSS) triangle mixin\nI wrote this to make it easier (and DRY) to automatically generate a CSS triangle:\n// Triangle helper mixin (by Yair Even-Or)\n// @param {Direction} $direction - either `top`, `right`, `bottom` or `left`\n// @param {Color} $color [currentcolor] - Triangle color\n// @param {Length} $size [1em] - Triangle size\n@mixin triangle($direction, $color: currentcolor, $size: 1em) {\n $size: $size/2;\n $transparent: rgba($color, 0);\n $opposite: (top:bottom, right:left, left:right, bottom:top);\n\n content: '';\n display: inline-block;\n width: 0;\n height: 0;\n border: $size solid $transparent;\n border-#{map-get($opposite, $direction)}-color: $color;\n margin-#{$direction}: -$size;\n}\n\nuse-case example:\nspan {\n @include triangle(bottom, red, 10px);\n}\n\nPlayground page\n\nImportant note: if the triangle seems pixelated in some browsers, try one of the methods described here.\n",
"If you want to play around with border-size, width and height and see how those can create different shapes, try this:\n\n\nconst sizes = [32, 32, 32, 32];\r\nconst triangle = document.getElementById('triangle');\r\n\r\nfunction update({ target }) {\r\n let index = null;\r\n \r\n if (target) {\r\n index = parseInt(target.id);\r\n\r\n if (!isNaN(index)) {\r\n sizes[index] = target.value;\r\n }\r\n }\r\n \r\n window.requestAnimationFrame(() => {\r\n triangle.style.borderWidth = sizes.map(size => `${ size }px`).join(' ');\r\n \r\n if (isNaN(index)) {\r\n triangle.style[target.id] = `${ target.value }px`;\r\n }\r\n });\r\n}\r\n\r\ndocument.querySelectorAll('input').forEach(input => {\r\n input.oninput = update;\r\n});\r\n\r\nupdate({});\nbody {\r\n margin: 0;\r\n min-height: 100vh;\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n overflow: hidden;\r\n}\r\n\r\n#triangle {\r\n border-style: solid;\r\n border-color: yellow magenta blue black;\r\n background: cyan;\r\n height: 0px;\r\n width: 0px;\r\n}\r\n\r\n#controls {\r\n position: fixed;\r\n bottom: 0;\r\n left: 0;\r\n right: 0;\r\n background: white;\r\n display: flex;\r\n box-shadow: 0 0 32px rgba(0, 0, 0, .125);\r\n}\r\n\r\n#controls > div {\r\n position: relative;\r\n width: 25%;\r\n padding: 8px;\r\n box-sizing: border-box;\r\n display: flex;\r\n}\r\n\r\ninput {\r\n margin: 0;\r\n width: 100%;\r\n position: relative;\r\n}\n<div id=\"triangle\" style=\"border-width: 32px 32px 32px 32px;\"></div>\r\n\r\n<div id=\"controls\">\r\n <div><input type=\"range\" min=\"0\" max=\"128\" value=\"32\" id=\"0\" /></div>\r\n <div><input type=\"range\" min=\"0\" max=\"128\" value=\"32\" id=\"1\" /></div>\r\n <div><input type=\"range\" min=\"0\" max=\"128\" value=\"32\" id=\"2\" /></div>\r\n <div><input type=\"range\" min=\"0\" max=\"128\" value=\"32\" id=\"3\" /></div>\r\n <div><input type=\"range\" min=\"0\" max=\"128\" value=\"0\" id=\"width\" /></div>\r\n <div><input type=\"range\" min=\"0\" max=\"128\" value=\"0\" id=\"height\" /></div>\r\n</div>\n\n\n\n",
"here is another fiddle: \n.container:after {\n position: absolute;\n right: 0;\n content: \"\";\n margin-right:-50px;\n margin-bottom: -8px;\n border-width: 25px;\n border-style: solid;\n border-color: transparent transparent transparent #000;\n width: 0;\n height: 0;\n z-index: 10;\n -webkit-transition: visibility 50ms ease-in-out,opacity 50ms ease-in-out;\n transition: visibility 50ms ease-in-out,opacity 50ms ease-in-out;\n bottom: 21px;\n}\n.container {\n float: left;\n margin-top: 100px;\n position: relative;\n width: 150px;\n height: 80px;\n background-color: #000;\n}\n\n.containerRed {\n float: left;\n margin-top: 100px;\n position: relative;\n width: 100px;\n height: 80px;\n background-color: red;\n}\n\nhttps://jsfiddle.net/qdhvdb17/\n",
"Others have already explained this well. Let me give you an animation which will explain this quickly: http://codepen.io/chriscoyier/pen/lotjh\nHere is some code for you to play with and learn the concepts.\nHTML:\n<html>\n <body>\n <div id=\"border-demo\">\n </div>\n </body>\n</html>\n\nCSS:\n/*border-width is border thickness*/\n#border-demo {\n background: gray;\n border-color: yellow blue red green;/*top right bottom left*/\n border-style: solid;\n border-width: 25px 25px 25px 25px;/*top right bottom left*/\n height: 50px;\n width: 50px;\n}\n\nPlay with this and see what happens. Set height and width to zero. Then remove top border and make left and right transparent, or just look at the code below to make a css triangle:\n#border-demo {\n border-left: 50px solid transparent;\n border-right: 50px solid transparent;\n border-bottom: 100px solid blue;\n}\n\n",
"I know this is an old one, but I'd like to add to this discussion that There are at least 5 different methods for creating a triangle using HTML & CSS alone.\n\nUsing borders \nUsing linear-gradient \nUsing conic-gradient \nUsing\ntransform and overflow \nUsing clip-path\n\nI think that all have been covered here except for method 3, using the conic-gradient, so I will share it here:\n\n\n.triangle{\r\n width: 40px;\r\n height: 40px;\r\n background: conic-gradient(at 50% 50%,transparent 135deg,green 0,green 225deg, transparent 0);\r\n }\n<div class=\"triangle\"></div>\n\n\n\n\n",
"use clip-path: polygon(50% 0%, 100% 100%, 0% 100%); for creating easy to Triangle\n<div class=\"triangle\"></div>\n\n.triangle{width:200px; height:200px;background:#000;clip-path: polygon(50% 0%, 100% 100%, 0% 100%);}\n\n",
"After reading through the other answers here I see there are great explanations as to why the CSS triangle works the way it does. I would consider it to be somewhat of a trick, versus something that you could apply generically.\nFor something that's easier to read and maintain, I would recommend you define your geometry in SVG.\nThen you can convert that SVG using data uri by adding the data:image/svg+xml, prefix. As a data uri, it can now be used as a background-image in a CSS. Because the SVG is in clear text, you can readily make updates to the geometry, stroke, and fill color.\n\n\ndiv.tri {\n width: 100px;\n height: 100px;\n display: inline-block;\n background-image: url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 32 32\"><path fill=\"red\" d=\"M31.345 29H1.655L16.5 1.96z\"/></svg>');\n}\n<div>\n <div class=\"tri\"></div>\n <div class=\"tri\"></div>\n <div class=\"tri\"></div>\n</div>\n\n\n\n"
] |
[
2356,
554,
529,
299,
192,
52,
39,
34,
28,
19,
19,
18,
12,
11,
8,
5,
3,
3,
1,
1,
0
] |
[
"Try This:-\n\n\n.triangle {\r\n border-color: transparent transparent red transparent;\r\n border-style: solid;\r\n border-width: 0px 200px 200px 200px;\r\n height: 0px;\r\n width: 0px;\r\n}\n<div class=\"triangle\"></div>\n\n\n\n",
"clip-path has the best result for me - works great for divs/containers with and without fixed dimensions:\n.triangleContainer{\n position: relative;\n width: 500px;\n height: 500px;\n}\n\n.triangleContainer::before{\n content: \"\"; \n position: absolute;\n background:blue;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n clip-path: polygon(50% 0, 0 100%, 100% 100%);\n}\n\n"
] |
[
-1,
-2
] |
[
"css",
"css_shapes",
"geometry",
"polygon"
] |
stackoverflow_0007073484_css_css_shapes_geometry_polygon.txt
|
Q:
Why can't I use "this" in my Android Studio plug-in for Unity?
I'm doing a plug-in on android studio for unity, I want to do text recognition to an image and send a string of the text detected to unity
I have the plugin in the unity project and can send and receive information normally, I want to use the google vision library, but the problem is the class TextRecognizer that I'm using, when it's built it asks for a "context", the guide says you have to use "this" but it seems that the whole plug-in structure doesn't go with it, I don't know what to do anymore
The problem description is: 'Builder(android.content.Context)' in 'com.google.android.gms.vision.text.TextRecognizer.Builder' cannot be applied to '(com.cwgtech.unity.MyPlugin)'
The name of the project comes from the youtube tutorial I was following to create the plug-in
I've followed the Android-Studio recommended action of making my plug-in class extend android.content.context, but it creates a lot of other functions on the top of my code that I don't understand, and all of them have this error: Must be one of: PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_DENIED
A:
The problem is that the Google Vision library requires an Android Context object in order to be used. Unfortunately, your Unity Android plugin doesn't provide an Android Context object. You can try creating an Android Context object within your plugin and passing it to the Google Vision library, but this may not work. Alternatively, you could look into using the Google Mobile Vision library which doesn't require an Android Context object.
|
Why can't I use "this" in my Android Studio plug-in for Unity?
|
I'm doing a plug-in on android studio for unity, I want to do text recognition to an image and send a string of the text detected to unity
I have the plugin in the unity project and can send and receive information normally, I want to use the google vision library, but the problem is the class TextRecognizer that I'm using, when it's built it asks for a "context", the guide says you have to use "this" but it seems that the whole plug-in structure doesn't go with it, I don't know what to do anymore
The problem description is: 'Builder(android.content.Context)' in 'com.google.android.gms.vision.text.TextRecognizer.Builder' cannot be applied to '(com.cwgtech.unity.MyPlugin)'
The name of the project comes from the youtube tutorial I was following to create the plug-in
I've followed the Android-Studio recommended action of making my plug-in class extend android.content.context, but it creates a lot of other functions on the top of my code that I don't understand, and all of them have this error: Must be one of: PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_DENIED
|
[
"The problem is that the Google Vision library requires an Android Context object in order to be used. Unfortunately, your Unity Android plugin doesn't provide an Android Context object. You can try creating an Android Context object within your plugin and passing it to the Google Vision library, but this may not work. Alternatively, you could look into using the Google Mobile Vision library which doesn't require an Android Context object.\n"
] |
[
0
] |
[] |
[] |
[
"android",
"android_gradle_plugin",
"java"
] |
stackoverflow_0074662181_android_android_gradle_plugin_java.txt
|
Q:
Insert multiple data into different tables in a single transaction
This has nothing to do with Frameworks because it is an external project, I am currently developing to learn, some things about database management or how databases behave...
I need help with some php and PDO... Previously I dev this script:
<?php
class DataBaseManager
{
public function GetData($query, $user, $pass)
{
try {
$db_result = [];
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8");
reset($query);
$db_name = key($query);
$conn->exec('USE ' . $db_name);
$db_result['r'] = $conn->query($query[$db_name], PDO::FETCH_ASSOC);
$count = $db_result['r']->rowCount();
$db_result['c'] = $count;
if (0 == $count) {
$db_result['r'] = null;
} elseif (1 == $count) {
$db_result['r'] = $db_result['r']->fetch();
}
return $db_result;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
public function DeleteData($query, $user, $pass)
{
try {
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("set names utf8");
foreach ($query as $db_name => $query_arr) {
$conn->exec('USE ' . $db_name);
foreach ($query_arr as $key => $query_string) {
$conn->exec($query_string);
++$ct;
}
}
$conn->commit();
$conn = null;
return '<b>' . $ct . ' Records Deleted Successfully.</b>';
} catch (PDOException $e) {
$conn->rollback();
echo $e->getMessage();
return false;
}
}
public function SetData($query, $user, $pass)
{
try {
$db_result = [];
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("set names utf8");
$count = ['u' => 0, 'i' => 0];
foreach ($query as $db_name => $query_arr) {
$conn->exec('USE ' . $db_name);
foreach ($query_arr as $key => $query_string) {
$cq = $conn->exec($query_string);
if (strpos($query_string, 'UPDATE') !== false) {
$count['u'] += $cq;
}
if (strpos($query_string, 'INSERT') !== false) {
$count['i'] += $cq;
}
}
}
$conn->commit();
$db_result['r'] = true;
$db_result['t'] = 'Updates: ' . $count['u'] . ', Inserts: ' . $count['i'];
return $db_result;
} catch (PDOException $e) {
$conn->rollback();
echo $e->getMessage();
return false;
}
}
}
I would like to be able to insert data by volumes in multiple tables in a single commit...
The idea of doing it that way is because if something fails I want it to be automatically rolled back in all table instances...
So I have a data structure in an array with the following content in my new class:
$dbquery =[
'test'=>[
'0' =>[
0 => 'INSERT INTO table_name_1(column1,column2) VALUES (?,?)', //mean it is the query
1 =>[value11,value12], // mean it is a row
2 =>[value21,value22], // mean it is a row
],
'1' =>[
0 => 'INSERT INTO table_name_2(column1,column2,column3,column4) VALUES (?,?,?,?)', //mean it is the query
1 =>[value11,value12,value13,value14], // mean it is a row
2 =>[value21,value22,value23,value24], // mean it is a row
],
],
];
but i have my first try with bindValue, this is my new class mentioned:
<?php
class DataBase
{
private static ?DataBase $instance = null;
public static function getInstance(): DataBase
{
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
private array $config;
public function __construct()
{
$this->config = ['DB_HOST'=>'test','DB_NAME'=>'test','DB_USER'=>'test','DB_PASSWORD'=>''];
$this->setConnection(new PDO("mysql:host=" . $this->config['DB_HOST'] . ";dbname=" . $this->config['DB_NAME'], $this->config['DB_USER'], $this->config['DB_PASSWORD']));
}
private PDO $connection;
/**
* @return PDO
*/
private function getConnection(): PDO
{
return $this->connection;
}
/**
* @param PDO $connection
*/
private function setConnection(PDO $connection): void
{
$this->connection = $connection;
}
public function changeConnectionServer(string $host, string $db_name, string $user, string $password): void
{
$this->setConnection(new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $user, $password));
}
private array $query;
public function setDataBaseTarget(string $db_name)
{
if (empty($this->query)) {
$this->query = [];
}
$this->query[$db_name] = [];
}
public function buildQuery(string $query)
{
if (empty($this->query)) {
$this->query = [];
$this->query[$this->config['DB_NAME']] = [];
}
$target = array_key_last($this->query);
$this->query[$target][] = [$query];
}
public function addQueryData($data)
{
$target = array_key_last($this->query);
$key = array_key_last($this->query[$target]);
$this->query[$target][$key][] = $data;
}
private function getQuery(): array
{
return $this->query;
}
/**
* @throws Exception
*/
public function setData(): array
{
try {
$time = -microtime(true);
$con = $this->getConnection();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->beginTransaction();
$con->exec("set names utf8;");
foreach ($this->getQuery() as $db_name => $query_arr) {
$con->exec('USE `' . $db_name . '`;');
$ct = 0;
// on this section have proble with code and logic .... i dont know what i need to dev to insert the data
foreach ($query_arr as $query_structure) {
foreach ($query_structure as $key => $raw) {
if ($key === 0) {
$ct++;
$stmt[$ct] = $con->prepare($raw);
} else {
if (is_array($raw)) {
$c = 0;
foreach ($raw as $value) {
$c++;
$stmt[$ct]->bindValue($c, $value, $this->getParamType($value));
}
}
}
}
$stmt[$ct]->execute();
}
//end section
}
//$con->commit();
return true;
} catch (PDOException $e) {
$con->rollback();
echo $e->getMessage();
return false;
}
}
private function getParamType($value)
{
if (is_int($value)) {
return PDO::PARAM_INT;
} elseif (is_bool($value)) {
return PDO::PARAM_BOOL;
} elseif (is_null($value)) {
return PDO::PARAM_NULL;
} elseif (is_string($value)) {
return PDO::PARAM_STR;
} else {
return false;
}
}
}
$db_handler = DataBase::getInstance();
$db_handler->buildQuery("INSERT INTO `client_list`(`email`,`mobile`) VALUES ('?','?');");
$db_handler->addQueryData(['[email protected]', '35634634636546']);
$db_handler->addQueryData(['[email protected]', '35634634636546']);
$db_handler->addQueryData(['[email protected]', '35634634636546']);
$db_handler->setData();
I can't figure out, develop the part that allows me to package everything in a single transaction... what I have is a stm[] ...
Can someone help me with this development?
A:
I can't make heads or tails of all the things your class is doing, but here's a generalized version according to the bits that seem obvious:
public function runMultipleQueries() {
$dbh = $this->getConnection();
// ... setup stuff
$dbh->beginTransaction();
try {
foreach($this->queries as $query) {
$stmt->prepare($query->queryString);
$param_id = 1;
foreach($query->params as $param) {
$stmt->bindValue($param_id++, $param);
}
$stmt->execute();
}
} catch( \Exception $e ) {
$dbh->rollback();
throw $e;
// IMO if you cannot fully/meaningfully recover, just re-throw and let it kill execution or be caught elsewhere where it can be
// otherwise you're likely having to maintain a stack of if(foo() == false) { ... } wrappers
}
$dbh->commit();
}
Additionally, singleton DB classes have the drawbacks of both being limiting if you ever need a second DB handle, as well as boiling down to being global state, and subject to the same "spooky action at a distance" problems.
Consider using dependency inversion and feeding class dependencies in via constructor arguments, method dependencies via method arguments, etc. Eg:
interface MyWrapperInterface {
function setQueries(array $queries);
function runQueries();
}
class MyDbWrapper implements MyWrapperInterface {
protected $dbh;
public function __construct(\PDO $dbh) {
$this->dbh = $dbh;
}
public function setQueries(array $queries) { /* ... */ }
public function runQueries() { /* ... */ }
}
class MyOtherThing {
protected $db;
public function __construct( MyWrapperInterface $db ) {
$this->db = $db;
}
// ...
}
$wrapper1 = new MyDbWrapper(new PDO($connstr1, $options));
$wrapper2 = new MyDbWrapper(new PDO($connstr2, $options));
$thing1 = new MyOtherThing($wrapper1);
$thing2 = new MyOtherThing($wrapper2);
$thing1_2 = new MyOtherThing($wrapper1);
// etc
|
Insert multiple data into different tables in a single transaction
|
This has nothing to do with Frameworks because it is an external project, I am currently developing to learn, some things about database management or how databases behave...
I need help with some php and PDO... Previously I dev this script:
<?php
class DataBaseManager
{
public function GetData($query, $user, $pass)
{
try {
$db_result = [];
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8");
reset($query);
$db_name = key($query);
$conn->exec('USE ' . $db_name);
$db_result['r'] = $conn->query($query[$db_name], PDO::FETCH_ASSOC);
$count = $db_result['r']->rowCount();
$db_result['c'] = $count;
if (0 == $count) {
$db_result['r'] = null;
} elseif (1 == $count) {
$db_result['r'] = $db_result['r']->fetch();
}
return $db_result;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
public function DeleteData($query, $user, $pass)
{
try {
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("set names utf8");
foreach ($query as $db_name => $query_arr) {
$conn->exec('USE ' . $db_name);
foreach ($query_arr as $key => $query_string) {
$conn->exec($query_string);
++$ct;
}
}
$conn->commit();
$conn = null;
return '<b>' . $ct . ' Records Deleted Successfully.</b>';
} catch (PDOException $e) {
$conn->rollback();
echo $e->getMessage();
return false;
}
}
public function SetData($query, $user, $pass)
{
try {
$db_result = [];
$conn = new PDO("mysql:host=localhost;dbname=test", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("set names utf8");
$count = ['u' => 0, 'i' => 0];
foreach ($query as $db_name => $query_arr) {
$conn->exec('USE ' . $db_name);
foreach ($query_arr as $key => $query_string) {
$cq = $conn->exec($query_string);
if (strpos($query_string, 'UPDATE') !== false) {
$count['u'] += $cq;
}
if (strpos($query_string, 'INSERT') !== false) {
$count['i'] += $cq;
}
}
}
$conn->commit();
$db_result['r'] = true;
$db_result['t'] = 'Updates: ' . $count['u'] . ', Inserts: ' . $count['i'];
return $db_result;
} catch (PDOException $e) {
$conn->rollback();
echo $e->getMessage();
return false;
}
}
}
I would like to be able to insert data by volumes in multiple tables in a single commit...
The idea of doing it that way is because if something fails I want it to be automatically rolled back in all table instances...
So I have a data structure in an array with the following content in my new class:
$dbquery =[
'test'=>[
'0' =>[
0 => 'INSERT INTO table_name_1(column1,column2) VALUES (?,?)', //mean it is the query
1 =>[value11,value12], // mean it is a row
2 =>[value21,value22], // mean it is a row
],
'1' =>[
0 => 'INSERT INTO table_name_2(column1,column2,column3,column4) VALUES (?,?,?,?)', //mean it is the query
1 =>[value11,value12,value13,value14], // mean it is a row
2 =>[value21,value22,value23,value24], // mean it is a row
],
],
];
but i have my first try with bindValue, this is my new class mentioned:
<?php
class DataBase
{
private static ?DataBase $instance = null;
public static function getInstance(): DataBase
{
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
private array $config;
public function __construct()
{
$this->config = ['DB_HOST'=>'test','DB_NAME'=>'test','DB_USER'=>'test','DB_PASSWORD'=>''];
$this->setConnection(new PDO("mysql:host=" . $this->config['DB_HOST'] . ";dbname=" . $this->config['DB_NAME'], $this->config['DB_USER'], $this->config['DB_PASSWORD']));
}
private PDO $connection;
/**
* @return PDO
*/
private function getConnection(): PDO
{
return $this->connection;
}
/**
* @param PDO $connection
*/
private function setConnection(PDO $connection): void
{
$this->connection = $connection;
}
public function changeConnectionServer(string $host, string $db_name, string $user, string $password): void
{
$this->setConnection(new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $user, $password));
}
private array $query;
public function setDataBaseTarget(string $db_name)
{
if (empty($this->query)) {
$this->query = [];
}
$this->query[$db_name] = [];
}
public function buildQuery(string $query)
{
if (empty($this->query)) {
$this->query = [];
$this->query[$this->config['DB_NAME']] = [];
}
$target = array_key_last($this->query);
$this->query[$target][] = [$query];
}
public function addQueryData($data)
{
$target = array_key_last($this->query);
$key = array_key_last($this->query[$target]);
$this->query[$target][$key][] = $data;
}
private function getQuery(): array
{
return $this->query;
}
/**
* @throws Exception
*/
public function setData(): array
{
try {
$time = -microtime(true);
$con = $this->getConnection();
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->beginTransaction();
$con->exec("set names utf8;");
foreach ($this->getQuery() as $db_name => $query_arr) {
$con->exec('USE `' . $db_name . '`;');
$ct = 0;
// on this section have proble with code and logic .... i dont know what i need to dev to insert the data
foreach ($query_arr as $query_structure) {
foreach ($query_structure as $key => $raw) {
if ($key === 0) {
$ct++;
$stmt[$ct] = $con->prepare($raw);
} else {
if (is_array($raw)) {
$c = 0;
foreach ($raw as $value) {
$c++;
$stmt[$ct]->bindValue($c, $value, $this->getParamType($value));
}
}
}
}
$stmt[$ct]->execute();
}
//end section
}
//$con->commit();
return true;
} catch (PDOException $e) {
$con->rollback();
echo $e->getMessage();
return false;
}
}
private function getParamType($value)
{
if (is_int($value)) {
return PDO::PARAM_INT;
} elseif (is_bool($value)) {
return PDO::PARAM_BOOL;
} elseif (is_null($value)) {
return PDO::PARAM_NULL;
} elseif (is_string($value)) {
return PDO::PARAM_STR;
} else {
return false;
}
}
}
$db_handler = DataBase::getInstance();
$db_handler->buildQuery("INSERT INTO `client_list`(`email`,`mobile`) VALUES ('?','?');");
$db_handler->addQueryData(['[email protected]', '35634634636546']);
$db_handler->addQueryData(['[email protected]', '35634634636546']);
$db_handler->addQueryData(['[email protected]', '35634634636546']);
$db_handler->setData();
I can't figure out, develop the part that allows me to package everything in a single transaction... what I have is a stm[] ...
Can someone help me with this development?
|
[
"I can't make heads or tails of all the things your class is doing, but here's a generalized version according to the bits that seem obvious:\npublic function runMultipleQueries() {\n $dbh = $this->getConnection();\n // ... setup stuff\n $dbh->beginTransaction();\n try {\n foreach($this->queries as $query) {\n $stmt->prepare($query->queryString);\n $param_id = 1;\n foreach($query->params as $param) {\n $stmt->bindValue($param_id++, $param);\n }\n $stmt->execute();\n }\n } catch( \\Exception $e ) {\n $dbh->rollback();\n throw $e;\n // IMO if you cannot fully/meaningfully recover, just re-throw and let it kill execution or be caught elsewhere where it can be\n // otherwise you're likely having to maintain a stack of if(foo() == false) { ... } wrappers\n }\n $dbh->commit();\n}\n\nAdditionally, singleton DB classes have the drawbacks of both being limiting if you ever need a second DB handle, as well as boiling down to being global state, and subject to the same \"spooky action at a distance\" problems.\nConsider using dependency inversion and feeding class dependencies in via constructor arguments, method dependencies via method arguments, etc. Eg:\ninterface MyWrapperInterface {\n function setQueries(array $queries);\n function runQueries();\n}\n\nclass MyDbWrapper implements MyWrapperInterface {\n protected $dbh;\n \n public function __construct(\\PDO $dbh) {\n $this->dbh = $dbh;\n }\n \n public function setQueries(array $queries) { /* ... */ }\n public function runQueries() { /* ... */ }\n}\n\nclass MyOtherThing {\n protected $db;\n \n public function __construct( MyWrapperInterface $db ) {\n $this->db = $db;\n }\n \n // ...\n}\n\n$wrapper1 = new MyDbWrapper(new PDO($connstr1, $options));\n$wrapper2 = new MyDbWrapper(new PDO($connstr2, $options));\n\n$thing1 = new MyOtherThing($wrapper1);\n$thing2 = new MyOtherThing($wrapper2);\n$thing1_2 = new MyOtherThing($wrapper1);\n\n// etc\n\n"
] |
[
1
] |
[] |
[] |
[
"bindvalue",
"pdo",
"php",
"php_7.4"
] |
stackoverflow_0074661817_bindvalue_pdo_php_php_7.4.txt
|
Q:
Is it possible to have a Business Event call Custom Code in Acumatica?
When my user adds an appointment, he wants to have 2 things happen:
Send an acknowledgement of the appointment to the customer's cell phone, with information about the appointment
24 hours before the appointment, to have a reminder sent out
The main issue is that the event screen displays dates as UTC. This, of course, confuses the customer. So, I need to change the date and format the text message via code.
When I first did this, there was no way to call a custom method from a business event -- so I actually send the message up to Twilio, catch that with a Webhook that sends it into my custom DLL. That massages the message, making everything look right, and then sends it back through Twilio to the customer.
But this is costly (2 messages sent and 1 received for every event) and needlessly complicated. I want to simplify it now, because I have been told there is added functionality in Business events now that allows a call out into custom code. Is this true?
I was told that this would be available starting in 2020 R2. I am looking for it in the docs and training classes, but I can't see anywhere that this is possible.
How do I call custom code from a business event? Can I set up a subscriber that is in a custom DLL?
Is there something that describes this process somewhere? Or did this never make it into the product?
A:
Here is an example blog from crestwood to use business events to create an import scenario: https://www.crestwood.com/2020/05/19/using-business-events-to-create-transactions-employee-birthday-checks/
The gist of it would be to create the generic inquiry to monitor. Next, you would create a business event that ties to the generic inquiry. Go under subscribers, select Create New Subscriber, and then name it. It will load the import scenario, and attach the provider to the event.
For provider object in the business event, you can fill from Results or Previous Results.
This is based on the aborted shipments in sales demo, but it shows my custom action after matching shipment number.
once saved, you can see your business event shows up as a subscriber:
|
Is it possible to have a Business Event call Custom Code in Acumatica?
|
When my user adds an appointment, he wants to have 2 things happen:
Send an acknowledgement of the appointment to the customer's cell phone, with information about the appointment
24 hours before the appointment, to have a reminder sent out
The main issue is that the event screen displays dates as UTC. This, of course, confuses the customer. So, I need to change the date and format the text message via code.
When I first did this, there was no way to call a custom method from a business event -- so I actually send the message up to Twilio, catch that with a Webhook that sends it into my custom DLL. That massages the message, making everything look right, and then sends it back through Twilio to the customer.
But this is costly (2 messages sent and 1 received for every event) and needlessly complicated. I want to simplify it now, because I have been told there is added functionality in Business events now that allows a call out into custom code. Is this true?
I was told that this would be available starting in 2020 R2. I am looking for it in the docs and training classes, but I can't see anywhere that this is possible.
How do I call custom code from a business event? Can I set up a subscriber that is in a custom DLL?
Is there something that describes this process somewhere? Or did this never make it into the product?
|
[
"Here is an example blog from crestwood to use business events to create an import scenario: https://www.crestwood.com/2020/05/19/using-business-events-to-create-transactions-employee-birthday-checks/\nThe gist of it would be to create the generic inquiry to monitor. Next, you would create a business event that ties to the generic inquiry. Go under subscribers, select Create New Subscriber, and then name it. It will load the import scenario, and attach the provider to the event.\nFor provider object in the business event, you can fill from Results or Previous Results.\nThis is based on the aborted shipments in sales demo, but it shows my custom action after matching shipment number.\n\nonce saved, you can see your business event shows up as a subscriber:\n\n"
] |
[
0
] |
[] |
[] |
[
"acumatica",
"c#"
] |
stackoverflow_0074647157_acumatica_c#.txt
|
Q:
Wallet file not specified (must request wallet RPC through /wallet/ uri-path). error when backuping wallet using BitcoinLib in C#
I'm currently working on a little program for backing up your Bitcoin Core wallet. I am using BitcoinLib v1.15.0 in C#.
IBitcoinService bitcoinService = new BitcoinService("http://127.0.0.1:8332", "test", "test", "", 60);
bitcoinService.BackupWallet("C:\\Users\\dominik\\OneDrive\\Desktop\\backup");
When I run this code I get following error message Wallet file not specified (must request wallet RPC through /wallet/<filename> uri-path).
I am a bit confused, because the BitcoinService.backupwallet(string destination) function has only one input parameter which I assume describes the path where it should generate the backup file (or at least that's the way this command works in Bitcoin Core's terminal).
Is there anyone with experience with BitcoinLib or similar problem. I am open to any suggestions.
The error is related to multiple wallets open at once in Bitcoin Core.
A:
It worked after I've added /wallet/<wallet_name> to the RPC URL
A:
This is just a guess at this stage but you have not specified the file extension in this path "C:\Users\dominik\OneDrive\Desktop\backup" so it does not know exactly which file to look for. In other words the filename is incorrect as it is missing the extension of ".something". Otherwise something else is wrong with your path because maybe it has to have /wallet/ then the uri path but your path does not have that. Please let me know how you go.
A:
If you willing to backup a wallet:
Make sure your bitcoin node up and running
Check used username & password (config file on Windows placed at %APPDATA%\bitcoin\bitcoin.conf)
Use a path with slashes instead of backslashes, ie. c:/users/username/backup/bitcoin/ or c:/users/username/backup/bitcoin/wallet_backup.dat or ../backup/wallet_backup.dat
A:
For me the error was the bitcoin config file.
Check the wallet name property wallet=<your_wallet_name> at bitcoin.conf is correct.
A:
I got exactly the same error message, only because too much wallets where loaded in the same time.
With the latest client (Bitcoin Core 23.0), this can be solved using these API calls (in a kind of Python pseudo-code):
wallets_list = listwallets()
for w in wallets_list:
unloadwallet(w)
loadwallet("my_wallet")
|
Wallet file not specified (must request wallet RPC through /wallet/ uri-path). error when backuping wallet using BitcoinLib in C#
|
I'm currently working on a little program for backing up your Bitcoin Core wallet. I am using BitcoinLib v1.15.0 in C#.
IBitcoinService bitcoinService = new BitcoinService("http://127.0.0.1:8332", "test", "test", "", 60);
bitcoinService.BackupWallet("C:\\Users\\dominik\\OneDrive\\Desktop\\backup");
When I run this code I get following error message Wallet file not specified (must request wallet RPC through /wallet/<filename> uri-path).
I am a bit confused, because the BitcoinService.backupwallet(string destination) function has only one input parameter which I assume describes the path where it should generate the backup file (or at least that's the way this command works in Bitcoin Core's terminal).
Is there anyone with experience with BitcoinLib or similar problem. I am open to any suggestions.
The error is related to multiple wallets open at once in Bitcoin Core.
|
[
"It worked after I've added /wallet/<wallet_name> to the RPC URL\n",
"This is just a guess at this stage but you have not specified the file extension in this path \"C:\\Users\\dominik\\OneDrive\\Desktop\\backup\" so it does not know exactly which file to look for. In other words the filename is incorrect as it is missing the extension of \".something\". Otherwise something else is wrong with your path because maybe it has to have /wallet/ then the uri path but your path does not have that. Please let me know how you go.\n",
"If you willing to backup a wallet:\n\nMake sure your bitcoin node up and running\nCheck used username & password (config file on Windows placed at %APPDATA%\\bitcoin\\bitcoin.conf)\nUse a path with slashes instead of backslashes, ie. c:/users/username/backup/bitcoin/ or c:/users/username/backup/bitcoin/wallet_backup.dat or ../backup/wallet_backup.dat\n\n",
"For me the error was the bitcoin config file.\nCheck the wallet name property wallet=<your_wallet_name> at bitcoin.conf is correct.\n",
"I got exactly the same error message, only because too much wallets where loaded in the same time.\nWith the latest client (Bitcoin Core 23.0), this can be solved using these API calls (in a kind of Python pseudo-code):\nwallets_list = listwallets()\nfor w in wallets_list:\n unloadwallet(w)\nloadwallet(\"my_wallet\")\n\n"
] |
[
3,
0,
0,
0,
0
] |
[] |
[] |
[
"bitcoin",
"bitcoinlib",
"c#",
"rpc"
] |
stackoverflow_0064324893_bitcoin_bitcoinlib_c#_rpc.txt
|
Q:
How to make input text bold in console?
I'm looking for a way to make the text that the user types in the console bold
input("Input your name: ")
If I type "John", I want it to show up as bold as I'm typing it, something like this
Input your name: John
A:
They are called ANSI escape sequence. Basically you output some special bytes to control how the terminal text looks. Try this:
x = input('Name: \u001b[1m') # anything from here on will be BOLD
print('\u001b[0m', end='') # anything from here on will be normal
print('Your input is:', x)
\u001b[1m tells the terminal to switch to bold text. \u001b[0m tells it to reset.
This page gives a good introduction to ANSI escape sequence.
A:
You can do the following with colorama:
from colorama import init,Style,Fore,Back
import os
os.system('cls')
def inputer(prompt) :
init()
print(Style.NORMAL+prompt + Style.BRIGHT+'',end="")
x = input()
return x
## -------------------------
inputer("Input your name: ")
and the output will be as follows:
Input your name: John
ref. : https://youtu.be/wYPh61tROiY
|
How to make input text bold in console?
|
I'm looking for a way to make the text that the user types in the console bold
input("Input your name: ")
If I type "John", I want it to show up as bold as I'm typing it, something like this
Input your name: John
|
[
"They are called ANSI escape sequence. Basically you output some special bytes to control how the terminal text looks. Try this:\nx = input('Name: \\u001b[1m') # anything from here on will be BOLD\n\nprint('\\u001b[0m', end='') # anything from here on will be normal\nprint('Your input is:', x)\n\n\\u001b[1m tells the terminal to switch to bold text. \\u001b[0m tells it to reset.\nThis page gives a good introduction to ANSI escape sequence.\n",
"You can do the following with colorama:\nfrom colorama import init,Style,Fore,Back\nimport os\n\nos.system('cls')\n\ndef inputer(prompt) :\n init()\n print(Style.NORMAL+prompt + Style.BRIGHT+'',end=\"\")\n x = input()\n return x\n\n## -------------------------\n\ninputer(\"Input your name: \")\n\nand the output will be as follows:\n\nInput your name: John\n\nref. : https://youtu.be/wYPh61tROiY\n"
] |
[
4,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0059122173_python_python_3.x.txt
|
Q:
How to get consistent timestamps from Firebase?
After authenticating through Firebase, one of the timestamp fields from the user data when console logged shows up as Fri Dec 02 2022 11:50:37 GMT-0700 (Mountain Standard Time). I haven't had the need to process any timestamps on my project so I just left that as is.
I tried to fetch data from my Firestore that included another timestamp field and somehow I get a different format. It shows as:
ut {seconds: 1670006748, nanoseconds: 11000000}
Is there a way for me to ensure that any timestamps coming from Firebase are returned to my application in a consistent format? I will eventually write a utility file on my React project to handle all of my date/time needs and I just want to be ready when I get to that point.
A:
Have you tried fetching the timestamp to try to convert it?
Sample code:
// to get as date
const date = new TimeStamp(yourTimeStamp.seconds , yourTimeStamp.nanoseconds).toDate();
// to get as string
const date = new TimeStamp(yourTimeStamp.seconds , yourTimeStamp.nanoseconds).toDate().toDateString();
|
How to get consistent timestamps from Firebase?
|
After authenticating through Firebase, one of the timestamp fields from the user data when console logged shows up as Fri Dec 02 2022 11:50:37 GMT-0700 (Mountain Standard Time). I haven't had the need to process any timestamps on my project so I just left that as is.
I tried to fetch data from my Firestore that included another timestamp field and somehow I get a different format. It shows as:
ut {seconds: 1670006748, nanoseconds: 11000000}
Is there a way for me to ensure that any timestamps coming from Firebase are returned to my application in a consistent format? I will eventually write a utility file on my React project to handle all of my date/time needs and I just want to be ready when I get to that point.
|
[
"Have you tried fetching the timestamp to try to convert it?\nSample code:\n// to get as date \nconst date = new TimeStamp(yourTimeStamp.seconds , yourTimeStamp.nanoseconds).toDate(); \n// to get as string \nconst date = new TimeStamp(yourTimeStamp.seconds , yourTimeStamp.nanoseconds).toDate().toDateString();\n\n"
] |
[
1
] |
[] |
[] |
[
"firebase",
"reactjs",
"timestamp"
] |
stackoverflow_0074660358_firebase_reactjs_timestamp.txt
|
Q:
Aggregate and count conditionally but return all lines
My table structure is like this:
+----------+------------+---------------+
| id | manager_id | restaurant_id |
+----------+------------+---------------+
| 1 | 1 | 1001 |
| 2 | 1 | 1002 |
| 3 | 2 | 1003 |
| 4 | 2 | 1004 |
| 5 | 2 | 1005 |
| 6 | 3 | 1006 |
+----------+------------+---------------+
I want to retrieve all the restaurant_id aggregated per manager_id, Additionally, I also need to filter per manager's count(restaurant_id): returning only restaurants of managers that have more than one restaurant, and less than 3.
Edit: this is an oversimplified version of the real data, my actual use case must cover more than one to 5 (included).
So that in the end, the result would be
+---------------+------------+
| restaurant_id | manager_id |
+---------------+------------+
| 1001 | 1 |
| 1002 | 1 |
+---------------+------------+
I tried something similar to:
SELECT
restaurant_id,
manager_id,
COUNT(*) AS restaurant_count
FROM
Manager_Restaurant
GROUP BY
manager_id
HAVING
restaurant_count > 1 and
restaurant_count < 3;
But this return only one line per manager because of the grouping and I want all the restaurants.
A:
You can make use of a windowed count here. More than 1 and less than 3 is 2:
select restaurant_id, manager_id
from (
select *, Count(*) over(partition by manager_id) cnt
from t
)t
where cnt = 2;
A:
Window (aka analytic) functions were designed with just such a case in mind.
You can use a window function to assign to each row the counts for a particular grouping, then select the rows having the required counts. Here is an example:
create table manager_restaurant (id int,manager_id int,restaurant_id int);
insert into manager_restaurant
values (1,1,1001),(2,1,1002),(3,2,1003),(4,2,1004),(5,2,1005),(6,3,1006);
select manager_id,restaurant_id from (
select *,
count(1) over (partition by manager_id) as n
from
manager_restaurant
)x
where
n>1 and n<3 ;
manager_id
restaurant_id
1
1001
1
1002
|
Aggregate and count conditionally but return all lines
|
My table structure is like this:
+----------+------------+---------------+
| id | manager_id | restaurant_id |
+----------+------------+---------------+
| 1 | 1 | 1001 |
| 2 | 1 | 1002 |
| 3 | 2 | 1003 |
| 4 | 2 | 1004 |
| 5 | 2 | 1005 |
| 6 | 3 | 1006 |
+----------+------------+---------------+
I want to retrieve all the restaurant_id aggregated per manager_id, Additionally, I also need to filter per manager's count(restaurant_id): returning only restaurants of managers that have more than one restaurant, and less than 3.
Edit: this is an oversimplified version of the real data, my actual use case must cover more than one to 5 (included).
So that in the end, the result would be
+---------------+------------+
| restaurant_id | manager_id |
+---------------+------------+
| 1001 | 1 |
| 1002 | 1 |
+---------------+------------+
I tried something similar to:
SELECT
restaurant_id,
manager_id,
COUNT(*) AS restaurant_count
FROM
Manager_Restaurant
GROUP BY
manager_id
HAVING
restaurant_count > 1 and
restaurant_count < 3;
But this return only one line per manager because of the grouping and I want all the restaurants.
|
[
"You can make use of a windowed count here. More than 1 and less than 3 is 2:\nselect restaurant_id, manager_id\nfrom (\n select *, Count(*) over(partition by manager_id) cnt\n from t\n)t\nwhere cnt = 2;\n\n",
"Window (aka analytic) functions were designed with just such a case in mind.\nYou can use a window function to assign to each row the counts for a particular grouping, then select the rows having the required counts. Here is an example:\ncreate table manager_restaurant (id int,manager_id int,restaurant_id int);\ninsert into manager_restaurant \n values (1,1,1001),(2,1,1002),(3,2,1003),(4,2,1004),(5,2,1005),(6,3,1006);\n\n\nselect manager_id,restaurant_id from (\n select *,\n count(1) over (partition by manager_id) as n \n from \n manager_restaurant\n )x \n where \n n>1 and n<3 ;\n\n\n\n\n\nmanager_id\nrestaurant_id\n\n\n\n\n1\n1001\n\n\n1\n1002\n\n\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"aggregation",
"count",
"grouping",
"sql"
] |
stackoverflow_0074659409_aggregation_count_grouping_sql.txt
|
Q:
How do I insert a randomly generated number in a textarea?
I'm trying to insert a randomly generated number in a textarea in a specific position. I've tried many possible ways but it won't work. Here is my code:
<!DOCTYPE html>
<html>
<body>
Body <textarea name="txtmsg" rows="20" cols="80"><?php echo GenNum();?> Your REF#[0000] </textarea>
<?php
function GenNum() {
$digits = '[0000]';
if ((strpos ($txtmsg, $digits) !== false)) {
$rand = rand(1000, 99999);
$txtmsg = str_replace('[0000]', $rand, $txtmsg);
}
}
?>
</body>
</html>
[0000] is meant to be replaced by the generated number. So result should be something like this... Your REF#12345
A:
There are a few issues with your code that are preventing it from working as intended.
First, the '$txtmsg' variable that you are using to store the text of the 'textarea' element is not defined. You can fix this by using the '$_POST' superglobal array to access the value of the 'txtmsg' form element after the form is submitted. For example:
$txtmsg = $_POST['txtmsg'];
Second, the 'GenNum()' function that you have defined is not being called, so the code inside the function will never be executed. You can fix this by calling the 'GenNum()' function and assigning its return value to the '$txtmsg' variable, like this:
$txtmsg = GenNum();
Third, the 'GenNum()' function does not have a return value, so even if it were called, it would not return any value to the '$txtmsg' variable. You can fix this by adding a 'return' statement to the function that returns the modified '$txtmsg' string, like this:
function GenNum() {
$txtmsg = $_POST['txtmsg'];
$digits = '[0000]';
if (strpos($txtmsg, $digits) !== false) {
$rand = rand(1000, 99999);
$txtmsg = str_replace('[0000]', $rand, $txtmsg);
}
return $txtmsg;
}
With these changes, your code should work as intended. Here is the complete, modified code:
<!DOCTYPE html>
<html>
<body>
Body <textarea name="txtmsg" rows="20" cols="80"><?php echo GenNum();?> Your REF#[0000] </textarea>
<?php
function GenNum() {
$txtmsg = $_POST['txtmsg'];
$digits = '[0000]';
if (strpos($txtmsg, $digits) !== false) {
$rand = rand(1000, 99999);
$txtmsg = str_replace('[0000]', $rand, $txtmsg);
}
return $txtmsg;
}
?>
</body>
</html>
EDIT: I've changed a few things, this should work now:
<!DOCTYPE html>
<html>
<body>
<!-- Display the generated string in a textarea element -->
<textarea name="txtmsg" rows="20" cols="80"><?php echo GenNum();?></textarea>
<?php
// Define the GenNum() function
function GenNum() {
// Define the string that we want to modify
$txtmsg = "Your REF#[0000]";
// The placeholder that we want to replace with a random number
$digits = '[0000]';
// Check if the $txtmsg string contains the $digits placeholder
if (strpos($txtmsg, $digits) !== false) {
// Generate a random number between 1000 and 99999
$rand = rand(1000, 99999);
// Replace the placeholder with the random number
$txtmsg = str_replace('[0000]', $rand, $txtmsg);
}
// Return the modified string
return $txtmsg;
}
?>
</body>
</html>
|
How do I insert a randomly generated number in a textarea?
|
I'm trying to insert a randomly generated number in a textarea in a specific position. I've tried many possible ways but it won't work. Here is my code:
<!DOCTYPE html>
<html>
<body>
Body <textarea name="txtmsg" rows="20" cols="80"><?php echo GenNum();?> Your REF#[0000] </textarea>
<?php
function GenNum() {
$digits = '[0000]';
if ((strpos ($txtmsg, $digits) !== false)) {
$rand = rand(1000, 99999);
$txtmsg = str_replace('[0000]', $rand, $txtmsg);
}
}
?>
</body>
</html>
[0000] is meant to be replaced by the generated number. So result should be something like this... Your REF#12345
|
[
"There are a few issues with your code that are preventing it from working as intended.\nFirst, the '$txtmsg' variable that you are using to store the text of the 'textarea' element is not defined. You can fix this by using the '$_POST' superglobal array to access the value of the 'txtmsg' form element after the form is submitted. For example:\n$txtmsg = $_POST['txtmsg'];\n\nSecond, the 'GenNum()' function that you have defined is not being called, so the code inside the function will never be executed. You can fix this by calling the 'GenNum()' function and assigning its return value to the '$txtmsg' variable, like this:\n$txtmsg = GenNum();\n\nThird, the 'GenNum()' function does not have a return value, so even if it were called, it would not return any value to the '$txtmsg' variable. You can fix this by adding a 'return' statement to the function that returns the modified '$txtmsg' string, like this:\nfunction GenNum() {\n $txtmsg = $_POST['txtmsg'];\n $digits = '[0000]';\n\n if (strpos($txtmsg, $digits) !== false) {\n $rand = rand(1000, 99999);\n $txtmsg = str_replace('[0000]', $rand, $txtmsg);\n }\n\n return $txtmsg;\n}\n\nWith these changes, your code should work as intended. Here is the complete, modified code:\n<!DOCTYPE html>\n<html>\n<body>\n\nBody <textarea name=\"txtmsg\" rows=\"20\" cols=\"80\"><?php echo GenNum();?> Your REF#[0000] </textarea>\n\n<?php\n\nfunction GenNum() {\n $txtmsg = $_POST['txtmsg'];\n $digits = '[0000]';\n\n if (strpos($txtmsg, $digits) !== false) {\n $rand = rand(1000, 99999);\n $txtmsg = str_replace('[0000]', $rand, $txtmsg);\n }\n\n return $txtmsg;\n}\n?>\n \n</body>\n</html>\n\nEDIT: I've changed a few things, this should work now:\n<!DOCTYPE html>\n<html>\n<body>\n\n<!-- Display the generated string in a textarea element -->\n<textarea name=\"txtmsg\" rows=\"20\" cols=\"80\"><?php echo GenNum();?></textarea>\n\n<?php\n\n// Define the GenNum() function\nfunction GenNum() {\n // Define the string that we want to modify\n $txtmsg = \"Your REF#[0000]\";\n\n // The placeholder that we want to replace with a random number\n $digits = '[0000]';\n\n // Check if the $txtmsg string contains the $digits placeholder\n if (strpos($txtmsg, $digits) !== false) {\n // Generate a random number between 1000 and 99999\n $rand = rand(1000, 99999);\n\n // Replace the placeholder with the random number\n $txtmsg = str_replace('[0000]', $rand, $txtmsg);\n }\n\n // Return the modified string\n return $txtmsg;\n}\n?>\n \n</body>\n</html>\n\n"
] |
[
0
] |
[] |
[] |
[
"php",
"random"
] |
stackoverflow_0074662138_php_random.txt
|
Q:
TS SS Vector similarity using matrices
I have two sets of vectors A,B and I want to compute the TS-SS similarity for each vector in A compared to every vector in B.
I have an implementation (from https://github.com/taki0112/Vector_Similarity) used for 2 vectors, however when I tried using it for matrices (function "compute_matrix_sim") - it is very inefficient and takes forever.
Is there a more vectorized approach to use TS-SS for matrices?
Thanks!
import math
import numpy as np
class TS_SS:
def Cosine(self, vec1: np.ndarray, vec2: np.ndarray):
return np.dot(vec1, vec2.T) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
def VectorSize(self, vec: np.ndarray):
return np.linalg.norm(vec)
def Euclidean(self, vec1: np.ndarray, vec2: np.ndarray):
return np.linalg.norm(vec1 - vec2)
def Theta(self, vec1: np.ndarray, vec2: np.ndarray):
return np.arccos(self.Cosine(vec1, vec2)) + np.radians(10)
def Triangle(self, vec1: np.ndarray, vec2: np.ndarray):
theta = np.radians(self.Theta(vec1, vec2))
return (self.VectorSize(vec1) * self.VectorSize(vec2) * np.sin(theta)) / 2
def Magnitude_Difference(self, vec1: np.ndarray, vec2: np.ndarray):
return abs(self.VectorSize(vec1) - self.VectorSize(vec2))
def Sector(self, vec1: np.ndarray, vec2: np.ndarray):
ED = self.Euclidean(vec1, vec2)
MD = self.Magnitude_Difference(vec1, vec2)
theta = self.Theta(vec1, vec2)
return math.pi * (ED + MD) ** 2 * theta / 360
def __call__(self, vec1: np.ndarray, vec2: np.ndarray):
return self.Triangle(vec1, vec2) * self.Sector(vec1, vec2)
def compute_matrix_sim(m1, m2):
similarity = TS_SS()
ans = np.zeros((len(m1), len(m2)))
for i, vec_m1 in enumerate(m1):
for j, vec_m2 in enumerate(m2):
ans[i, j] = similarity(vec_m1, vec_m2)
return ans
# Usage
v1 = np.random.random_sample((40, 80))
v2 = np.random.random_sample((2000000, 80))
x = compute_matrix_sim(v1, v2)
print(x)
A:
import numpy as np
import torch
class TS_SS:
def __init__(self):
self.thetaval = 0
self.vecnorm1 = 0
self.vecnorm2 = 0
def Theta(self, vec1, vec2):
return (torch.arccos(torch.mm(vec1,vec2.T)/(self.vecnorm1*self.vecnorm2.T))
+ np.radians(10))
def Triangle(self, vec1, vec2):
self.thetaval = self.Theta(vec1, vec2)
return ((self.vecnorm1 * self.vecnorm2.T * torch.sin(self.thetaval))
/ 2)
def Sector(self, vec1: np.ndarray, vec2: np.ndarray):
ED = torch.cdist(vec1,vec2,p=2)
MD = torch.abs(self.vecnorm1 - self.vecnorm2.T)
# theta = self.Theta(vec1, vec2)
return (1/2) * ((ED + MD) ** 2) * self.thetaval
def __call__(self, vec1, vec2):
self.thetaval = 0
self.vecnorm1 = vec1.norm(p=2, dim=1, keepdim=True)
self.vecnorm2 = vec2.norm(p=2, dim=1, keepdim=True)
return self.Triangle(vec1, vec2) * self.Sector(vec1, vec2)
v1 = torch.tensor([[3.0,4.0]])
v2 = torch.tensor([[4.0,3.0]])
similarity = TS_SS()
print(similarity(v1, v2))
|
TS SS Vector similarity using matrices
|
I have two sets of vectors A,B and I want to compute the TS-SS similarity for each vector in A compared to every vector in B.
I have an implementation (from https://github.com/taki0112/Vector_Similarity) used for 2 vectors, however when I tried using it for matrices (function "compute_matrix_sim") - it is very inefficient and takes forever.
Is there a more vectorized approach to use TS-SS for matrices?
Thanks!
import math
import numpy as np
class TS_SS:
def Cosine(self, vec1: np.ndarray, vec2: np.ndarray):
return np.dot(vec1, vec2.T) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
def VectorSize(self, vec: np.ndarray):
return np.linalg.norm(vec)
def Euclidean(self, vec1: np.ndarray, vec2: np.ndarray):
return np.linalg.norm(vec1 - vec2)
def Theta(self, vec1: np.ndarray, vec2: np.ndarray):
return np.arccos(self.Cosine(vec1, vec2)) + np.radians(10)
def Triangle(self, vec1: np.ndarray, vec2: np.ndarray):
theta = np.radians(self.Theta(vec1, vec2))
return (self.VectorSize(vec1) * self.VectorSize(vec2) * np.sin(theta)) / 2
def Magnitude_Difference(self, vec1: np.ndarray, vec2: np.ndarray):
return abs(self.VectorSize(vec1) - self.VectorSize(vec2))
def Sector(self, vec1: np.ndarray, vec2: np.ndarray):
ED = self.Euclidean(vec1, vec2)
MD = self.Magnitude_Difference(vec1, vec2)
theta = self.Theta(vec1, vec2)
return math.pi * (ED + MD) ** 2 * theta / 360
def __call__(self, vec1: np.ndarray, vec2: np.ndarray):
return self.Triangle(vec1, vec2) * self.Sector(vec1, vec2)
def compute_matrix_sim(m1, m2):
similarity = TS_SS()
ans = np.zeros((len(m1), len(m2)))
for i, vec_m1 in enumerate(m1):
for j, vec_m2 in enumerate(m2):
ans[i, j] = similarity(vec_m1, vec_m2)
return ans
# Usage
v1 = np.random.random_sample((40, 80))
v2 = np.random.random_sample((2000000, 80))
x = compute_matrix_sim(v1, v2)
print(x)
|
[
"import numpy as np\nimport torch\n\n\nclass TS_SS:\n def __init__(self):\n self.thetaval = 0\n self.vecnorm1 = 0\n self.vecnorm2 = 0\n\n def Theta(self, vec1, vec2):\n return (torch.arccos(torch.mm(vec1,vec2.T)/(self.vecnorm1*self.vecnorm2.T))\n + np.radians(10))\n\n def Triangle(self, vec1, vec2):\n self.thetaval = self.Theta(vec1, vec2)\n return ((self.vecnorm1 * self.vecnorm2.T * torch.sin(self.thetaval))\n / 2)\n\n\n\n def Sector(self, vec1: np.ndarray, vec2: np.ndarray):\n ED = torch.cdist(vec1,vec2,p=2)\n MD = torch.abs(self.vecnorm1 - self.vecnorm2.T)\n # theta = self.Theta(vec1, vec2)\n return (1/2) * ((ED + MD) ** 2) * self.thetaval\n\n def __call__(self, vec1, vec2):\n self.thetaval = 0\n self.vecnorm1 = vec1.norm(p=2, dim=1, keepdim=True)\n self.vecnorm2 = vec2.norm(p=2, dim=1, keepdim=True)\n return self.Triangle(vec1, vec2) * self.Sector(vec1, vec2)\n\n\nv1 = torch.tensor([[3.0,4.0]])\nv2 = torch.tensor([[4.0,3.0]])\nsimilarity = TS_SS()\nprint(similarity(v1, v2))\n\n"
] |
[
0
] |
[] |
[] |
[
"cosine_similarity",
"nlp",
"python",
"similarity",
"vectorization"
] |
stackoverflow_0068338024_cosine_similarity_nlp_python_similarity_vectorization.txt
|
Q:
Why did user object is undefined in NextAuth session callback?
I use NextAuth for signIn with discord provider and I need to add userID into the session object. For that I use session callback but user object is undefined. When I try to add userID to the session object, I got an error like this :
[next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'id')
Indeed, it seems the user object is undefined but I don't have any solution.
export default NextAuth({
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
authorization: { params: { scope: 'identify' } }
})
],
session: {
jwt: true
},
jwt: {
secret: process.env.JWT_SECRET
},
callbacks: {
async session({session, user}) {
session.user.id = user.id
return session
},
async jwt(token) {
return token
}
}
})
A:
You can do it like that
providers: [
Github({
clientId: process.env.GITHUB_ID,
clientSecret:process.env.GITHUB_SECRET,
})
],
database :process.env.DB_URL,
session:{
jwt:true
},
adapter: MongoDBAdapter(clientPromise, {
databaseName: 'AuthDb'
}),
jwt:{
secret: 'secretCode',
},
callbacks:{
async jwt({token,user}){
if(user){
token.id = user.id
}
return token
},
async session(session,token) {
session.user.id =token.id
return session
}
},
}); ```
A:
You can augment next-auth session types with @types/next-auth by adding an auth.d.ts file with the following:
import "next-auth";
declare module "next-auth" {
interface User {
id: string | number;
}
interface Session {
user: User;
}
}
More on this: https://github.com/nextauthjs/next-auth/issues/671
|
Why did user object is undefined in NextAuth session callback?
|
I use NextAuth for signIn with discord provider and I need to add userID into the session object. For that I use session callback but user object is undefined. When I try to add userID to the session object, I got an error like this :
[next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'id')
Indeed, it seems the user object is undefined but I don't have any solution.
export default NextAuth({
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID,
clientSecret: process.env.DISCORD_CLIENT_SECRET,
authorization: { params: { scope: 'identify' } }
})
],
session: {
jwt: true
},
jwt: {
secret: process.env.JWT_SECRET
},
callbacks: {
async session({session, user}) {
session.user.id = user.id
return session
},
async jwt(token) {
return token
}
}
})
|
[
"You can do it like that\n providers: [ \n Github({\n clientId: process.env.GITHUB_ID,\n clientSecret:process.env.GITHUB_SECRET,\n })\n ],\n database :process.env.DB_URL,\n session:{\n jwt:true\n },\n adapter: MongoDBAdapter(clientPromise, {\n databaseName: 'AuthDb'\n }),\n jwt:{\n secret: 'secretCode',\n },\n callbacks:{\n async jwt({token,user}){\n if(user){\n token.id = user.id\n }\n return token\n },\n async session(session,token) {\n session.user.id =token.id\n return session \n }\n },\n}); ```\n\n",
"You can augment next-auth session types with @types/next-auth by adding an auth.d.ts file with the following:\nimport \"next-auth\";\n\ndeclare module \"next-auth\" {\n interface User {\n id: string | number;\n }\n\n interface Session {\n user: User;\n }\n}\n\nMore on this: https://github.com/nextauthjs/next-auth/issues/671\n"
] |
[
1,
0
] |
[
"You can do like that in your callback :-\ncallbacks: {\n jwt:({token,user})=>{\n if(user){\n token.id = user.userId;\n }\n return token;\n },\n session:({session,token}) =>{\n if(token){\n session.user.id = token.id;\n }\n return session;\n }\n}\n\nand don't forget to return the user in the function which is executed just before the callback, otherwise it tell undefined.\n"
] |
[
-1
] |
[
"javascript",
"jwt",
"next.js",
"next_auth",
"reactjs"
] |
stackoverflow_0072073321_javascript_jwt_next.js_next_auth_reactjs.txt
|
Q:
Merge Sort failing at deletion (Thread 1: EXC_BAD_ACCESS code 2 )
I know I should be using vectors, but I want to get better at dynamically allocating arrays. I'm not sure where I went wrong. I'm creating a new array and deleting it.
void Merge(int *arr,int begin, int mid, int end){
int*arrB = new int[mid - begin + 1];
int i = begin;
int j = mid+1;
int k = 0;
while(i <= mid && j <= end){
if(arr[i] <= arr[j]){
arrB[k] = arr[i];
k++;
i++;
}
else {
arrB[k] = arr[j];
k++;
j++;
}
}
while(i <= mid){
arrB[k] = arr[i];
i++;
k++;
}
while(j <= end){
arrB[k] = arr[j];
j++;
k++;
}
k = 0;
for(int i = begin; i <= end; i++){
arr[i] = arrB[k];
s.setData(arr);
k++;
}
delete[] arrB; //error here
}
I've tried replacing <= to < for n-1, I've tried switching to vectors and that also gives me an error. I've also tried looking at similar questions.
A:
void Merge(int *arr, int begin, int mid, int end) {
// Allocate the arrB array on the stack instead of the heap
int arrB[mid - begin + 1];
int i = begin;
int j = mid+1;
int k = 0;
// Initialize the k variable to 0 before using it to index arrB
k = 0;
while (i <= mid && j <= end) {
if (arr[i] <= arr[j]) {
arrB[k] = arr[i];
i++;
} else {
arrB[k] = arr[j];
j++;
}
// Increment the k variable after each element is added to arrB
k++;
}
while (i <= mid) {
arrB[k] = arr[i];
i++;
k++;
}
while (j <= end) {
arrB[k] = arr[j];
j++;
k++;
}
// Call the setData method once, outside of the for loop
s.setData(arr);
k = 0;
for (int i = begin; i <= end; i++) {
arr[i] = arrB[k];
k++;
}
}
|
Merge Sort failing at deletion (Thread 1: EXC_BAD_ACCESS code 2 )
|
I know I should be using vectors, but I want to get better at dynamically allocating arrays. I'm not sure where I went wrong. I'm creating a new array and deleting it.
void Merge(int *arr,int begin, int mid, int end){
int*arrB = new int[mid - begin + 1];
int i = begin;
int j = mid+1;
int k = 0;
while(i <= mid && j <= end){
if(arr[i] <= arr[j]){
arrB[k] = arr[i];
k++;
i++;
}
else {
arrB[k] = arr[j];
k++;
j++;
}
}
while(i <= mid){
arrB[k] = arr[i];
i++;
k++;
}
while(j <= end){
arrB[k] = arr[j];
j++;
k++;
}
k = 0;
for(int i = begin; i <= end; i++){
arr[i] = arrB[k];
s.setData(arr);
k++;
}
delete[] arrB; //error here
}
I've tried replacing <= to < for n-1, I've tried switching to vectors and that also gives me an error. I've also tried looking at similar questions.
|
[
"void Merge(int *arr, int begin, int mid, int end) {\n // Allocate the arrB array on the stack instead of the heap\n int arrB[mid - begin + 1];\n\n\n\n int i = begin;\n int j = mid+1;\n int k = 0;\n\n\n\n // Initialize the k variable to 0 before using it to index arrB\n k = 0;\n\n\n\n while (i <= mid && j <= end) {\n if (arr[i] <= arr[j]) {\n arrB[k] = arr[i];\n i++;\n } else {\n arrB[k] = arr[j];\n j++;\n }\n\n\n\n // Increment the k variable after each element is added to arrB\n k++;\n }\n\n\n\n while (i <= mid) {\n arrB[k] = arr[i];\n i++;\n k++;\n }\n while (j <= end) {\n arrB[k] = arr[j];\n j++;\n k++;\n }\n\n\n\n // Call the setData method once, outside of the for loop\n s.setData(arr);\n\n\n\n k = 0;\n for (int i = begin; i <= end; i++) {\n arr[i] = arrB[k];\n k++;\n }\n}\n\n"
] |
[
1
] |
[] |
[] |
[
"c++",
"mergesort",
"xcode14"
] |
stackoverflow_0074662193_c++_mergesort_xcode14.txt
|
Q:
How to restrict access by particular user to bucket using bucket level policy in minio?
I am configuring minio as S3 compatible storage.
Based on https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html
I understood that I can limit access to the bucket using BUCKET level policy for particular user.
aws example from the linked document:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddCannedAcl",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::111122223333:root",
"arn:aws:iam::444455556666:root"
]
},
"Action": [
"s3:PutObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*",
"Condition": {
"StringEquals": {
"s3:x-amz-acl": [
"public-read"
]
}
}
}
]
}
Let's consider 2 lines:
"arn:aws:iam::111122223333:root",
"arn:aws:iam::444455556666:root"
as I understand 111122223333:root and 444455556666:root are user identifiers. But I haven't found any mc command which return me any user identifier ? I also check UI console but I haven't found anything
Could you please help ?
A:
"Principal": {
"AWS": [
"arn:aws:iam::111122223333:root",
"arn:aws:iam::444455556666:root"
]
},
Bucket Policies in MinIO are for anonymous access only, we did not implement this on purpose because AWS implementation in this regard is unnecessarily complex and redundant. As there are many ways to do the same thing.
You simply attach relevant policies directly to your users and provide them access via resources for relevant buckets or prefixes. This has solved 90% of the use cases 100% of the time.
There may be other requirements that might come in the future, at that point we may reconsider our position and implement it. Until then you do not really need Bucket policies with Principals.
A:
Bucket level policy in MinIO is only for anonymous users. To restrict a user access you need to set IAM policies.
A:
Althouh Minio states they are s3 compatible - they don't support it and the worst thing here that I was not able to find any information in Minio documentation about inconsistecy with S3 API regarding my question.
But eventually after wasting many and many hours I was able to find closed ticket on github and it is slearly stated that it won't be implemented. It must be in documentation.
https://github.com/minio/minio/issues/9530
|
How to restrict access by particular user to bucket using bucket level policy in minio?
|
I am configuring minio as S3 compatible storage.
Based on https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html
I understood that I can limit access to the bucket using BUCKET level policy for particular user.
aws example from the linked document:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AddCannedAcl",
"Effect": "Allow",
"Principal": {
"AWS": [
"arn:aws:iam::111122223333:root",
"arn:aws:iam::444455556666:root"
]
},
"Action": [
"s3:PutObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*",
"Condition": {
"StringEquals": {
"s3:x-amz-acl": [
"public-read"
]
}
}
}
]
}
Let's consider 2 lines:
"arn:aws:iam::111122223333:root",
"arn:aws:iam::444455556666:root"
as I understand 111122223333:root and 444455556666:root are user identifiers. But I haven't found any mc command which return me any user identifier ? I also check UI console but I haven't found anything
Could you please help ?
|
[
" \"Principal\": {\n \"AWS\": [\n \"arn:aws:iam::111122223333:root\",\n \"arn:aws:iam::444455556666:root\"\n ]\n },\n\nBucket Policies in MinIO are for anonymous access only, we did not implement this on purpose because AWS implementation in this regard is unnecessarily complex and redundant. As there are many ways to do the same thing.\nYou simply attach relevant policies directly to your users and provide them access via resources for relevant buckets or prefixes. This has solved 90% of the use cases 100% of the time.\nThere may be other requirements that might come in the future, at that point we may reconsider our position and implement it. Until then you do not really need Bucket policies with Principals.\n",
"Bucket level policy in MinIO is only for anonymous users. To restrict a user access you need to set IAM policies.\n",
"Althouh Minio states they are s3 compatible - they don't support it and the worst thing here that I was not able to find any information in Minio documentation about inconsistecy with S3 API regarding my question.\nBut eventually after wasting many and many hours I was able to find closed ticket on github and it is slearly stated that it won't be implemented. It must be in documentation.\nhttps://github.com/minio/minio/issues/9530\n"
] |
[
1,
1,
-1
] |
[] |
[] |
[
"access_control",
"amazon_s3",
"java",
"minio"
] |
stackoverflow_0074603734_access_control_amazon_s3_java_minio.txt
|
Q:
Alamofire Deprication target Warning Silence
How do I get rid of this warning?
My iOS Development Traget ist iOS 13
No Mac or TVOS Target added.
Updated to the new Version of Alamofire+
Screenshot Alamofire
A:
Update to 5.6.4, which updated the package with the new deployment targets.
|
Alamofire Deprication target Warning Silence
|
How do I get rid of this warning?
My iOS Development Traget ist iOS 13
No Mac or TVOS Target added.
Updated to the new Version of Alamofire+
Screenshot Alamofire
|
[
"Update to 5.6.4, which updated the package with the new deployment targets.\n"
] |
[
0
] |
[] |
[] |
[
"alamofire"
] |
stackoverflow_0074652200_alamofire.txt
|
Q:
JavaFX TableView Cell color change depending on text value
I have a JavaFX desktop app with a TableView. I populate the data using a POJO named Orders which ultimately comes from a Firebird SQL database.
Image of what I have now
What I am looking to do is change the background fill color of each cell in the first column 'Status' depending on the text value. So if the text value is 'READY' then green, 'STARTED' will be yellow and 'DONE' will be gray.
Image of what I would like
Here is the code portion I use to populate the TableView:
`
@FXML private TableView<Orders> tblOrders;
@FXML private TableColumn<Orders, Integer> clmStatus;
@FXML private TableColumn<Orders, String> clmStartDateTime;
@FXML private TableColumn<Orders, String> clmShopOrder;
@FXML private TableColumn<Orders, String> clmRotation;
@FXML private TableColumn<Orders, String> clmGMIECode;
@FXML private TableColumn<Orders, String> clmSAPCode;
@FXML private TableColumn<Orders, Integer> clmLineName;
@FXML private TableColumn<Orders, Integer> clmOrderProductionNr;
private ObservableList<Orders> list;
public void initialize(URL location, ResourceBundle resources) {
populateTable();
}
private void populateTable() {
log.appLog("Populating table\r\n");
clmStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
clmStartDateTime.setCellValueFactory(new PropertyValueFactory<>
("startDateTime"));
clmShopOrder.setCellValueFactory(new PropertyValueFactory<>("extra1"));
clmRotation.setCellValueFactory(new
PropertyValueFactory<("batchLotNr"));
clmGMIECode.setCellValueFactory(new PropertyValueFactory<>("wareNr"));
clmSAPCode.setCellValueFactory(new PropertyValueFactory<>
("serviceDescription"));
clmLineName.setCellValueFactory(new PropertyValueFactory<>
("productionLineNr"));
clmOrderProductionNr.setCellValueFactory(new PropertyValueFactory<>
("orderProductionNr"));
tblOrders.setItems(list);
}
`
Code sample of my Orders POJO:
`
public class Orders {
private final SimpleStringProperty status;
private final SimpleStringProperty startDateTime;
private final SimpleStringProperty extra1;
private final SimpleStringProperty batchLotNr;
private final SimpleStringProperty wareNr;
private final SimpleStringProperty serviceDescription;
private final SimpleStringProperty productionLineNr;
private final SimpleIntegerProperty orderProductionNr;
Orders(String status, String startDateTime, String extra1, String batchLotNr, String wareNr, String serviceDescription, String productionLineNr, int orderProductionNr) {
this.status = new SimpleStringProperty(status);
this.startDateTime = new SimpleStringProperty(startDateTime);
this.extra1 = new SimpleStringProperty(extra1);
this.batchLotNr = new SimpleStringProperty(batchLotNr);
this.wareNr = new SimpleStringProperty(wareNr);
this.serviceDescription = new SimpleStringProperty(serviceDescription);
this.productionLineNr = new SimpleStringProperty(productionLineNr);
this.orderProductionNr = new SimpleIntegerProperty((orderProductionNr));
}
public String getStatus() {
return status.get();
}
public String getStartDateTime() {return startDateTime.get(); }
public String getExtra1() {
return extra1.get();
}
public String getBatchLotNr() {
return batchLotNr.get();
}
public String getWareNr() {
return wareNr.get();
}
public String getServiceDescription() {
return serviceDescription.get();
}
public String getProductionLineNr() {
return productionLineNr.get();
}
int getOrderProductionNr() {return orderProductionNr.get();}
}
`
I have tried using a callback but I have never used callbacks before and don't properly understand how I can fit my needs into a callback. Any help will be important to my learning. Thanks SO.
A:
You have to define a custom TableCell for your status column like this:
public class ColoredStatusTableCell extends TableCell<TableRow, Status> {
@Override
protected void updateItem(Status item, boolean empty) {
super.updateItem(item, empty);
if (empty || getTableRow() == null) {
setText(null);
setGraphic(null);
} else {
TableRow row = (TableRow) getTableRow().getItem();
setText(item.toString());
setStyle("-fx-background-color: " + row.getColorAsString());
// If the statis is changing dynamic you have to add the following:
row.statusProperty()
.addListener((observable, oldValue, newValue) ->
setStyle("-fx-background-color: " + row.getColorAsString()));
}
}
}
Where TableRow:
public class TableRow {
private ObjectProperty<Status> status;
private Map<Status, Color> statusColor;
public TableRow(Status status, Map<Status, Color> statusColor) {
this.status = new SimpleObjectProperty<>(status);
this.statusColor = statusColor;
}
public Status getStatus() {
return status.get();
}
public ObjectProperty<Status> statusProperty() {
return status;
}
public Color getStatusColor() {
return statusColor.get(status.get());
}
public String getColorAsString() {
return String.format("#%02X%02X%02X",
(int) (getStatusColor().getRed() * 255),
(int) (getStatusColor().getGreen() * 255),
(int) (getStatusColor().getBlue() * 255));
}
}
Status:
public enum Status {
READY, STARTED, DONE
}
and the controller:
public class TestController {
@FXML
private TableView<TableRow> table;
@FXML
private TableColumn<TableRow, Status> column;
private ObservableList<TableRow> data = FXCollections.observableArrayList();
@FXML
public void initialize() {
column.setCellValueFactory(data -> data.getValue().statusProperty());
column.setCellFactory(factory -> new ColoredStatusTableCell());
Map<Status, Color> statusColor = new HashMap<>();
statusColor.put(Status.READY, Color.GREEN);
statusColor.put(Status.STARTED, Color.YELLOW);
statusColor.put(Status.DONE, Color.GRAY);
TableRow ready = new TableRow(Status.READY, statusColor);
TableRow started = new TableRow(Status.STARTED, statusColor);
TableRow done = new TableRow(Status.DONE, statusColor);
data.addAll(ready, started, done);
table.setItems(data);
}
}
I chose to set the status as an enum because it is easier to handle it,
then I have used a map to each status-color combination, then in the cell you can set its background color to the matched color of the status.
If you want of course instead of Color.YELLOW and so on you can use a custom Color.rgb(red,green,blue)
A:
I finally found the solution without having to use any extra classes, just a callback in my controller class with the help of this SO link:
StackOverFlow Link
`
private void populateTable() {
log.appLog("Populating table\r\n");
//clmStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
clmStatus.setCellFactory(new Callback<TableColumn<Orders, String>,
TableCell<Orders, String>>()
{
@Override
public TableCell<Orders, String> call(
TableColumn<Orders, String> param) {
return new TableCell<Orders, String>() {
@Override
protected void updateItem(String item, boolean empty) {
if (!empty) {
int currentIndex = indexProperty()
.getValue() < 0 ? 0
: indexProperty().getValue();
String clmStatus = param
.getTableView().getItems()
.get(currentIndex).getStatus();
if (clmStatus.equals("READY")) {
setTextFill(Color.WHITE);
setStyle("-fx-font-weight: bold");
setStyle("-fx-background-color: green");
setText(clmStatus);
} else if (clmStatus.equals("STARTED")){
setTextFill(Color.BLACK);
setStyle("-fx-font-weight: bold");
setStyle("-fx-background-color: yellow");
setText(clmStatus);
} else if (clmStatus.equals("DONE")){
setTextFill(Color.BLACK);
setStyle("-fx-font-weight: bold");
setStyle("-fx-background-color: gray");
setText(clmStatus);
} else {
setTextFill(Color.WHITE);
setStyle("-fx-font-weight: bold");
setStyle("-fx-background-color: red");
setText(clmStatus);
}
}
}
};
}
});
clmStartDateTime.setCellValueFactory(new PropertyValueFactory<>("startDateTime"));
clmShopOrder.setCellValueFactory(new PropertyValueFactory<>("extra1"));
clmRotation.setCellValueFactory(new PropertyValueFactory<>("batchLotNr"));
clmGMIECode.setCellValueFactory(new PropertyValueFactory<>("wareNr"));
clmSAPCode.setCellValueFactory(new PropertyValueFactory<>("serviceDescription"));
clmLineName.setCellValueFactory(new PropertyValueFactory<>("productionLineNr"));
clmOrderProductionNr.setCellValueFactory(new PropertyValueFactory<>("orderProductionNr"));
tblOrders.setItems(list);
}
`
A:
I don't have badge to comment, but wanted to add some details.
I wanted to format color of cell based on the boolean value which i have in my data set. I have reviewed this question and similar one provided already here:
Stackoverflow link - style based on another cell in row
What was missing in both for me is reseting style when there is no value as kleopatra mentioned.
This works for me:
public class TableCellColored extends TableCell<DimensionDtoFxBean, DimValVoFxBean> {
private static final String DEFAULT_STYLE_CLASS = "table-cell";
public TableCellColored() {
super();
}
@Override
protected void updateItem(DimValVoFxBean item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText("");
resetStyle();
return;
}
setText(Optional.ofNullable(item.getValue()).map(BigDecimal::toString).orElse(""));
Boolean conversionFlag = Optional.ofNullable(item.getConversionFlag()).orElse(true);
updateStyle(conversionFlag);
item.conversionFlagProperty()
.addListener((observable, oldValue, newValue) -> updateStyle(newValue));
}
private void updateStyle(Boolean conversionFlag) {
if (!conversionFlag) {
setStyle("-fx-background-color: red");
} else {
resetStyle();
}
}
private void resetStyle() {
setStyle("");
getStyleClass().addAll(TableCellColored.DEFAULT_STYLE_CLASS);
}
}
Since I have value object with value and boolean flag I can do it i seperate class and don't have add lambda in controller.
Deafult styling of cell is transparent so if we use style to change color, we have to reset it when there is no value.
Since direct styling has bigger priority than class it overrides default styling from css classes.
To be on the safe side I also apply DEFAULT_STYLE_CLASS. Value taken from TableCell class.
Without listener and styles reset I red was staying in table during scrolling. After few scrolls all cells where red. So listener and styles reset is the must have for me.
|
JavaFX TableView Cell color change depending on text value
|
I have a JavaFX desktop app with a TableView. I populate the data using a POJO named Orders which ultimately comes from a Firebird SQL database.
Image of what I have now
What I am looking to do is change the background fill color of each cell in the first column 'Status' depending on the text value. So if the text value is 'READY' then green, 'STARTED' will be yellow and 'DONE' will be gray.
Image of what I would like
Here is the code portion I use to populate the TableView:
`
@FXML private TableView<Orders> tblOrders;
@FXML private TableColumn<Orders, Integer> clmStatus;
@FXML private TableColumn<Orders, String> clmStartDateTime;
@FXML private TableColumn<Orders, String> clmShopOrder;
@FXML private TableColumn<Orders, String> clmRotation;
@FXML private TableColumn<Orders, String> clmGMIECode;
@FXML private TableColumn<Orders, String> clmSAPCode;
@FXML private TableColumn<Orders, Integer> clmLineName;
@FXML private TableColumn<Orders, Integer> clmOrderProductionNr;
private ObservableList<Orders> list;
public void initialize(URL location, ResourceBundle resources) {
populateTable();
}
private void populateTable() {
log.appLog("Populating table\r\n");
clmStatus.setCellValueFactory(new PropertyValueFactory<>("status"));
clmStartDateTime.setCellValueFactory(new PropertyValueFactory<>
("startDateTime"));
clmShopOrder.setCellValueFactory(new PropertyValueFactory<>("extra1"));
clmRotation.setCellValueFactory(new
PropertyValueFactory<("batchLotNr"));
clmGMIECode.setCellValueFactory(new PropertyValueFactory<>("wareNr"));
clmSAPCode.setCellValueFactory(new PropertyValueFactory<>
("serviceDescription"));
clmLineName.setCellValueFactory(new PropertyValueFactory<>
("productionLineNr"));
clmOrderProductionNr.setCellValueFactory(new PropertyValueFactory<>
("orderProductionNr"));
tblOrders.setItems(list);
}
`
Code sample of my Orders POJO:
`
public class Orders {
private final SimpleStringProperty status;
private final SimpleStringProperty startDateTime;
private final SimpleStringProperty extra1;
private final SimpleStringProperty batchLotNr;
private final SimpleStringProperty wareNr;
private final SimpleStringProperty serviceDescription;
private final SimpleStringProperty productionLineNr;
private final SimpleIntegerProperty orderProductionNr;
Orders(String status, String startDateTime, String extra1, String batchLotNr, String wareNr, String serviceDescription, String productionLineNr, int orderProductionNr) {
this.status = new SimpleStringProperty(status);
this.startDateTime = new SimpleStringProperty(startDateTime);
this.extra1 = new SimpleStringProperty(extra1);
this.batchLotNr = new SimpleStringProperty(batchLotNr);
this.wareNr = new SimpleStringProperty(wareNr);
this.serviceDescription = new SimpleStringProperty(serviceDescription);
this.productionLineNr = new SimpleStringProperty(productionLineNr);
this.orderProductionNr = new SimpleIntegerProperty((orderProductionNr));
}
public String getStatus() {
return status.get();
}
public String getStartDateTime() {return startDateTime.get(); }
public String getExtra1() {
return extra1.get();
}
public String getBatchLotNr() {
return batchLotNr.get();
}
public String getWareNr() {
return wareNr.get();
}
public String getServiceDescription() {
return serviceDescription.get();
}
public String getProductionLineNr() {
return productionLineNr.get();
}
int getOrderProductionNr() {return orderProductionNr.get();}
}
`
I have tried using a callback but I have never used callbacks before and don't properly understand how I can fit my needs into a callback. Any help will be important to my learning. Thanks SO.
|
[
"You have to define a custom TableCell for your status column like this:\npublic class ColoredStatusTableCell extends TableCell<TableRow, Status> {\n\n @Override\n protected void updateItem(Status item, boolean empty) {\n super.updateItem(item, empty);\n if (empty || getTableRow() == null) {\n setText(null);\n setGraphic(null);\n } else {\n TableRow row = (TableRow) getTableRow().getItem();\n setText(item.toString());\n setStyle(\"-fx-background-color: \" + row.getColorAsString());\n // If the statis is changing dynamic you have to add the following:\n row.statusProperty()\n .addListener((observable, oldValue, newValue) -> \n setStyle(\"-fx-background-color: \" + row.getColorAsString()));\n }\n }\n}\n\nWhere TableRow:\npublic class TableRow {\n\n private ObjectProperty<Status> status;\n private Map<Status, Color> statusColor;\n\n public TableRow(Status status, Map<Status, Color> statusColor) {\n this.status = new SimpleObjectProperty<>(status);\n this.statusColor = statusColor;\n }\n\n public Status getStatus() {\n return status.get();\n }\n\n public ObjectProperty<Status> statusProperty() {\n return status;\n }\n\n public Color getStatusColor() {\n return statusColor.get(status.get());\n }\n\n public String getColorAsString() {\n return String.format(\"#%02X%02X%02X\",\n (int) (getStatusColor().getRed() * 255),\n (int) (getStatusColor().getGreen() * 255),\n (int) (getStatusColor().getBlue() * 255));\n }\n}\n\nStatus: \npublic enum Status {\n READY, STARTED, DONE\n}\n\nand the controller:\npublic class TestController {\n\n @FXML\n private TableView<TableRow> table;\n @FXML\n private TableColumn<TableRow, Status> column;\n\n private ObservableList<TableRow> data = FXCollections.observableArrayList();\n\n @FXML\n public void initialize() {\n column.setCellValueFactory(data -> data.getValue().statusProperty());\n column.setCellFactory(factory -> new ColoredStatusTableCell());\n Map<Status, Color> statusColor = new HashMap<>();\n statusColor.put(Status.READY, Color.GREEN);\n statusColor.put(Status.STARTED, Color.YELLOW);\n statusColor.put(Status.DONE, Color.GRAY);\n\n TableRow ready = new TableRow(Status.READY, statusColor);\n TableRow started = new TableRow(Status.STARTED, statusColor);\n TableRow done = new TableRow(Status.DONE, statusColor);\n\n data.addAll(ready, started, done);\n\n table.setItems(data);\n }\n\n}\n\nI chose to set the status as an enum because it is easier to handle it, \nthen I have used a map to each status-color combination, then in the cell you can set its background color to the matched color of the status.\nIf you want of course instead of Color.YELLOW and so on you can use a custom Color.rgb(red,green,blue)\n",
"I finally found the solution without having to use any extra classes, just a callback in my controller class with the help of this SO link:\nStackOverFlow Link\n`\nprivate void populateTable() {\n log.appLog(\"Populating table\\r\\n\");\n //clmStatus.setCellValueFactory(new PropertyValueFactory<>(\"status\"));\n\n clmStatus.setCellFactory(new Callback<TableColumn<Orders, String>,\n TableCell<Orders, String>>()\n {\n @Override\n public TableCell<Orders, String> call(\n TableColumn<Orders, String> param) {\n return new TableCell<Orders, String>() {\n @Override\n protected void updateItem(String item, boolean empty) {\n if (!empty) {\n int currentIndex = indexProperty()\n .getValue() < 0 ? 0\n : indexProperty().getValue();\n String clmStatus = param\n .getTableView().getItems()\n .get(currentIndex).getStatus();\n if (clmStatus.equals(\"READY\")) {\n setTextFill(Color.WHITE);\n setStyle(\"-fx-font-weight: bold\");\n setStyle(\"-fx-background-color: green\");\n setText(clmStatus);\n } else if (clmStatus.equals(\"STARTED\")){\n setTextFill(Color.BLACK);\n setStyle(\"-fx-font-weight: bold\");\n setStyle(\"-fx-background-color: yellow\");\n setText(clmStatus);\n } else if (clmStatus.equals(\"DONE\")){\n setTextFill(Color.BLACK);\n setStyle(\"-fx-font-weight: bold\");\n setStyle(\"-fx-background-color: gray\");\n setText(clmStatus);\n } else {\n setTextFill(Color.WHITE);\n setStyle(\"-fx-font-weight: bold\");\n setStyle(\"-fx-background-color: red\");\n setText(clmStatus);\n }\n }\n }\n };\n }\n });\n\n clmStartDateTime.setCellValueFactory(new PropertyValueFactory<>(\"startDateTime\"));\n clmShopOrder.setCellValueFactory(new PropertyValueFactory<>(\"extra1\"));\n clmRotation.setCellValueFactory(new PropertyValueFactory<>(\"batchLotNr\"));\n clmGMIECode.setCellValueFactory(new PropertyValueFactory<>(\"wareNr\"));\n clmSAPCode.setCellValueFactory(new PropertyValueFactory<>(\"serviceDescription\"));\n clmLineName.setCellValueFactory(new PropertyValueFactory<>(\"productionLineNr\"));\n clmOrderProductionNr.setCellValueFactory(new PropertyValueFactory<>(\"orderProductionNr\"));\n tblOrders.setItems(list);\n }\n`\n\n",
"I don't have badge to comment, but wanted to add some details.\nI wanted to format color of cell based on the boolean value which i have in my data set. I have reviewed this question and similar one provided already here:\nStackoverflow link - style based on another cell in row\nWhat was missing in both for me is reseting style when there is no value as kleopatra mentioned.\nThis works for me:\npublic class TableCellColored extends TableCell<DimensionDtoFxBean, DimValVoFxBean> {\n\n private static final String DEFAULT_STYLE_CLASS = \"table-cell\";\n\n public TableCellColored() {\n super();\n }\n\n @Override\n protected void updateItem(DimValVoFxBean item, boolean empty) {\n super.updateItem(item, empty);\n\n if (empty || item == null) {\n setText(\"\");\n resetStyle();\n return;\n }\n\n setText(Optional.ofNullable(item.getValue()).map(BigDecimal::toString).orElse(\"\"));\n\n Boolean conversionFlag = Optional.ofNullable(item.getConversionFlag()).orElse(true);\n\n updateStyle(conversionFlag);\n\n item.conversionFlagProperty()\n .addListener((observable, oldValue, newValue) -> updateStyle(newValue));\n }\n\n private void updateStyle(Boolean conversionFlag) {\n if (!conversionFlag) {\n setStyle(\"-fx-background-color: red\");\n } else {\n resetStyle();\n }\n }\n\n private void resetStyle() {\n setStyle(\"\");\n getStyleClass().addAll(TableCellColored.DEFAULT_STYLE_CLASS);\n }\n}\n\nSince I have value object with value and boolean flag I can do it i seperate class and don't have add lambda in controller.\nDeafult styling of cell is transparent so if we use style to change color, we have to reset it when there is no value.\nSince direct styling has bigger priority than class it overrides default styling from css classes.\nTo be on the safe side I also apply DEFAULT_STYLE_CLASS. Value taken from TableCell class.\nWithout listener and styles reset I red was staying in table during scrolling. After few scrolls all cells where red. So listener and styles reset is the must have for me.\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"background_color",
"cell",
"javafx",
"tableview"
] |
stackoverflow_0046113170_background_color_cell_javafx_tableview.txt
|
Q:
Why doesn't this conversion to utf8 work?
I have a subprocess command that outputs some characters such as '\xf1'. I'm trying to decode it as utf8 but I get an error.
s = '\xf1'
s.decode('utf-8')
The above throws:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf1 in position 0: unexpected end of data
It works when I use 'latin-1' but shouldn't utf8 work as well? My understanding is that latin1 is a subset of utf8.
Am I missing something here?
EDIT:
print s # ñ
repr(s) # returns "'\\xa9'"
A:
You have confused Unicode with UTF-8. Latin-1 is a subset of Unicode, but it is not a subset of UTF-8. Avoid like the plague ever thinking about individual code units. Just use code points. Do not think about UTF-8. Think about Unicode instead. This is where you are being confused.
Source Code for Demo Program
Using Unicode in Python is very easy. It’s especially with Python 3 and wide builds, the only way I use Python, but you can still use the legacy Python 2 under a narrow build if you are careful about sticking to UTF-8.
To do this, always your source code encoding and your output encoding correctly to UTF-8. Now stop thinking of UTF-anything and use only UTF-8 literals, logical code point numbers, or symbolic character names throughout your Python program.
Here’s the source code with line numbers:
% cat -n /tmp/py
1 #!/usr/bin/env python3.2
2 # -*- coding: UTF-8 -*-
3
4 from __future__ import unicode_literals
5 from __future__ import print_function
6
7 import sys
8 import os
9 import re
10
11 if not (("PYTHONIOENCODING" in os.environ)
12 and
13 re.search("^utf-?8$", os.environ["PYTHONIOENCODING"], re.I)):
14 sys.stderr.write(sys.argv[0] + ": Please set your PYTHONIOENCODING envariable to utf8\n")
15 sys.exit(1)
16
17 print('1a: el ni\xF1o')
18 print('2a: el nin\u0303o')
19
20 print('1a: el niño')
21 print('2b: el niño')
22
23 print('1c: el ni\N{LATIN SMALL LETTER N WITH TILDE}o')
24 print('2c: el nin\N{COMBINING TILDE}o')
And here are print functions with their non-ASCII characters uniquoted using the \x{⋯} notation:
% grep -n ^print /tmp/py | uniquote -x
17:print('1a: el ni\xF1o')
18:print('2a: el nin\u0303o')
20:print('1b: el ni\x{F1}o')
21:print('2b: el nin\x{303}o')
23:print('1c: el ni\N{LATIN SMALL LETTER N WITH TILDE}o')
24:print('2c: el nin\N{COMBINING TILDE}o')
Sample Runs of Demo Program
Here’s a sample run of that program that shows the three different ways (a, b, and c) of doing it: the first set as literals in your source code (which will be subject to StackOverflow’s NFC conversions and so cannot be trusted!!!) and the second two sets with numeric Unicode code points and with symbolic Unicode character names respectively, again uniquoted so you can see what things really are:
% python /tmp/py
1a: el niño
2a: el niño
1b: el niño
2b: el niño
1c: el niño
2c: el niño
% python /tmp/py | uniquote -x
1a: el ni\x{F1}o
2a: el nin\x{303}o
1b: el ni\x{F1}o
2b: el nin\x{303}o
1c: el ni\x{F1}o
2c: el nin\x{303}o
% python /tmp/py | uniquote -v
1a: el ni\N{LATIN SMALL LETTER N WITH TILDE}o
2a: el nin\N{COMBINING TILDE}o
1b: el ni\N{LATIN SMALL LETTER N WITH TILDE}o
2b: el nin\N{COMBINING TILDE}o
1c: el ni\N{LATIN SMALL LETTER N WITH TILDE}o
2c: el nin\N{COMBINING TILDE}o
I really dislike looking at binary, but here is what that looks like as binary bytes:
% python /tmp/py | uniquote -b
1a: el ni\xC3\xB1o
2a: el nin\xCC\x83o
1b: el ni\xC3\xB1o
2b: el nin\xCC\x83o
1c: el ni\xC3\xB1o
2c: el nin\xCC\x83o
The Moral of the Story
Even when you use UTF-8 source, you should think and use only logical Unicode code point numbers (or symbolic named characters), not the individual 8-bit code units that underlie the serial representation of UTF-8 (or for that matter of UTF-16). It is extremely rare to need code units instead of code points, and it just confuses you.
You will also get more reliably behavior if you use a wide build of Python3 than you will get with alternatives to those choices, but that is a UTF-32 matter, not a UTF-8 one. Both UTF-32 and UTF-8 are easy to work with, if you just go with the flow.
A:
UTF-8 is not a subset of Latin-1. UTF-8 encodes ASCII with the same single bytes. For all other code points, it's all multiple bytes.
Put simply, \xf1 is not valid UTF-8, as Python tells you. "Unexpected end of input" indicates that this byte marks the beginning of a multi-byte sequence which is not provided.
I recommend you read up on UTF-8.
A:
My understanding is that latin1 is a subset of utf8.
Wrong. Latin-1, aka ISO 8859-1 (and sometimes erroneously as Windows-1252), is not a subet of UTF-8. ASCII, on the other hand, is a subset of UTF-8. ASCII strings are valid UTF-8 strings, but generalized Windows-1252 or ISO 8859-1 strings are not valid UTF-8, which is why s.decode('UTF-8') is throwing a UnicodeDecodeError.
A:
It's the first byte of a multi-byte sequence in UTF-8, so it's not valid by itself.
In fact, it's the first byte of a 4 byte sequence.
Bits Last code point Byte 1 Byte 2 Byte 3 Byte 4 Byte 5 Byte 6
21 U+1FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
See here for more info.
A:
the easy way (python 3)
s='\xf1'
bytes(s, 'utf-8').decode('utf-8')
#'ñ'
if you are trying decode escaped unicode you can use:
s='Autom\\u00e1tico'
bytes(s, "utf-8").decode('unicode-escape')
#'Automático'
|
Why doesn't this conversion to utf8 work?
|
I have a subprocess command that outputs some characters such as '\xf1'. I'm trying to decode it as utf8 but I get an error.
s = '\xf1'
s.decode('utf-8')
The above throws:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf1 in position 0: unexpected end of data
It works when I use 'latin-1' but shouldn't utf8 work as well? My understanding is that latin1 is a subset of utf8.
Am I missing something here?
EDIT:
print s # ñ
repr(s) # returns "'\\xa9'"
|
[
"You have confused Unicode with UTF-8. Latin-1 is a subset of Unicode, but it is not a subset of UTF-8. Avoid like the plague ever thinking about individual code units. Just use code points. Do not think about UTF-8. Think about Unicode instead. This is where you are being confused.\nSource Code for Demo Program\nUsing Unicode in Python is very easy. It’s especially with Python 3 and wide builds, the only way I use Python, but you can still use the legacy Python 2 under a narrow build if you are careful about sticking to UTF-8. \nTo do this, always your source code encoding and your output encoding correctly to UTF-8. Now stop thinking of UTF-anything and use only UTF-8 literals, logical code point numbers, or symbolic character names throughout your Python program. \nHere’s the source code with line numbers:\n% cat -n /tmp/py\n 1 #!/usr/bin/env python3.2\n 2 # -*- coding: UTF-8 -*-\n 3 \n 4 from __future__ import unicode_literals\n 5 from __future__ import print_function\n 6 \n 7 import sys\n 8 import os\n 9 import re\n 10 \n 11 if not ((\"PYTHONIOENCODING\" in os.environ)\n 12 and\n 13 re.search(\"^utf-?8$\", os.environ[\"PYTHONIOENCODING\"], re.I)):\n 14 sys.stderr.write(sys.argv[0] + \": Please set your PYTHONIOENCODING envariable to utf8\\n\")\n 15 sys.exit(1)\n 16 \n 17 print('1a: el ni\\xF1o')\n 18 print('2a: el nin\\u0303o')\n 19 \n 20 print('1a: el niño')\n 21 print('2b: el niño')\n 22 \n 23 print('1c: el ni\\N{LATIN SMALL LETTER N WITH TILDE}o')\n 24 print('2c: el nin\\N{COMBINING TILDE}o')\n\nAnd here are print functions with their non-ASCII characters uniquoted using the \\x{⋯} notation:\n% grep -n ^print /tmp/py | uniquote -x\n17:print('1a: el ni\\xF1o')\n18:print('2a: el nin\\u0303o')\n20:print('1b: el ni\\x{F1}o')\n21:print('2b: el nin\\x{303}o')\n23:print('1c: el ni\\N{LATIN SMALL LETTER N WITH TILDE}o')\n24:print('2c: el nin\\N{COMBINING TILDE}o')\n\nSample Runs of Demo Program\nHere’s a sample run of that program that shows the three different ways (a, b, and c) of doing it: the first set as literals in your source code (which will be subject to StackOverflow’s NFC conversions and so cannot be trusted!!!) and the second two sets with numeric Unicode code points and with symbolic Unicode character names respectively, again uniquoted so you can see what things really are:\n% python /tmp/py\n1a: el niño\n2a: el niño\n1b: el niño\n2b: el niño\n1c: el niño\n2c: el niño\n\n% python /tmp/py | uniquote -x\n1a: el ni\\x{F1}o\n2a: el nin\\x{303}o\n1b: el ni\\x{F1}o\n2b: el nin\\x{303}o\n1c: el ni\\x{F1}o\n2c: el nin\\x{303}o\n\n% python /tmp/py | uniquote -v\n1a: el ni\\N{LATIN SMALL LETTER N WITH TILDE}o\n2a: el nin\\N{COMBINING TILDE}o\n1b: el ni\\N{LATIN SMALL LETTER N WITH TILDE}o\n2b: el nin\\N{COMBINING TILDE}o\n1c: el ni\\N{LATIN SMALL LETTER N WITH TILDE}o\n2c: el nin\\N{COMBINING TILDE}o\n\nI really dislike looking at binary, but here is what that looks like as binary bytes:\n% python /tmp/py | uniquote -b\n1a: el ni\\xC3\\xB1o\n2a: el nin\\xCC\\x83o\n1b: el ni\\xC3\\xB1o\n2b: el nin\\xCC\\x83o\n1c: el ni\\xC3\\xB1o\n2c: el nin\\xCC\\x83o\n\nThe Moral of the Story\nEven when you use UTF-8 source, you should think and use only logical Unicode code point numbers (or symbolic named characters), not the individual 8-bit code units that underlie the serial representation of UTF-8 (or for that matter of UTF-16). It is extremely rare to need code units instead of code points, and it just confuses you.\nYou will also get more reliably behavior if you use a wide build of Python3 than you will get with alternatives to those choices, but that is a UTF-32 matter, not a UTF-8 one. Both UTF-32 and UTF-8 are easy to work with, if you just go with the flow.\n",
"UTF-8 is not a subset of Latin-1. UTF-8 encodes ASCII with the same single bytes. For all other code points, it's all multiple bytes.\nPut simply, \\xf1 is not valid UTF-8, as Python tells you. \"Unexpected end of input\" indicates that this byte marks the beginning of a multi-byte sequence which is not provided.\nI recommend you read up on UTF-8.\n",
"\nMy understanding is that latin1 is a subset of utf8.\n\nWrong. Latin-1, aka ISO 8859-1 (and sometimes erroneously as Windows-1252), is not a subet of UTF-8. ASCII, on the other hand, is a subset of UTF-8. ASCII strings are valid UTF-8 strings, but generalized Windows-1252 or ISO 8859-1 strings are not valid UTF-8, which is why s.decode('UTF-8') is throwing a UnicodeDecodeError.\n",
"It's the first byte of a multi-byte sequence in UTF-8, so it's not valid by itself.\nIn fact, it's the first byte of a 4 byte sequence.\nBits Last code point Byte 1 Byte 2 Byte 3 Byte 4 Byte 5 Byte 6\n21 U+1FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\nSee here for more info.\n",
"the easy way (python 3)\ns='\\xf1'\nbytes(s, 'utf-8').decode('utf-8')\n#'ñ'\n\nif you are trying decode escaped unicode you can use:\ns='Autom\\\\u00e1tico'\nbytes(s, \"utf-8\").decode('unicode-escape')\n#'Automático'\n\n"
] |
[
9,
4,
1,
1,
0
] |
[] |
[] |
[
"encoding",
"python",
"unicode",
"utf_8"
] |
stackoverflow_0007163485_encoding_python_unicode_utf_8.txt
|
Q:
Remove :any from component in React
I am starting with React. I am trying to send a var and function to my component. I know that it is a bad practice to use :any that is why I want to change for a proper way.
I am doing a modal and I am sending the data to my component this way. I am using useState
Datatable.tsx
import { useEffect, useMemo, useState } from "react";
import Modal from "../modal/Modal";
const Datatable = () => {
const [show, setShow] = useState<boolean>(false);
return (
<div>
<Modal show={show} closeModal={() => setShow(false)} />
<button onClick={() =>setShow((s) => !s)}>
Open Modal
</button>
<tableStuff/>
<div/>
);
Modal.tsx
import "./modal.scss";
import React from "react";
import ReactDOM from "react-dom";
const Modal = (props:any) => {
const portal = document.getElementById("portal");
if (!portal) {
return null;
}
if (!props.show) {
return null;
}
return ReactDOM.createPortal(
<>
<div className="modal" onClick={props.closeModal}>
<div className="content">
<h2>Simple modal</h2>
</div>
</div>
</>,
portal
);
};
export default Modal;
I have seen this on tons of videos, but the following piece of code does not work for me.
I am getting this error Binding element 'show' implicitly has an 'any' type and Binding element 'closeModal' implicitly has an 'any' type
//...
const Modal = ({show, closeModal}) => {
if (show) {
return null;
}
//...
return ReactDOM.createPortal(
<>
<div className="modals" onClick={closeModal}>
<button onClick={closeModal}>Close</button>
</div>
</>,
portal
);
}
Is something else I am missing in order to not use (props:any)? Any help or suggestion would be nice.
A:
interface ModalProps {
show: boolean;
closeModal: () => void;
}
const Modal = ({show, closeModal}: ModalProps) => {
|
Remove :any from component in React
|
I am starting with React. I am trying to send a var and function to my component. I know that it is a bad practice to use :any that is why I want to change for a proper way.
I am doing a modal and I am sending the data to my component this way. I am using useState
Datatable.tsx
import { useEffect, useMemo, useState } from "react";
import Modal from "../modal/Modal";
const Datatable = () => {
const [show, setShow] = useState<boolean>(false);
return (
<div>
<Modal show={show} closeModal={() => setShow(false)} />
<button onClick={() =>setShow((s) => !s)}>
Open Modal
</button>
<tableStuff/>
<div/>
);
Modal.tsx
import "./modal.scss";
import React from "react";
import ReactDOM from "react-dom";
const Modal = (props:any) => {
const portal = document.getElementById("portal");
if (!portal) {
return null;
}
if (!props.show) {
return null;
}
return ReactDOM.createPortal(
<>
<div className="modal" onClick={props.closeModal}>
<div className="content">
<h2>Simple modal</h2>
</div>
</div>
</>,
portal
);
};
export default Modal;
I have seen this on tons of videos, but the following piece of code does not work for me.
I am getting this error Binding element 'show' implicitly has an 'any' type and Binding element 'closeModal' implicitly has an 'any' type
//...
const Modal = ({show, closeModal}) => {
if (show) {
return null;
}
//...
return ReactDOM.createPortal(
<>
<div className="modals" onClick={closeModal}>
<button onClick={closeModal}>Close</button>
</div>
</>,
portal
);
}
Is something else I am missing in order to not use (props:any)? Any help or suggestion would be nice.
|
[
"interface ModalProps {\n show: boolean;\n closeModal: () => void;\n}\n\nconst Modal = ({show, closeModal}: ModalProps) => {\n\n"
] |
[
2
] |
[] |
[] |
[
"javascript",
"react_component",
"react_props",
"reactjs",
"typescript"
] |
stackoverflow_0074662231_javascript_react_component_react_props_reactjs_typescript.txt
|
Q:
Implementing the Fibonacci sequence for the last n elements: The nBonacci sequence
I was curious about how I can implement the Fibonacci sequence for summing the last n elements instead of just the last 2. So I was thinking about implementing a function nBonacci(n,m) where n is the number of last elements we gotta sum, and m is the number of elements in this list.
The Fibonacci sequence starts with 2 ones, and each following element is the sum of the 2 previous numbers.
Let's make a generalization: The nBonacci sequence starts with n ones, and each following element is the sum of the previous n numbers.
I want to define the nBonacci function that takes the positive integer n and a positive integer m, with m>n, and returns a list with the first m elements of the nBonacci sequence corresponding to the value n.
For example, nBonacci(3,8) should return the list [1, 1, 1, 3, 5, 9, 17, 31].
def fib(num):
a = 0
b = 1
while b <= num:
prev_a = a
a = b
b = prev_a +b
The problem is that I don't know the number of times I gotta sum. Does anyone have an idea and a suggestion of resolution?
A:
The nBonacci sequence will always have to start with n ones, or the sequence could never start. Therefore, we can just take advantage of the range() function and slice the existing list:
def nfib(n, m):
lst = [1] * n
for i in range(n, m):
lst.append(sum(lst[i-n:i]))
return lst
print(nfib(3, 8)) # => [1, 1, 1, 3, 5, 9, 17, 31]
A:
If you wanted to the fibonacci sequence recursively, you could do
def fib(x, y, l):
if len(l) == y:
return l
return fib(x, y, l + [sum(l[-x:])])
num = 3
print(fib(num, 8, [1 for _ in range(num)])) #[1, 1, 1, 3, 5, 9, 17, 31]
|
Implementing the Fibonacci sequence for the last n elements: The nBonacci sequence
|
I was curious about how I can implement the Fibonacci sequence for summing the last n elements instead of just the last 2. So I was thinking about implementing a function nBonacci(n,m) where n is the number of last elements we gotta sum, and m is the number of elements in this list.
The Fibonacci sequence starts with 2 ones, and each following element is the sum of the 2 previous numbers.
Let's make a generalization: The nBonacci sequence starts with n ones, and each following element is the sum of the previous n numbers.
I want to define the nBonacci function that takes the positive integer n and a positive integer m, with m>n, and returns a list with the first m elements of the nBonacci sequence corresponding to the value n.
For example, nBonacci(3,8) should return the list [1, 1, 1, 3, 5, 9, 17, 31].
def fib(num):
a = 0
b = 1
while b <= num:
prev_a = a
a = b
b = prev_a +b
The problem is that I don't know the number of times I gotta sum. Does anyone have an idea and a suggestion of resolution?
|
[
"The nBonacci sequence will always have to start with n ones, or the sequence could never start. Therefore, we can just take advantage of the range() function and slice the existing list:\ndef nfib(n, m):\n lst = [1] * n\n for i in range(n, m):\n lst.append(sum(lst[i-n:i]))\n return lst\n\n\nprint(nfib(3, 8)) # => [1, 1, 1, 3, 5, 9, 17, 31]\n\n",
"If you wanted to the fibonacci sequence recursively, you could do\ndef fib(x, y, l):\n if len(l) == y:\n return l\n return fib(x, y, l + [sum(l[-x:])])\n\n\nnum = 3\nprint(fib(num, 8, [1 for _ in range(num)])) #[1, 1, 1, 3, 5, 9, 17, 31]\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"fibonacci",
"iteration",
"python"
] |
stackoverflow_0074662150_fibonacci_iteration_python.txt
|
Q:
"input expected at most 1 arguments, got 2"
I'm trying to create a function that will prompt the user to give a radius for each circle that they have designated as having, however, I can't seem to figure out how to display it without running into the TypeError: input expected at most 1 arguments, got 2
def GetRadius():
NUM_CIRCLES = eval(input("Enter the number of circles: "))
for i in range(NUM_CIRCLES):
Radius = eval(input("Enter the radius of circle #", i + 1))
GetRadius()
A:
That's because you gave it a second argument. You can only give it the string you want to see displayed. This isn't a free-form print statement. Try this:
Radius = eval(input("Enter the radius of circle #" + str(i + 1)))
This gives you a single string value to send to input.
Also, be very careful with using eval.
A:
input only takes one argument, if you want to create a string with your i value you can use
Radius = eval(input("Enter the radius of circle #{} ".format(i + 1)))
Also it is very dangerous to use eval to blindly execute user input.
A:
TypeError: input expected at most 1 arguments, got 2
Thats because you provided two arguments for input function but it expects one argument (yeah I rephrased error message...).
Anyway, use this:
Radius = float(input("Enter the radius of circle #" + str(i + 1)))
Don't use eval for this. (Other answer explains why)
For future issues, it's worth using help function from within python interpreter. Try help(input) in python interpreter.
A:
In golang I got the exact same error using database/sql when I tried this code:
err := db.QueryRow("SELECT ... WHERE field=$1 ", field, field2).Scan(&count)
if err != nil {
return false, err
}
it turns out the solution was to do add 1 parameter instead of 2 parameters to the varargs of the function.
so the solution was this:
err := db.QueryRow("SELECT ... WHERE field=$1 ", field).Scan(&count)
// notice field2 is missing here
if err != nil {
return false, err
}
I hope this helps anyone, particularly since this is the first google result when googling this issue.
also guys, always provide context to your errors.
HTH
|
"input expected at most 1 arguments, got 2"
|
I'm trying to create a function that will prompt the user to give a radius for each circle that they have designated as having, however, I can't seem to figure out how to display it without running into the TypeError: input expected at most 1 arguments, got 2
def GetRadius():
NUM_CIRCLES = eval(input("Enter the number of circles: "))
for i in range(NUM_CIRCLES):
Radius = eval(input("Enter the radius of circle #", i + 1))
GetRadius()
|
[
"That's because you gave it a second argument. You can only give it the string you want to see displayed. This isn't a free-form print statement. Try this:\nRadius = eval(input(\"Enter the radius of circle #\" + str(i + 1)))\n\nThis gives you a single string value to send to input.\nAlso, be very careful with using eval.\n",
"input only takes one argument, if you want to create a string with your i value you can use\nRadius = eval(input(\"Enter the radius of circle #{} \".format(i + 1)))\n\nAlso it is very dangerous to use eval to blindly execute user input.\n",
"\nTypeError: input expected at most 1 arguments, got 2\n\nThats because you provided two arguments for input function but it expects one argument (yeah I rephrased error message...).\nAnyway, use this:\nRadius = float(input(\"Enter the radius of circle #\" + str(i + 1)))\n\nDon't use eval for this. (Other answer explains why)\nFor future issues, it's worth using help function from within python interpreter. Try help(input) in python interpreter. \n",
"In golang I got the exact same error using database/sql when I tried this code:\n err := db.QueryRow(\"SELECT ... WHERE field=$1 \", field, field2).Scan(&count)\n if err != nil {\n return false, err\n }\n\nit turns out the solution was to do add 1 parameter instead of 2 parameters to the varargs of the function.\nso the solution was this:\n err := db.QueryRow(\"SELECT ... WHERE field=$1 \", field).Scan(&count)\n // notice field2 is missing here\n if err != nil {\n return false, err\n }\n\nI hope this helps anyone, particularly since this is the first google result when googling this issue.\nalso guys, always provide context to your errors.\nHTH\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0043243627_python_python_3.x.txt
|
Q:
Hibernate 6 mapping without annotations
Up to Hibernate 5 the class mapping can be defined either by using JPA annotations or with an XML file. The XML file is convenient because it isn't tied to the class, which means it's possible to:
map a class even if you don't have the source code
map a class differently depending on the context (a class may be mapped one way on the server, and another way on the client)
Hibernate 6 removed the XML mapping. Is there an alternative method to define a mapping without adding annotations to the persisted classes?
A:
Unless I missed something hbm XML mappings are still in Hibernate 6 but now they are officially deprecated: https://docs.jboss.org/hibernate/orm/6.0/migration-guide/migration-guide.html#_deprecation_of_hbm_xml_mappings
A:
We now recommend the use of the standard JPA ORM mapping format, which is orm.xml.
For Hibernate-specific extensions to the orm.xml format you can find mapping-3.1.0.xsd here:
https://hibernate.org/xsd/orm/mapping/mapping-3.1.0.xsd
I guess this is what you're looking for.
|
Hibernate 6 mapping without annotations
|
Up to Hibernate 5 the class mapping can be defined either by using JPA annotations or with an XML file. The XML file is convenient because it isn't tied to the class, which means it's possible to:
map a class even if you don't have the source code
map a class differently depending on the context (a class may be mapped one way on the server, and another way on the client)
Hibernate 6 removed the XML mapping. Is there an alternative method to define a mapping without adding annotations to the persisted classes?
|
[
"Unless I missed something hbm XML mappings are still in Hibernate 6 but now they are officially deprecated: https://docs.jboss.org/hibernate/orm/6.0/migration-guide/migration-guide.html#_deprecation_of_hbm_xml_mappings\n",
"We now recommend the use of the standard JPA ORM mapping format, which is orm.xml.\nFor Hibernate-specific extensions to the orm.xml format you can find mapping-3.1.0.xsd here:\nhttps://hibernate.org/xsd/orm/mapping/mapping-3.1.0.xsd\nI guess this is what you're looking for.\n"
] |
[
2,
1
] |
[] |
[] |
[
"hibernate",
"nhibernate_mapping"
] |
stackoverflow_0074218546_hibernate_nhibernate_mapping.txt
|
Q:
How to send an email from GitLab CI pipeline's job?
I am trying to set up a GitLab CI configuration that sends an email after a pipeline's job completes with a link of the artifacts to the upload site. The pipeline builds based upon pom.xml, then tests with sonarqube and then uploads the artifacts using curl to a specific artifactory location. The folder structure and link of the artifact directory depends upon the CI_PIPELINE_ID. After all of these succeeds, I need to send this link for downloading the artifacts to a list of people via mail. My .gitlab-config.yml looks like the following:
image: maven:3.3.9-jdk-8
variables:
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true"
MAVEN_CLI_OPTS: "-U --batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=true -DdeployAtEnd=true"
REPO_NAME: "<artifactory url>"
cache:
paths:
- .m2/repository
- ./target/
stages:
- build
compile_commit:
stage: build
only:
- cr_integrate
before_script:
- git submodule sync --recursive
- git submodule update --init --recursive --remote
script:
- mvn -f pom.xml -s settings.xml $MAVEN_CLI_OPTS clean install $MAVEN_OPTS
- curl -i -u<username>:<token> -T "target/<artifact-1>.zip" "${REPO_NAME}/${CI_PIPELINE_ID}/<artifact-1>.zip"
- curl -i -u<username>:<token> -T "target/<artifact-1>.zip" "${REPO_NAME}/${CI_PIPELINE_ID}/<artifact-2>.zip"
- - curl -i -u<username>:<token> -T "target/<artifact-1>.zip" "${REPO_NAME}/${CI_PIPELINE_ID}/<artifact-3>.zip"
tags:
- <tagname>
How do I send a mail to some people after this with the link?
A:
I built a solution for this, sharing it here.
The following tools were used for this:
GitLab release api
Python-GitLab api
Docker
Microsoft Teams
Sharepoint
The process flow can be outlined as follows:
A new pipeline is triggered
After successful build, codescan and publish, a release job is run
The release job uses a python script written with the help of
python-gitlab api to create a release using gitlab release api. It
inserts external artifactory links for downloading artifacts under
release assets and adds links to release note and other documents.
GitLab sends a release mail to the appropriate notification channel,
a group email id created by Microsoft Teams and Sharepoint, so that
the entire team receives the release mail.
The python script is given below:
import os
import gitlab
from datetime import datetime
if __name__ == '__main__':
access_token = os.environ['RELEASE_TOKEN']
gitlab_url = os.environ['GITLAB_URL']
project_id = int(os.environ['CI_PROJECT_ID'])
tag_name = os.environ['CI_PIPELINE_ID']
ref = os.environ['CI_COMMIT_REF_NAME']
# artifactory_links
artifactory_link = os.environ['ARTIFACTORY_PATH']
group_name = os.environ['GROUP_NAME']
project_name = os.environ['CI_PROJECT_NAME']
directory = f'{datetime.now():%Y%m%d}'
artifact_name = os.environ['ARTIFACT_NAME']
package_type = os.environ['PACKAGE_TYPE']
# artifacts_links
artifacts_links = f'{artifactory_link}/{group_name}/{project_name}/{directory}/{artifact_name}-{tag_name}.{package_type}'
# release note
release_note = os.environ['RELEASE_NOTE']
# authenticate with gitlab
gl = gitlab.Gitlab(gitlab_url, private_token=access_token)
gl.auth()
# obtain the project object by id
project = gl.projects.get(project_id)
# creating the project tags
project.tags.create({'tag_name': tag_name, 'ref': ref})
# creating the project releases
release = project.releases.create(
{
'name': f'Release for Pipeline ID {ref}',
'tag_name': tag_name,
'description': release_note,
'assets': {
'links': [{'name': artifact_name, 'url': artifacts_links}],
}
}
)
The script requires the following environment variables:
RELEASE_TOKEN – GitLab access token
GITLAB_URL – GitLab base URL.
ARTIFACTORY_PATH – Artifactory base URL.
GROUP_NAME – In case the project is under a group.
ARTIFACT_NAME – The artifact name
PACKAGE_TYPE – Artifact package type
RELEASE_NOTE – Link to release note and any other document.
These variables can be provided as GitLab CI variables. If there are more than one artifacts, the python script can be modified accordingly.
Since the python script needs to be called during the pipeline event and adding the script in the project would be modifying the project codebase, dockerizing the script is the best solution. That way, it can be pulled directly from docker hub. The dockerfile contents for this are as follows:
FROM python:3.7-alpine
COPY release_api.py /bin
RUN pip install python-gitlab
ENTRYPOINT ["/bin/release_api.py"]
CMD ["/bin/bash"]
In order to send a release mail to every member of the team, irrespective of their individual GitLab notification and subscription preferences, a team needs to be set up using Microsoft Teams. When a team is created in Teams application, a corresponding sharepoint site is created, along with a team email id. This set up takes some time.
Once a team is created, under Files section, there’s an option to open it in sharepoint (screenshot below).
The sharepoint site has a link in the left sidebar called Conversations. Once the sharepoint site is fully ready, clicking this link will open the inbox of the Teams email.
Under the settings for the group, the option Edit Group can be found and there the group email id can be found. This group email id will be used to send the release mail to everyone in the team.
Under user settings of GitLab, the group email needs to be added. Once the mail is added and verified, the notification channel can be set up under Notifications. Once this is done, all notifications for that group (or project) will go to the group mail, and everyone in the team will get them. The last activity left is to set up notification preference to send a notification when a new release is available.
A:
The gitlab script line below can be used to send email. You will need to have the ssmtp linux program which I suggest building a docker container and installing the ssmtp dependency. Personally I went with an API, but that has its own problems. What's nice about this solution is you are using core protocols and can build the email message in plain-text.
image: registry.gitlab.com/gitlab-group/dev-ops/REFERENCE-TO-IMAGE-OF-DOCKERFILE-BELOW
script:
- | # Build the core smtp configuration
echo "[email protected]" > /etc/ssmtp/ssmtp.conf
echo "mailhub=EMAIL_SERVER:EMAIL_SERVER_PORT" >> /etc/ssmtp/ssmtp.conf
echo "FromLineOverride=YES" >> /etc/ssmtp/ssmtp.conf
echo "AuthUser=EMAIL_SERVER_USERNAME" >> /etc/ssmtp/ssmtp.conf
echo "AuthPass=EMAIL_SERVER_PASSWORD" >> /etc/ssmtp/ssmtp.conf
echo "UseTLS=false" >> /etc/ssmtp/ssmtp.conf
echo "Debug=YES" >> /etc/ssmtp/ssmtp.conf
- "echo 'From: [email protected]' > msg.txt" # Build the message
- echo "EMAIL SUBJECT" >> msg.txt
- echo "" >> msg.txt
- echo "EMAIL BODY" >> msg.txt
- ssmtp [email protected] < msg.txt # Send the email
Here's a Dockerfile that you can use to get your ssmtp dependency
FROM alpine:3.9
RUN apk add --update --no-cache \
bash=4.4.19-r1 \
ssmtp \
|
How to send an email from GitLab CI pipeline's job?
|
I am trying to set up a GitLab CI configuration that sends an email after a pipeline's job completes with a link of the artifacts to the upload site. The pipeline builds based upon pom.xml, then tests with sonarqube and then uploads the artifacts using curl to a specific artifactory location. The folder structure and link of the artifact directory depends upon the CI_PIPELINE_ID. After all of these succeeds, I need to send this link for downloading the artifacts to a list of people via mail. My .gitlab-config.yml looks like the following:
image: maven:3.3.9-jdk-8
variables:
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true"
MAVEN_CLI_OPTS: "-U --batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=true -DdeployAtEnd=true"
REPO_NAME: "<artifactory url>"
cache:
paths:
- .m2/repository
- ./target/
stages:
- build
compile_commit:
stage: build
only:
- cr_integrate
before_script:
- git submodule sync --recursive
- git submodule update --init --recursive --remote
script:
- mvn -f pom.xml -s settings.xml $MAVEN_CLI_OPTS clean install $MAVEN_OPTS
- curl -i -u<username>:<token> -T "target/<artifact-1>.zip" "${REPO_NAME}/${CI_PIPELINE_ID}/<artifact-1>.zip"
- curl -i -u<username>:<token> -T "target/<artifact-1>.zip" "${REPO_NAME}/${CI_PIPELINE_ID}/<artifact-2>.zip"
- - curl -i -u<username>:<token> -T "target/<artifact-1>.zip" "${REPO_NAME}/${CI_PIPELINE_ID}/<artifact-3>.zip"
tags:
- <tagname>
How do I send a mail to some people after this with the link?
|
[
"I built a solution for this, sharing it here.\nThe following tools were used for this:\n\nGitLab release api\nPython-GitLab api\nDocker\nMicrosoft Teams\nSharepoint\n\nThe process flow can be outlined as follows:\n\nA new pipeline is triggered\nAfter successful build, codescan and publish, a release job is run\nThe release job uses a python script written with the help of\npython-gitlab api to create a release using gitlab release api. It\ninserts external artifactory links for downloading artifacts under\nrelease assets and adds links to release note and other documents.\nGitLab sends a release mail to the appropriate notification channel,\na group email id created by Microsoft Teams and Sharepoint, so that\nthe entire team receives the release mail.\n\nThe python script is given below:\nimport os\nimport gitlab\nfrom datetime import datetime\n\nif __name__ == '__main__':\n access_token = os.environ['RELEASE_TOKEN']\n gitlab_url = os.environ['GITLAB_URL']\n project_id = int(os.environ['CI_PROJECT_ID'])\n \n tag_name = os.environ['CI_PIPELINE_ID']\n ref = os.environ['CI_COMMIT_REF_NAME']\n \n # artifactory_links\n artifactory_link = os.environ['ARTIFACTORY_PATH']\n group_name = os.environ['GROUP_NAME']\n project_name = os.environ['CI_PROJECT_NAME']\n directory = f'{datetime.now():%Y%m%d}'\n artifact_name = os.environ['ARTIFACT_NAME']\n package_type = os.environ['PACKAGE_TYPE']\n \n # artifacts_links\n artifacts_links = f'{artifactory_link}/{group_name}/{project_name}/{directory}/{artifact_name}-{tag_name}.{package_type}'\n \n # release note\n release_note = os.environ['RELEASE_NOTE']\n \n # authenticate with gitlab\n gl = gitlab.Gitlab(gitlab_url, private_token=access_token)\n gl.auth()\n \n # obtain the project object by id\n project = gl.projects.get(project_id)\n \n # creating the project tags\n project.tags.create({'tag_name': tag_name, 'ref': ref})\n \n # creating the project releases\n release = project.releases.create(\n {\n 'name': f'Release for Pipeline ID {ref}',\n 'tag_name': tag_name,\n 'description': release_note,\n 'assets': {\n 'links': [{'name': artifact_name, 'url': artifacts_links}],\n }\n }\n )\n\nThe script requires the following environment variables:\n\nRELEASE_TOKEN – GitLab access token\nGITLAB_URL – GitLab base URL.\nARTIFACTORY_PATH – Artifactory base URL.\nGROUP_NAME – In case the project is under a group.\nARTIFACT_NAME – The artifact name\nPACKAGE_TYPE – Artifact package type\nRELEASE_NOTE – Link to release note and any other document.\n\nThese variables can be provided as GitLab CI variables. If there are more than one artifacts, the python script can be modified accordingly.\nSince the python script needs to be called during the pipeline event and adding the script in the project would be modifying the project codebase, dockerizing the script is the best solution. That way, it can be pulled directly from docker hub. The dockerfile contents for this are as follows:\nFROM python:3.7-alpine\nCOPY release_api.py /bin\nRUN pip install python-gitlab\nENTRYPOINT [\"/bin/release_api.py\"]\nCMD [\"/bin/bash\"]\n\nIn order to send a release mail to every member of the team, irrespective of their individual GitLab notification and subscription preferences, a team needs to be set up using Microsoft Teams. When a team is created in Teams application, a corresponding sharepoint site is created, along with a team email id. This set up takes some time.\nOnce a team is created, under Files section, there’s an option to open it in sharepoint (screenshot below).\n\nThe sharepoint site has a link in the left sidebar called Conversations. Once the sharepoint site is fully ready, clicking this link will open the inbox of the Teams email.\nUnder the settings for the group, the option Edit Group can be found and there the group email id can be found. This group email id will be used to send the release mail to everyone in the team.\nUnder user settings of GitLab, the group email needs to be added. Once the mail is added and verified, the notification channel can be set up under Notifications. Once this is done, all notifications for that group (or project) will go to the group mail, and everyone in the team will get them. The last activity left is to set up notification preference to send a notification when a new release is available.\n\n",
"The gitlab script line below can be used to send email. You will need to have the ssmtp linux program which I suggest building a docker container and installing the ssmtp dependency. Personally I went with an API, but that has its own problems. What's nice about this solution is you are using core protocols and can build the email message in plain-text.\n image: registry.gitlab.com/gitlab-group/dev-ops/REFERENCE-TO-IMAGE-OF-DOCKERFILE-BELOW\n script:\n - | # Build the core smtp configuration\n echo \"[email protected]\" > /etc/ssmtp/ssmtp.conf\n echo \"mailhub=EMAIL_SERVER:EMAIL_SERVER_PORT\" >> /etc/ssmtp/ssmtp.conf\n echo \"FromLineOverride=YES\" >> /etc/ssmtp/ssmtp.conf\n echo \"AuthUser=EMAIL_SERVER_USERNAME\" >> /etc/ssmtp/ssmtp.conf\n echo \"AuthPass=EMAIL_SERVER_PASSWORD\" >> /etc/ssmtp/ssmtp.conf\n echo \"UseTLS=false\" >> /etc/ssmtp/ssmtp.conf\n echo \"Debug=YES\" >> /etc/ssmtp/ssmtp.conf\n - \"echo 'From: [email protected]' > msg.txt\" # Build the message\n - echo \"EMAIL SUBJECT\" >> msg.txt\n - echo \"\" >> msg.txt\n - echo \"EMAIL BODY\" >> msg.txt\n - ssmtp [email protected] < msg.txt # Send the email\n\nHere's a Dockerfile that you can use to get your ssmtp dependency\nFROM alpine:3.9\n\nRUN apk add --update --no-cache \\\n bash=4.4.19-r1 \\\n ssmtp \\\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"continuous_integration",
"gitlab",
"gitlab_ci",
"pipeline"
] |
stackoverflow_0059703155_continuous_integration_gitlab_gitlab_ci_pipeline.txt
|
Q:
error: 'to' is not a member of 'std::ranges'
Facing issue
std::ranges::to
I am executing the below example from https://en.cppreference.com/w/cpp/ranges/to
#include <algorithm>
#include <concepts>
#include <iostream>
#include <ranges>
#include <vector>
int main()
{
auto vec = std::views::iota(1, 5)
| std::views::transform([](auto const v){ return v * 2; })
| std::ranges::to<std::vector>();
static_assert(std::same_as<decltype(vec), std::vector<int>>);
std::ranges::for_each(vec, [](auto const v){ std::cout << v << ' '; });
}
But getting a error
main.cpp: In function 'int main()':
main.cpp:11:29: error: 'to' is not a member of 'std::ranges'
11 | | std::ranges::to<std::vector>();
| ^~
main.cpp:11:43: error: missing template arguments before '>' token
11 | | std::ranges::to<std::vector>();
| ^
main.cpp:11:45: error: expected primary-expression before ')' token
11 | | std::ranges::to<std::vector>();
| ^
main.cpp:13:24: error: template argument 1 is invalid
13 | static_assert(std::same_as<decltype(vec), std::vector<int>>);
https://coliru.stacked-crooked.com/view?id=8fdd3554af82ef24
I am using the compiler C++23
A:
This is because std::ranges::to is only supported right now by MSVC 19.34
You can check on the status of compiler support for language and library features here: https://en.cppreference.com/w/cpp/compiler_support
For example this feature is listed un the C++23 library section as
C++23 feature
Paper(s)
ranges::to()
P1206R7
|
error: 'to' is not a member of 'std::ranges'
|
Facing issue
std::ranges::to
I am executing the below example from https://en.cppreference.com/w/cpp/ranges/to
#include <algorithm>
#include <concepts>
#include <iostream>
#include <ranges>
#include <vector>
int main()
{
auto vec = std::views::iota(1, 5)
| std::views::transform([](auto const v){ return v * 2; })
| std::ranges::to<std::vector>();
static_assert(std::same_as<decltype(vec), std::vector<int>>);
std::ranges::for_each(vec, [](auto const v){ std::cout << v << ' '; });
}
But getting a error
main.cpp: In function 'int main()':
main.cpp:11:29: error: 'to' is not a member of 'std::ranges'
11 | | std::ranges::to<std::vector>();
| ^~
main.cpp:11:43: error: missing template arguments before '>' token
11 | | std::ranges::to<std::vector>();
| ^
main.cpp:11:45: error: expected primary-expression before ')' token
11 | | std::ranges::to<std::vector>();
| ^
main.cpp:13:24: error: template argument 1 is invalid
13 | static_assert(std::same_as<decltype(vec), std::vector<int>>);
https://coliru.stacked-crooked.com/view?id=8fdd3554af82ef24
I am using the compiler C++23
|
[
"This is because std::ranges::to is only supported right now by MSVC 19.34\nYou can check on the status of compiler support for language and library features here: https://en.cppreference.com/w/cpp/compiler_support\nFor example this feature is listed un the C++23 library section as\n\n\n\n\nC++23 feature\nPaper(s)\n\n\n\n\nranges::to()\nP1206R7\n\n\n\n"
] |
[
4
] |
[] |
[] |
[
"c++",
"c++23"
] |
stackoverflow_0074662221_c++_c++23.txt
|
Q:
My react project is showing white blank screen with the use of api to get data from the back in react
I have already done the back and front of the project but when I am trying to get a data from the back with the use of useFetch, it shows me white blank space.
I have tried all my best to get data from the back through the use of the api but it just showing me blank. When I remove the useFetch method, everything works well.
useFetch.js
import { useEffect, useState } from "react"
import axios from "axios";
const useFetch = (url) => {
const [data, setData] = useState([])
const [loading, setLoading] = useState([false])
const [error, setError] = useState([false])
useEffect(()=>{
const fetchData = async ()=>{
setLoading(true)
try{
const res = await axios.get(url);
setData(res.data);
}catch(err){
setError(err)
}
setLoading(false)
};
fetchData();
},[url])
const reFetch = async ()=>{
setLoading(true)
try{
const res = await axios.get(url);
setData(res.data);
}catch(err){
setError(err)
}
setLoading(false)
};
return { data, loading, error, reFetch}
};
export default useFetch;
featured.js
import useFetch from "../../hooks/useFetch";
import "./featured.css";
const Featured = () => {
const { data, loading, error } = useFetch(
"/hotels/countByCity?cities=freetown,makeni,bo"
);
return (
<div className="featured">
<div className="featuredItem">
<img
src="https://tourismsierraleone.com/wp-content/uploads/2021/08/Freetown2.jpg"
alt=""
className="featuredImg"
/>
<div className="featuredTitles">
<h1>Freetown</h1>
<h2>20 properties</h2>
</div>
</div>
<div className="featuredItem">
<img
src="https://upload.wikimedia.org/wikipedia/commons/c/c0/Makeni_Wusum.JPG"
alt=""
className="featuredImg"
/>
<div className="featuredTitles">
<h1>Makeni</h1>
<h2>50 properties</h2>
</div>
</div>
<div className="featuredItem">
<img
src="https://www.visitsierraleone.org/wp-content/uploads/2021/08/doha-1.jpg"
alt=""
className="featuredImg"
/>
<div className="featuredTitles">
<h1>Bo</h1>
<h2>35 properties</h2>
</div>
</div>
</div>
);
};
export default Featured;
A:
try this :
const [data, setData] = useState()
const [loading, setLoading] = useState(false)
const [error, setError] = useState(false)
useEffect(()=>{
const fetchData = async ()=>{
setLoading(true)
try{
const res = await axios.get(url);
setData(res.data);
}catch(err){
setError(err)
}
setLoading(false)
};
fetchData().catch(err => setError(err));
},[url])
useState here are not supposed to be an array of boolean, you just want to know if you're data are loading or not and if you catch an error.
Can you also check your api url ?
|
My react project is showing white blank screen with the use of api to get data from the back in react
|
I have already done the back and front of the project but when I am trying to get a data from the back with the use of useFetch, it shows me white blank space.
I have tried all my best to get data from the back through the use of the api but it just showing me blank. When I remove the useFetch method, everything works well.
useFetch.js
import { useEffect, useState } from "react"
import axios from "axios";
const useFetch = (url) => {
const [data, setData] = useState([])
const [loading, setLoading] = useState([false])
const [error, setError] = useState([false])
useEffect(()=>{
const fetchData = async ()=>{
setLoading(true)
try{
const res = await axios.get(url);
setData(res.data);
}catch(err){
setError(err)
}
setLoading(false)
};
fetchData();
},[url])
const reFetch = async ()=>{
setLoading(true)
try{
const res = await axios.get(url);
setData(res.data);
}catch(err){
setError(err)
}
setLoading(false)
};
return { data, loading, error, reFetch}
};
export default useFetch;
featured.js
import useFetch from "../../hooks/useFetch";
import "./featured.css";
const Featured = () => {
const { data, loading, error } = useFetch(
"/hotels/countByCity?cities=freetown,makeni,bo"
);
return (
<div className="featured">
<div className="featuredItem">
<img
src="https://tourismsierraleone.com/wp-content/uploads/2021/08/Freetown2.jpg"
alt=""
className="featuredImg"
/>
<div className="featuredTitles">
<h1>Freetown</h1>
<h2>20 properties</h2>
</div>
</div>
<div className="featuredItem">
<img
src="https://upload.wikimedia.org/wikipedia/commons/c/c0/Makeni_Wusum.JPG"
alt=""
className="featuredImg"
/>
<div className="featuredTitles">
<h1>Makeni</h1>
<h2>50 properties</h2>
</div>
</div>
<div className="featuredItem">
<img
src="https://www.visitsierraleone.org/wp-content/uploads/2021/08/doha-1.jpg"
alt=""
className="featuredImg"
/>
<div className="featuredTitles">
<h1>Bo</h1>
<h2>35 properties</h2>
</div>
</div>
</div>
);
};
export default Featured;
|
[
"try this :\nconst [data, setData] = useState()\nconst [loading, setLoading] = useState(false)\nconst [error, setError] = useState(false)\n\nuseEffect(()=>{\n const fetchData = async ()=>{\n setLoading(true)\n try{\n const res = await axios.get(url);\n setData(res.data);\n }catch(err){\n setError(err)\n }\n setLoading(false)\n };\n fetchData().catch(err => setError(err));\n},[url])\n\nuseState here are not supposed to be an array of boolean, you just want to know if you're data are loading or not and if you catch an error.\nCan you also check your api url ?\n"
] |
[
0
] |
[] |
[] |
[
"api",
"mongodb",
"reactjs"
] |
stackoverflow_0074661993_api_mongodb_reactjs.txt
|
Q:
Up-to-date example of NetMQ multithreading
I am trying to create a single server/multiple clients NetMQ test program (I believe this should use the Router-Dealer pattern) which would allow the server to process unique client requests using workers on separate threads (and reply to each client separately), but I cannot find a single working example which works with the current nuget version (v4.0.1.5 at the time of writing).
Each client is just supposed to send a request (which contains its Id since it's a Dealer socket), and get its dedicated response from the server. Server should have a pool of threads (IOCP style) which will consume messages and send back responses.
I found the Multithreaded example in the NetMQ/Samples github, which seems to be what I am looking for, but it uses a QueueDevice to connect clients with workers, and this class seems to have been removed at some point:
var queue = new QueueDevice(
"tcp://localhost:5555",
"tcp://localhost:5556",
DeviceMode.Threaded);
Then there is the Router-dealer example at netmq.readthedocs.io, which uses the NetMQPoller, but doesn't compile because it calls the non-existent RouterSocket.ReceiveMessage() and NetMQSocket.Receive(out bool hasmore) methods, which have been removed:
public static void Main(string[] args)
{
// NOTES
// 1. Use ThreadLocal<DealerSocket> where each thread has
// its own client DealerSocket to talk to server
// 2. Each thread can send using it own socket
// 3. Each thread socket is added to poller
const int delay = 3000; // millis
var clientSocketPerThread = new ThreadLocal<DealerSocket>();
using (var server = new RouterSocket("@tcp://127.0.0.1:5556"))
using (var poller = new NetMQPoller())
{
// Start some threads, each with its own DealerSocket
// to talk to the server socket. Creates lots of sockets,
// but no nasty race conditions no shared state, each
// thread has its own socket, happy days.
for (int i = 0; i < 3; i++)
{
Task.Factory.StartNew(state =>
{
DealerSocket client = null;
if (!clientSocketPerThread.IsValueCreated)
{
client = new DealerSocket();
client.Options.Identity =
Encoding.Unicode.GetBytes(state.ToString());
client.Connect("tcp://127.0.0.1:5556");
client.ReceiveReady += Client_ReceiveReady;
clientSocketPerThread.Value = client;
poller.Add(client);
}
else
{
client = clientSocketPerThread.Value;
}
while (true)
{
var messageToServer = new NetMQMessage();
messageToServer.AppendEmptyFrame();
messageToServer.Append(state.ToString());
PrintFrames("Client Sending", messageToServer);
client.SendMultipartMessage(messageToServer);
Thread.Sleep(delay);
}
}, string.Format("client {0}", i), TaskCreationOptions.LongRunning);
}
// start the poller
poller.RunAsync();
// server loop
while (true)
{
var clientMessage = server.ReceiveMessage();
PrintFrames("Server receiving", clientMessage);
if (clientMessage.FrameCount == 3)
{
var clientAddress = clientMessage[0];
var clientOriginalMessage = clientMessage[2].ConvertToString();
string response = string.Format("{0} back from server {1}",
clientOriginalMessage, DateTime.Now.ToLongTimeString());
var messageToClient = new NetMQMessage();
messageToClient.Append(clientAddress);
messageToClient.AppendEmptyFrame();
messageToClient.Append(response);
server.SendMultipartMessage(messageToClient);
}
}
}
}
static void PrintFrames(string operationType, NetMQMessage message)
{
for (int i = 0; i < message.FrameCount; i++)
{
Console.WriteLine("{0} Socket : Frame[{1}] = {2}", operationType, i,
message[i].ConvertToString());
}
}
static void Client_ReceiveReady(object sender, NetMQSocketEventArgs e)
{
bool hasmore = false;
e.Socket.Receive(out hasmore);
if (hasmore)
{
string result = e.Socket.ReceiveFrameString(out hasmore);
Console.WriteLine("REPLY {0}", result);
}
}
Perhaps these are easy to fix, but I am a NetMQ newbie and I would just like to get a proper "multithreaded Hello World" for C# working.
The NetMQ API is slightly different from the one at the official 0MQ docs (it's more idiomatic with C# and uses new low-allocation .NET constructs), so it's hard for me to understand how to properly port original C examples.
Can someone point me to a resource with up-to-date examples for this scenario, or help me understand what's the correct way to do it using the new NetMQ API?
Or is this library deprecated and I should use the clrzmq4 .NET wrapper? From what I've seen, NetMQ uses Span<T> and ref structs all around the codebase, so it seems it should be performant.
A:
I've fixed those several issues with the router-dealer example at netmq.readthedocs.io, and now the code is working. I am posting it here, perhaps it will be useful (maybe @somdoron or somebody can check it out and update the docs too).
The example doesn't fully do what I'd want (to have a pool of workers which fairly get jobs), I believe I have to implement the separate broker thread.
using NetMQ;
using NetMQ.Sockets;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
internal static class Program
{
public static void Main(string[] args)
{
InitLogger();
const int NumClients = 5;
Log($"App started with {NumClients} clients\r\n");
using (var server = new RouterSocket("@tcp://127.0.0.1:5556"))
using (var poller = new NetMQPoller())
{
// Start some threads, each with its own DealerSocket
// to talk to the server socket. Creates lots of sockets,
// but no nasty race conditions no shared state, each
// thread has its own socket, happy days.
for (int i = 0; i < NumClients; i++)
{
var clientNo = i + 1;
Task.Factory.StartNew(async () =>
{
var rnd = new Random(31 + clientNo * 57);
var clientId = $"C{clientNo}";
DealerSocket client = new DealerSocket();
client.Options.Identity = Encoding.ASCII.GetBytes(clientId);
client.Connect("tcp://127.0.0.1:5556");
client.ReceiveReady += (sender, e) =>
{
var msg = e.Socket.ReceiveMultipartMessage(3);
var clientid = Encoding.ASCII.GetString(e.Socket.Options.Identity);
Log($"Client '{clientid}' received <- server", msg);
};
poller.Add(client);
while (true)
{
var messageToServer = new NetMQMessage();
messageToServer.Append(NetMQFrame.Empty);
messageToServer.Append($"Some data ({clientId}|{rnd.Next():X8})", Encoding.ASCII);
Log($"Client {clientId} sending -> server: ", messageToServer);
client.SendMultipartMessage(messageToServer);
await Task.Delay(3000);
}
}, TaskCreationOptions.LongRunning);
}
// start the poller
poller.RunAsync();
// server loop
while (true)
{
var clientMessage = server.ReceiveMultipartMessage();
if (clientMessage.FrameCount < 1)
{
Log("Server received invalid frame count");
continue;
}
var clientid = clientMessage[0];
Log($"Server received <- {clientid.ConvertToString()}: ", clientMessage);
var msg = clientMessage.Last().ConvertToString(Encoding.ASCII);
string response = $"Replying to '{msg}'";
{
var messageToClient = new NetMQMessage();
messageToClient.Append(clientid);
messageToClient.Append(NetMQFrame.Empty);
messageToClient.Append(response, Encoding.ASCII);
Log($"Server sending -> {clientid.ConvertToString()}: {response}");
server.SendMultipartMessage(messageToClient);
}
}
}
}
#region Poor man's console logging
static BlockingCollection<string> _logQueue;
// log using a blocking collection
private static void InitLogger()
{
_logQueue = new BlockingCollection<string>();
Task.Factory.StartNew(() =>
{
foreach (var msg in _logQueue.GetConsumingEnumerable())
{
Console.WriteLine(msg);
}
});
}
// thread id, timestamp, message
static void Log(string msg)
{
var thid = Thread.CurrentThread.ManagedThreadId;
var time = GetTimestamp().ToString("HH:mm:ss.fff");
_logQueue.Add($"[T{thid:00}] {time}: {msg}");
}
// log all frames in a message
static void Log(string operationType, NetMQMessage message)
{
var frames = string.Join(", ", message.Select((m, i) => $"F[{i}]={{{m.ConvertToString(Encoding.ASCII)}}}"));
Log($"{operationType} {message.FrameCount} frames: " + frames);
}
// if possible, use win10 high precision timestamps
static DateTime GetTimestamp()
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 10) // win 10
{
long fileTime;
WinApi.GetSystemTimePreciseAsFileTime(out fileTime);
return DateTime.FromFileTimeUtc(fileTime);
}
return DateTime.UtcNow;
}
static class WinApi
{
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.Winapi)]
internal static extern void GetSystemTimePreciseAsFileTime(out long filetime);
}
#endregion
}
A:
I recently completed a fairly good example of a pub-sub model, with support for multiple subscribers (many tasks). Since it appears you are using C#, the code also demonstrates how to use a CancellationToken to have all tasks exit when requested; this will help if you are writing NET Core Service Workers. I'm no expert on NetMQ, but this was my opportunity to learn a small amount.
paultechguy/NetMQPubSubExample
|
Up-to-date example of NetMQ multithreading
|
I am trying to create a single server/multiple clients NetMQ test program (I believe this should use the Router-Dealer pattern) which would allow the server to process unique client requests using workers on separate threads (and reply to each client separately), but I cannot find a single working example which works with the current nuget version (v4.0.1.5 at the time of writing).
Each client is just supposed to send a request (which contains its Id since it's a Dealer socket), and get its dedicated response from the server. Server should have a pool of threads (IOCP style) which will consume messages and send back responses.
I found the Multithreaded example in the NetMQ/Samples github, which seems to be what I am looking for, but it uses a QueueDevice to connect clients with workers, and this class seems to have been removed at some point:
var queue = new QueueDevice(
"tcp://localhost:5555",
"tcp://localhost:5556",
DeviceMode.Threaded);
Then there is the Router-dealer example at netmq.readthedocs.io, which uses the NetMQPoller, but doesn't compile because it calls the non-existent RouterSocket.ReceiveMessage() and NetMQSocket.Receive(out bool hasmore) methods, which have been removed:
public static void Main(string[] args)
{
// NOTES
// 1. Use ThreadLocal<DealerSocket> where each thread has
// its own client DealerSocket to talk to server
// 2. Each thread can send using it own socket
// 3. Each thread socket is added to poller
const int delay = 3000; // millis
var clientSocketPerThread = new ThreadLocal<DealerSocket>();
using (var server = new RouterSocket("@tcp://127.0.0.1:5556"))
using (var poller = new NetMQPoller())
{
// Start some threads, each with its own DealerSocket
// to talk to the server socket. Creates lots of sockets,
// but no nasty race conditions no shared state, each
// thread has its own socket, happy days.
for (int i = 0; i < 3; i++)
{
Task.Factory.StartNew(state =>
{
DealerSocket client = null;
if (!clientSocketPerThread.IsValueCreated)
{
client = new DealerSocket();
client.Options.Identity =
Encoding.Unicode.GetBytes(state.ToString());
client.Connect("tcp://127.0.0.1:5556");
client.ReceiveReady += Client_ReceiveReady;
clientSocketPerThread.Value = client;
poller.Add(client);
}
else
{
client = clientSocketPerThread.Value;
}
while (true)
{
var messageToServer = new NetMQMessage();
messageToServer.AppendEmptyFrame();
messageToServer.Append(state.ToString());
PrintFrames("Client Sending", messageToServer);
client.SendMultipartMessage(messageToServer);
Thread.Sleep(delay);
}
}, string.Format("client {0}", i), TaskCreationOptions.LongRunning);
}
// start the poller
poller.RunAsync();
// server loop
while (true)
{
var clientMessage = server.ReceiveMessage();
PrintFrames("Server receiving", clientMessage);
if (clientMessage.FrameCount == 3)
{
var clientAddress = clientMessage[0];
var clientOriginalMessage = clientMessage[2].ConvertToString();
string response = string.Format("{0} back from server {1}",
clientOriginalMessage, DateTime.Now.ToLongTimeString());
var messageToClient = new NetMQMessage();
messageToClient.Append(clientAddress);
messageToClient.AppendEmptyFrame();
messageToClient.Append(response);
server.SendMultipartMessage(messageToClient);
}
}
}
}
static void PrintFrames(string operationType, NetMQMessage message)
{
for (int i = 0; i < message.FrameCount; i++)
{
Console.WriteLine("{0} Socket : Frame[{1}] = {2}", operationType, i,
message[i].ConvertToString());
}
}
static void Client_ReceiveReady(object sender, NetMQSocketEventArgs e)
{
bool hasmore = false;
e.Socket.Receive(out hasmore);
if (hasmore)
{
string result = e.Socket.ReceiveFrameString(out hasmore);
Console.WriteLine("REPLY {0}", result);
}
}
Perhaps these are easy to fix, but I am a NetMQ newbie and I would just like to get a proper "multithreaded Hello World" for C# working.
The NetMQ API is slightly different from the one at the official 0MQ docs (it's more idiomatic with C# and uses new low-allocation .NET constructs), so it's hard for me to understand how to properly port original C examples.
Can someone point me to a resource with up-to-date examples for this scenario, or help me understand what's the correct way to do it using the new NetMQ API?
Or is this library deprecated and I should use the clrzmq4 .NET wrapper? From what I've seen, NetMQ uses Span<T> and ref structs all around the codebase, so it seems it should be performant.
|
[
"I've fixed those several issues with the router-dealer example at netmq.readthedocs.io, and now the code is working. I am posting it here, perhaps it will be useful (maybe @somdoron or somebody can check it out and update the docs too).\nThe example doesn't fully do what I'd want (to have a pool of workers which fairly get jobs), I believe I have to implement the separate broker thread.\nusing NetMQ;\nusing NetMQ.Sockets;\n\nusing System;\nusing System.Collections.Concurrent;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\n\ninternal static class Program\n{\n public static void Main(string[] args)\n {\n InitLogger();\n\n const int NumClients = 5;\n Log($\"App started with {NumClients} clients\\r\\n\");\n\n using (var server = new RouterSocket(\"@tcp://127.0.0.1:5556\"))\n using (var poller = new NetMQPoller())\n {\n // Start some threads, each with its own DealerSocket\n // to talk to the server socket. Creates lots of sockets,\n // but no nasty race conditions no shared state, each\n // thread has its own socket, happy days.\n\n for (int i = 0; i < NumClients; i++)\n {\n var clientNo = i + 1;\n Task.Factory.StartNew(async () =>\n {\n var rnd = new Random(31 + clientNo * 57);\n var clientId = $\"C{clientNo}\";\n DealerSocket client = new DealerSocket();\n\n client.Options.Identity = Encoding.ASCII.GetBytes(clientId);\n client.Connect(\"tcp://127.0.0.1:5556\");\n client.ReceiveReady += (sender, e) => \n {\n var msg = e.Socket.ReceiveMultipartMessage(3);\n var clientid = Encoding.ASCII.GetString(e.Socket.Options.Identity);\n Log($\"Client '{clientid}' received <- server\", msg);\n };\n poller.Add(client);\n\n while (true)\n {\n var messageToServer = new NetMQMessage();\n messageToServer.Append(NetMQFrame.Empty);\n messageToServer.Append($\"Some data ({clientId}|{rnd.Next():X8})\", Encoding.ASCII);\n\n Log($\"Client {clientId} sending -> server: \", messageToServer);\n client.SendMultipartMessage(messageToServer);\n\n await Task.Delay(3000);\n }\n }, TaskCreationOptions.LongRunning);\n }\n\n // start the poller\n poller.RunAsync();\n\n // server loop\n\n while (true)\n {\n var clientMessage = server.ReceiveMultipartMessage();\n\n if (clientMessage.FrameCount < 1)\n {\n Log(\"Server received invalid frame count\");\n continue;\n }\n\n var clientid = clientMessage[0];\n Log($\"Server received <- {clientid.ConvertToString()}: \", clientMessage);\n \n var msg = clientMessage.Last().ConvertToString(Encoding.ASCII);\n string response = $\"Replying to '{msg}'\";\n\n {\n var messageToClient = new NetMQMessage();\n messageToClient.Append(clientid);\n messageToClient.Append(NetMQFrame.Empty);\n messageToClient.Append(response, Encoding.ASCII);\n Log($\"Server sending -> {clientid.ConvertToString()}: {response}\");\n server.SendMultipartMessage(messageToClient);\n }\n\n }\n }\n }\n\n #region Poor man's console logging \n\n static BlockingCollection<string> _logQueue;\n\n // log using a blocking collection\n private static void InitLogger()\n {\n _logQueue = new BlockingCollection<string>();\n Task.Factory.StartNew(() =>\n {\n foreach (var msg in _logQueue.GetConsumingEnumerable())\n {\n Console.WriteLine(msg);\n }\n });\n }\n \n // thread id, timestamp, message\n static void Log(string msg)\n {\n var thid = Thread.CurrentThread.ManagedThreadId;\n var time = GetTimestamp().ToString(\"HH:mm:ss.fff\");\n _logQueue.Add($\"[T{thid:00}] {time}: {msg}\");\n }\n\n // log all frames in a message\n static void Log(string operationType, NetMQMessage message)\n {\n var frames = string.Join(\", \", message.Select((m, i) => $\"F[{i}]={{{m.ConvertToString(Encoding.ASCII)}}}\"));\n Log($\"{operationType} {message.FrameCount} frames: \" + frames);\n }\n\n // if possible, use win10 high precision timestamps\n static DateTime GetTimestamp()\n {\n if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 10) // win 10\n {\n long fileTime;\n WinApi.GetSystemTimePreciseAsFileTime(out fileTime);\n return DateTime.FromFileTimeUtc(fileTime);\n }\n\n return DateTime.UtcNow;\n }\n\n static class WinApi\n {\n [DllImport(\"Kernel32.dll\", CallingConvention = CallingConvention.Winapi)]\n internal static extern void GetSystemTimePreciseAsFileTime(out long filetime);\n }\n\n #endregion\n}\n\n",
"I recently completed a fairly good example of a pub-sub model, with support for multiple subscribers (many tasks). Since it appears you are using C#, the code also demonstrates how to use a CancellationToken to have all tasks exit when requested; this will help if you are writing NET Core Service Workers. I'm no expert on NetMQ, but this was my opportunity to learn a small amount.\npaultechguy/NetMQPubSubExample\n"
] |
[
5,
0
] |
[] |
[] |
[
"c#",
"client_server",
"multithreading",
"netmq",
"zeromq"
] |
stackoverflow_0063820558_c#_client_server_multithreading_netmq_zeromq.txt
|
Q:
NextJs import doesn't work for certain libs
I created a Next.Js app with create-next-app and trying to import and use ramda. But it gives me next error TypeError: Cannot read properties of undefined (reading 'add'). So actual import from lib is undefined.
Code snippet
Error with ramda
But if I replace ramda.add with lodash.add - all works fine. Do somebody know what is the difference and how I make it work with ramda?
My setup
"lodash": "^4.17.21",
"next": "13.0.5",
"ramda": "^0.28.0",
"typescript": "4.9.3"
"packageManager": "[email protected]",
I would expect it work with both libs, as for me there's no difference in usage.
I tried to move it to getServerSideProps, use yarn v1, npm, recreate a project..
A:
See https://ramdajs.com/ docs:
Note for versions > 0.25 Ramda versions > 0.25 don't have a default export. So instead of import R from 'ramda';, one has to use import * as R from 'ramda'; Or better yet, import only the required functions via import { functionName } from 'ramda';
So you have to use
import * as R from 'ramda';
|
NextJs import doesn't work for certain libs
|
I created a Next.Js app with create-next-app and trying to import and use ramda. But it gives me next error TypeError: Cannot read properties of undefined (reading 'add'). So actual import from lib is undefined.
Code snippet
Error with ramda
But if I replace ramda.add with lodash.add - all works fine. Do somebody know what is the difference and how I make it work with ramda?
My setup
"lodash": "^4.17.21",
"next": "13.0.5",
"ramda": "^0.28.0",
"typescript": "4.9.3"
"packageManager": "[email protected]",
I would expect it work with both libs, as for me there's no difference in usage.
I tried to move it to getServerSideProps, use yarn v1, npm, recreate a project..
|
[
"See https://ramdajs.com/ docs:\n\nNote for versions > 0.25 Ramda versions > 0.25 don't have a default export. So instead of import R from 'ramda';, one has to use import * as R from 'ramda'; Or better yet, import only the required functions via import { functionName } from 'ramda';\n\nSo you have to use\nimport * as R from 'ramda';\n\n"
] |
[
0
] |
[] |
[] |
[
"next.js"
] |
stackoverflow_0074662097_next.js.txt
|
Q:
Combining two tables in dataset results in only first table in datagridview
I am querying two SQL database tables in the same dataset. I've tried merging them, using union and different join methods. All seem to result without the data from the second table.
Here is my code:
`
public string c = My data source string.
public DataSet ds = new DataSet();
public void GetData()
{
var select = "Select tblMainOrder.fldOrderNum AS [Order], fldBatchName As Batch, fldShipWeekDate AS [Ship Week], Trim(Concat(fldFinishDesc, ' ', fldSpecialFX1Desc, ' ', fldSpecialFX2Desc, ' ', fldSpecialFX3Desc, ' ', fldSpecialFX4Desc, ' ', fldSpecialFinishName, ' ', fldFinishNote1, ' ', fldFinishNote2, ' ', fldFinishNote3)) AS FinishDesc, fldVarnishTypeDesc AS Varnish, fldColorSampleNum AS [Sample #], fldNumberOfCabinets AS Items, fldDateWritten AS Written FROM tblMainOrder WHERE fldOrderStatus <> 99 AND fldFinishingOrderedDate IS NULL AND fldDateShipped IS NULL AND (fldFinishDesc = 'BM' OR fldFinishDesc = 'Spec Paint' OR fldFinishDesc = 'SPEC PAINT' OR fldFinishDesc = 'Spec Stain' OR fldFinishDesc = 'SPEC STAIN' OR fldFinishDesc = 'Special P' OR fldFinishDesc = 'SPECIAL R' OR fldFinishDesc = 'SW')";
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable dtData = new DataTable();
ds.Tables.Add(dtData);
dataAdapter.Fill(dtData);
var select2 = "Select SUM(CASE fldProductID WHEN 'b' THEN fldQuantity WHEN 'w' THEN fldQuantity WHEN 'T' THEN fldQuantity WHEN 'v' THEN fldQuantity END) AS Cabs From tblOrderItems"; //Group By tblOrderItems.fldOrderNum";
var da = new SqlDataAdapter(select2, c);
var cmdBuilder = new SqlCommandBuilder(da);
DataTable dtCnt = new DataTable();
ds.Tables.Add(dtCnt);
dataAdapter.Fill(dtCnt);
var select3 = "SELECT dtData.Order, dtData.Batch, dtData.[Ship Week], dtData.FinishDesc, dtData.Varnish, dtData.[Sample #], dtData.Items, dtCnt.Cabs, dtData.Written FROM dtData LEFT OUTER JOIN dtCnt ON dtData.Order = dtCnt.fldOrderNum";
var dadapt = new SqlDataAdapter(select3, c);
var cmdBldr = new SqlCommandBuilder(dadapt);
DataTable dtFnl = new DataTable();
ds.Tables.Add(dtFnl);
dataAdapter.Fill(dtFnl);
DGV1.DataSource = dtFnl;
}
`
Pulling my hair out trying to make this work. Any suggestions would be greatly appreciated.
A:
select3 = "select tblMainOrder.fldOrderNum AS [Order], fldBatchName As Batch, fldShipWeekDate AS [Ship Week], Trim(Concat(fldFinishDesc, ' ', fldSpecialFX1Desc, ' ', fldSpecialFX2Desc, ' ', fldSpecialFX3Desc, ' ', fldSpecialFX4Desc, ' ', fldSpecialFinishName, ' ', fldFinishNote1, ' ', fldFinishNote2, ' ', fldFinishNote3)) AS FinishDesc, fldVarnishTypeDesc AS Varnish, fldColorSampleNum AS [Sample #], fldNumberOfCabinets AS Items, fldDateWritten AS Written,(Select isnull(SUM(CASE fldProductID WHEN 'b' THEN fldQuantity WHEN 'w' THEN fldQuantity WHEN 'T' THEN fldQuantity WHEN 'v' THEN fldQuantity END),0) AS Cabs From tblOrderItems where tblOrderItems.fldOrderNum= tblMainOrder.fldOrderNum) as Cabs
FROM tblMainOrder WHERE fldOrderStatus <> 99 AND fldFinishingOrderedDate IS NULL AND fldDateShipped IS NULL AND (fldFinishDesc = 'BM' OR fldFinishDesc = 'Spec Paint' OR fldFinishDesc = 'SPEC PAINT' OR fldFinishDesc = 'Spec Stain' OR fldFinishDesc = 'SPEC STAIN' OR fldFinishDesc = 'Special P' OR fldFinishDesc = 'SPECIAL R' OR fldFinishDesc = 'SW')";
Unfortunately, I am writing to you from a mobile phone, and this editor does not support profiling the answer as required. So use this query. I can write a better answer than this later.
|
Combining two tables in dataset results in only first table in datagridview
|
I am querying two SQL database tables in the same dataset. I've tried merging them, using union and different join methods. All seem to result without the data from the second table.
Here is my code:
`
public string c = My data source string.
public DataSet ds = new DataSet();
public void GetData()
{
var select = "Select tblMainOrder.fldOrderNum AS [Order], fldBatchName As Batch, fldShipWeekDate AS [Ship Week], Trim(Concat(fldFinishDesc, ' ', fldSpecialFX1Desc, ' ', fldSpecialFX2Desc, ' ', fldSpecialFX3Desc, ' ', fldSpecialFX4Desc, ' ', fldSpecialFinishName, ' ', fldFinishNote1, ' ', fldFinishNote2, ' ', fldFinishNote3)) AS FinishDesc, fldVarnishTypeDesc AS Varnish, fldColorSampleNum AS [Sample #], fldNumberOfCabinets AS Items, fldDateWritten AS Written FROM tblMainOrder WHERE fldOrderStatus <> 99 AND fldFinishingOrderedDate IS NULL AND fldDateShipped IS NULL AND (fldFinishDesc = 'BM' OR fldFinishDesc = 'Spec Paint' OR fldFinishDesc = 'SPEC PAINT' OR fldFinishDesc = 'Spec Stain' OR fldFinishDesc = 'SPEC STAIN' OR fldFinishDesc = 'Special P' OR fldFinishDesc = 'SPECIAL R' OR fldFinishDesc = 'SW')";
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable dtData = new DataTable();
ds.Tables.Add(dtData);
dataAdapter.Fill(dtData);
var select2 = "Select SUM(CASE fldProductID WHEN 'b' THEN fldQuantity WHEN 'w' THEN fldQuantity WHEN 'T' THEN fldQuantity WHEN 'v' THEN fldQuantity END) AS Cabs From tblOrderItems"; //Group By tblOrderItems.fldOrderNum";
var da = new SqlDataAdapter(select2, c);
var cmdBuilder = new SqlCommandBuilder(da);
DataTable dtCnt = new DataTable();
ds.Tables.Add(dtCnt);
dataAdapter.Fill(dtCnt);
var select3 = "SELECT dtData.Order, dtData.Batch, dtData.[Ship Week], dtData.FinishDesc, dtData.Varnish, dtData.[Sample #], dtData.Items, dtCnt.Cabs, dtData.Written FROM dtData LEFT OUTER JOIN dtCnt ON dtData.Order = dtCnt.fldOrderNum";
var dadapt = new SqlDataAdapter(select3, c);
var cmdBldr = new SqlCommandBuilder(dadapt);
DataTable dtFnl = new DataTable();
ds.Tables.Add(dtFnl);
dataAdapter.Fill(dtFnl);
DGV1.DataSource = dtFnl;
}
`
Pulling my hair out trying to make this work. Any suggestions would be greatly appreciated.
|
[
"select3 = \"select tblMainOrder.fldOrderNum AS [Order], fldBatchName As Batch, fldShipWeekDate AS [Ship Week], Trim(Concat(fldFinishDesc, ' ', fldSpecialFX1Desc, ' ', fldSpecialFX2Desc, ' ', fldSpecialFX3Desc, ' ', fldSpecialFX4Desc, ' ', fldSpecialFinishName, ' ', fldFinishNote1, ' ', fldFinishNote2, ' ', fldFinishNote3)) AS FinishDesc, fldVarnishTypeDesc AS Varnish, fldColorSampleNum AS [Sample #], fldNumberOfCabinets AS Items, fldDateWritten AS Written,(Select isnull(SUM(CASE fldProductID WHEN 'b' THEN fldQuantity WHEN 'w' THEN fldQuantity WHEN 'T' THEN fldQuantity WHEN 'v' THEN fldQuantity END),0) AS Cabs From tblOrderItems where tblOrderItems.fldOrderNum= tblMainOrder.fldOrderNum) as Cabs\nFROM tblMainOrder WHERE fldOrderStatus <> 99 AND fldFinishingOrderedDate IS NULL AND fldDateShipped IS NULL AND (fldFinishDesc = 'BM' OR fldFinishDesc = 'Spec Paint' OR fldFinishDesc = 'SPEC PAINT' OR fldFinishDesc = 'Spec Stain' OR fldFinishDesc = 'SPEC STAIN' OR fldFinishDesc = 'Special P' OR fldFinishDesc = 'SPECIAL R' OR fldFinishDesc = 'SW')\";\nUnfortunately, I am writing to you from a mobile phone, and this editor does not support profiling the answer as required. So use this query. I can write a better answer than this later.\n"
] |
[
0
] |
[] |
[] |
[
"c#",
"sql"
] |
stackoverflow_0074659685_c#_sql.txt
|
Q:
How can you set custom labels for controls in Storybook?
I'm trying to set custom labels for my controls in Storybook as outlined in the instructions here, but it's not working as expected. According to the instructions you can specify control.labels to configure custom labels for your checkbox, radio, or select input.
Right now I have a prop of size that allows the user to select the size of the component, but in Storybook it's showing the number value as opposed to name. e.g.
Instead of the number values I want the labels to read the names from the enum below.
export enum sizes {
small = 32,
default = 50,
large = 100,
};
How can I update Storybook to use the enum sizes name instead of the value?
// storybook
export default {
title: 'Components/Spinner',
component: Spinner,
controls: { expanded: true },
argTypes: {
type: {
options: ['primary', 'secondary', 'success', 'warning', 'danger', 'info', 'light'],
control: { type: 'radio'},
},
size: {
options: [sizes.default, sizes.small, sizes.large],
control: {
type: 'radio',
labels: {
Default: 'Default',
Small: 'Small',
Large: 'Large'
},
},
}
}
} as Meta;
FYI: If I update options to the following:
options: sizes,
I get both the name and the value and only the name works
A:
In case anyone else comes across this issue I solved it by manually typing in the values. According to this Stackoverflow post enums end up as object. So it was outputting both the key and values.
export default {
title: 'Components/Spinner',
component: Spinner,
controls: { expanded: true },
argTypes: {
type: {
options: ['primary', 'secondary', 'success', 'warning', 'danger', 'info', 'light'],
control: { type: 'radio'},
},
size: {
options: [32, 50, 100],
control: {
type: 'radio',
labels: {
32: 'small',
50: 'default',
100: 'large',
},
},
}
}
} as Meta;
|
How can you set custom labels for controls in Storybook?
|
I'm trying to set custom labels for my controls in Storybook as outlined in the instructions here, but it's not working as expected. According to the instructions you can specify control.labels to configure custom labels for your checkbox, radio, or select input.
Right now I have a prop of size that allows the user to select the size of the component, but in Storybook it's showing the number value as opposed to name. e.g.
Instead of the number values I want the labels to read the names from the enum below.
export enum sizes {
small = 32,
default = 50,
large = 100,
};
How can I update Storybook to use the enum sizes name instead of the value?
// storybook
export default {
title: 'Components/Spinner',
component: Spinner,
controls: { expanded: true },
argTypes: {
type: {
options: ['primary', 'secondary', 'success', 'warning', 'danger', 'info', 'light'],
control: { type: 'radio'},
},
size: {
options: [sizes.default, sizes.small, sizes.large],
control: {
type: 'radio',
labels: {
Default: 'Default',
Small: 'Small',
Large: 'Large'
},
},
}
}
} as Meta;
FYI: If I update options to the following:
options: sizes,
I get both the name and the value and only the name works
|
[
"In case anyone else comes across this issue I solved it by manually typing in the values. According to this Stackoverflow post enums end up as object. So it was outputting both the key and values.\nexport default {\ntitle: 'Components/Spinner',\ncomponent: Spinner,\ncontrols: { expanded: true },\nargTypes: {\n type: {\n options: ['primary', 'secondary', 'success', 'warning', 'danger', 'info', 'light'],\n control: { type: 'radio'},\n },\n size: {\n options: [32, 50, 100],\n control: {\n type: 'radio',\n labels: {\n 32: 'small',\n 50: 'default',\n 100: 'large',\n },\n },\n }\n}\n} as Meta;\n\n"
] |
[
0
] |
[] |
[] |
[
"reactjs",
"storybook",
"typescript"
] |
stackoverflow_0074660694_reactjs_storybook_typescript.txt
|
Q:
service container fails at connecting to MongoDB container with docker-compose
I have a project with this directory structure:
- other-service/
- my-service/
src/
Dockerfile
.env
docker-compose
.env
I have defined my mongoDB container & service container in a docker-compose.yml file like below:
version: "3"
services:
my-service:
depends_on:
- mongodb
env_file: ./my-service/.env
container_name: my-service
build: ./my-service
environment:
- DB_HOST=$DB_HOST
- DB_USER=$DB_USER
- DB_PASSWORD=$DB_PASSWORD
- DB_NAME=$DB_NAME
- DB_PORT=$DB_PORT
ports:
- "3002:3002"
mongodb:
image: mongo:latest
container_name: my-mongodb
env_file: ./.env
environment:
MONGO_INITDB_ROOT_USERNAME: $DB_USER
MONGO_INITDB_ROOT_PASSWORD: $DB_PASSWORD
ports:
- $DB_PORT:$DB_PORT
volumes:
- db_vol:/data/db
volumes:
db_vol:
The my-service/.env file looks like this:
DB_HOST=mongodb
DB_USER=root
DB_PASSWORD=pass123
DB_NAME=my_db
DB_PORT=27017
...
The root level .env looks like this (basically the same content as my-service/.env for the DB part):
#used by compose
DB_HOST=mongodb
DB_USER=root
DB_PASSWORD=pass123
DB_NAME=my_db
DB_PORT=27017
my-service tries to connect to mongoDB with this code:
const dbUri=`mongodb://${process.env['DB_USER']}:${process.env['DB_PASSWORD']}@${process.env['DB_HOST']}:${process.env['DB_PORT']}/${process.env['DB_NAME']}`
console.log(`DB connect to: ${dbUri}`);
await mongoose.connect(dbUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
After I run docker-compose build & docker-compose up -d. The my-mongodb container is up and running. But my-service is not. I checked the container log, it shows:
DB connect to: mongodb://root:pass123@mongodb:27017/my_db
...
DatabaseConnError: Database connection failure. undefined
...
statusCode: 500,
msg: 'Database connection failure'
}
Node.js v19.2.0
I feel it is because both containers are on the same Docker bridge network, the database URI I defined might not correct? But I am not sure. Could someone please guide me where could be wrong in my case?
A:
you might need a healthcheck for mongodb.
version: "3"
services:
my-service:
depends_on:
mongodb:
condition: service_healthy
env_file: ./my-service/.env
container_name: my-service
build: ./my-service
environment:
- DB_HOST=$DB_HOST
- DB_USER=$DB_USER
- DB_PASSWORD=$DB_PASSWORD
- DB_NAME=$DB_NAME
- DB_PORT=$DB_PORT
ports:
- "3002:3002"
mongodb:
image: mongo:latest
container_name: my-mongodb
env_file: ./.env
environment:
MONGO_INITDB_ROOT_USERNAME: $DB_USER
MONGO_INITDB_ROOT_PASSWORD: $DB_PASSWORD
ports:
- $DB_PORT:$DB_PORT
volumes:
- db_vol:/data/db
healthcheck:
test: echo 'db.runCommand("ping").ok' | mongosh localhost:$DB_PORT/test --quiet
interval: 10s
timeout: 10s
retries: 5
start_period: 10s
volumes:
db_vol:
Similar: mongodb and mongo-express not connecting with docker-compose
|
service container fails at connecting to MongoDB container with docker-compose
|
I have a project with this directory structure:
- other-service/
- my-service/
src/
Dockerfile
.env
docker-compose
.env
I have defined my mongoDB container & service container in a docker-compose.yml file like below:
version: "3"
services:
my-service:
depends_on:
- mongodb
env_file: ./my-service/.env
container_name: my-service
build: ./my-service
environment:
- DB_HOST=$DB_HOST
- DB_USER=$DB_USER
- DB_PASSWORD=$DB_PASSWORD
- DB_NAME=$DB_NAME
- DB_PORT=$DB_PORT
ports:
- "3002:3002"
mongodb:
image: mongo:latest
container_name: my-mongodb
env_file: ./.env
environment:
MONGO_INITDB_ROOT_USERNAME: $DB_USER
MONGO_INITDB_ROOT_PASSWORD: $DB_PASSWORD
ports:
- $DB_PORT:$DB_PORT
volumes:
- db_vol:/data/db
volumes:
db_vol:
The my-service/.env file looks like this:
DB_HOST=mongodb
DB_USER=root
DB_PASSWORD=pass123
DB_NAME=my_db
DB_PORT=27017
...
The root level .env looks like this (basically the same content as my-service/.env for the DB part):
#used by compose
DB_HOST=mongodb
DB_USER=root
DB_PASSWORD=pass123
DB_NAME=my_db
DB_PORT=27017
my-service tries to connect to mongoDB with this code:
const dbUri=`mongodb://${process.env['DB_USER']}:${process.env['DB_PASSWORD']}@${process.env['DB_HOST']}:${process.env['DB_PORT']}/${process.env['DB_NAME']}`
console.log(`DB connect to: ${dbUri}`);
await mongoose.connect(dbUri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
After I run docker-compose build & docker-compose up -d. The my-mongodb container is up and running. But my-service is not. I checked the container log, it shows:
DB connect to: mongodb://root:pass123@mongodb:27017/my_db
...
DatabaseConnError: Database connection failure. undefined
...
statusCode: 500,
msg: 'Database connection failure'
}
Node.js v19.2.0
I feel it is because both containers are on the same Docker bridge network, the database URI I defined might not correct? But I am not sure. Could someone please guide me where could be wrong in my case?
|
[
"you might need a healthcheck for mongodb.\nversion: \"3\"\nservices:\n my-service:\n depends_on:\n mongodb:\n condition: service_healthy\n env_file: ./my-service/.env\n container_name: my-service\n build: ./my-service\n environment:\n - DB_HOST=$DB_HOST\n - DB_USER=$DB_USER\n - DB_PASSWORD=$DB_PASSWORD\n - DB_NAME=$DB_NAME\n - DB_PORT=$DB_PORT\n ports:\n - \"3002:3002\"\n\n mongodb:\n image: mongo:latest\n container_name: my-mongodb\n env_file: ./.env\n environment:\n MONGO_INITDB_ROOT_USERNAME: $DB_USER\n MONGO_INITDB_ROOT_PASSWORD: $DB_PASSWORD\n ports:\n - $DB_PORT:$DB_PORT\n volumes:\n - db_vol:/data/db\n healthcheck:\n test: echo 'db.runCommand(\"ping\").ok' | mongosh localhost:$DB_PORT/test --quiet\n interval: 10s\n timeout: 10s\n retries: 5\n start_period: 10s \n\nvolumes:\n db_vol:\n\nSimilar: mongodb and mongo-express not connecting with docker-compose\n"
] |
[
0
] |
[] |
[] |
[
"docker",
"docker_compose",
"mongodb",
"node.js"
] |
stackoverflow_0074631201_docker_docker_compose_mongodb_node.js.txt
|
Q:
How to classify unknown/unseen data as anomaly
I trained a CNN model with 6 different classes (labels are 0-5) and I am getting more than 90% accuracy out of it. It can correctly classify the classes. I am actually trying to detect anomaly with it. So what I want is, if any data comes which my model has never seen before or never been trained on similar data then it will be classified as anomaly. I do not have any abnormal data to train my model, I just have the normal data. So the rule would be, if any incoming data point does not belong to any of the six classes then it is anomaly. How can I do it?
I thought of a method which I am not sure if it works in this scenario. The method is, when I predict a single data point it gives me the probability score for all 6 classes. So, I take the maximum value out of this 6 value and if this max value is below a threshold level, for example, 70, then this observation will be classified as anomaly. That means, if any data point has less than 70% probability of being one of the six classes then it is an anomaly. The code looks like this
y_pred = s_model.predict(X_test_scaled)
normal = []
abnormal = []
max_value_list= []
for i in y_pred:
max_value= np.max(i)
max_value_list.append(max_value)
if max_value <=0.70:
abnormal.append(max_value)
print('Anomaly detected')
else:
normal.append(max_value)
print('The number of total abnormal observations are: ',len(abnormal))
Does this method works in my case? Or is there any better way to do it? Any kind of help is appreciated.
A:
Interesting problem but I think your method does not work.
When your model's entropy is high, i.e. it is unsure which class to choose for that particular sample input, it does not necessarily mean that that sample is an anomaly, it just means that the model is perhaps struggling to select the correct normal class.
I suggest adding some abnormal samples (some random unrelated images, if your samples are images), between 1% to 10% of your data, and labelling them as class 7. Then train your model with those (and perhaps give more penalty for misclassifying the class 7).
When you have your unseen samples, you classify them using your trained model. If they are classified as class 7, then you know they are anomalies.
Hope this helps.
|
How to classify unknown/unseen data as anomaly
|
I trained a CNN model with 6 different classes (labels are 0-5) and I am getting more than 90% accuracy out of it. It can correctly classify the classes. I am actually trying to detect anomaly with it. So what I want is, if any data comes which my model has never seen before or never been trained on similar data then it will be classified as anomaly. I do not have any abnormal data to train my model, I just have the normal data. So the rule would be, if any incoming data point does not belong to any of the six classes then it is anomaly. How can I do it?
I thought of a method which I am not sure if it works in this scenario. The method is, when I predict a single data point it gives me the probability score for all 6 classes. So, I take the maximum value out of this 6 value and if this max value is below a threshold level, for example, 70, then this observation will be classified as anomaly. That means, if any data point has less than 70% probability of being one of the six classes then it is an anomaly. The code looks like this
y_pred = s_model.predict(X_test_scaled)
normal = []
abnormal = []
max_value_list= []
for i in y_pred:
max_value= np.max(i)
max_value_list.append(max_value)
if max_value <=0.70:
abnormal.append(max_value)
print('Anomaly detected')
else:
normal.append(max_value)
print('The number of total abnormal observations are: ',len(abnormal))
Does this method works in my case? Or is there any better way to do it? Any kind of help is appreciated.
|
[
"Interesting problem but I think your method does not work.\nWhen your model's entropy is high, i.e. it is unsure which class to choose for that particular sample input, it does not necessarily mean that that sample is an anomaly, it just means that the model is perhaps struggling to select the correct normal class.\nI suggest adding some abnormal samples (some random unrelated images, if your samples are images), between 1% to 10% of your data, and labelling them as class 7. Then train your model with those (and perhaps give more penalty for misclassifying the class 7).\nWhen you have your unseen samples, you classify them using your trained model. If they are classified as class 7, then you know they are anomalies.\nHope this helps.\n"
] |
[
2
] |
[] |
[] |
[
"anomaly_detection",
"conv_neural_network",
"machine_learning",
"python",
"tensorflow"
] |
stackoverflow_0074662022_anomaly_detection_conv_neural_network_machine_learning_python_tensorflow.txt
|
Q:
How to prevent IntelliJ IDEA from deleting unused packages?
I'm working with intelliJ and my problem is when I start to import some temporary unused packages into my class file intellij delete those line within a second.
how can I turn off this not so nice feature?
A:
Disable File | Settings | Editor | General | Auto Import | Optimize imports on the fly.
Normally you don't need to add imports manually, IDEA does it for you.
A:
For Scala developers: you can have enabled
Settings > Editor > General > Auto Import > Optimize imports on the fly
but add exclusions into
Settings > Editor > Code Style > Scala > Imports always marked as used:
A:
In Intellij 14 :
Settings > Editor > General > Auto Import > Optimize imports on the fly.
A:
(Update)
For the Scala developers out there, you can have 1/2 the cake and eat the other 1/2 now: disable the auto-optimize for just scala
A:
The above answers are obviously the way to go. Here's another quick fix (a bad one at that) is to simply use it somewhere in your code
if (0) console.log(LibraryName.version);
This should only be a temporary measure though.
A:
For me while using Go, this was caused by optimizing imports on save. IntelliJ IDEA -> Prefernces -> Tools -> Actions on Save -> Optimize imports.
|
How to prevent IntelliJ IDEA from deleting unused packages?
|
I'm working with intelliJ and my problem is when I start to import some temporary unused packages into my class file intellij delete those line within a second.
how can I turn off this not so nice feature?
|
[
"Disable File | Settings | Editor | General | Auto Import | Optimize imports on the fly.\nNormally you don't need to add imports manually, IDEA does it for you.\n",
"For Scala developers: you can have enabled \nSettings > Editor > General > Auto Import > Optimize imports on the fly\nbut add exclusions into\nSettings > Editor > Code Style > Scala > Imports always marked as used:\n\n\n",
"In Intellij 14 :\nSettings > Editor > General > Auto Import > Optimize imports on the fly.\n",
"(Update)\nFor the Scala developers out there, you can have 1/2 the cake and eat the other 1/2 now: disable the auto-optimize for just scala\n\n",
"The above answers are obviously the way to go. Here's another quick fix (a bad one at that) is to simply use it somewhere in your code\nif (0) console.log(LibraryName.version);\n\nThis should only be a temporary measure though.\n",
"For me while using Go, this was caused by optimizing imports on save. IntelliJ IDEA -> Prefernces -> Tools -> Actions on Save -> Optimize imports.\n"
] |
[
99,
17,
12,
3,
0,
0
] |
[] |
[] |
[
"intellij_idea"
] |
stackoverflow_0011154912_intellij_idea.txt
|
Q:
GetClipBounds in Direct2D
Is there a way to get the clip bounds in Direct2D similar to GDI+?
https://learn.microsoft.com/en-us/windows/win32/api/gdiplusgraphics/nf-gdiplusgraphics-graphics-getclipbounds(rectf)
I have a D2D render target that has been transformed (translate, rotate and scale). How do I now calculate the clipped bounds? Any sample code or a function to calculate this?
Thanks
A:
I 'd create a rectangle geometry on the target rectangle, then and calculate the bounds passing the transform. You don't even need a target, geometries are target-indepentent.
|
GetClipBounds in Direct2D
|
Is there a way to get the clip bounds in Direct2D similar to GDI+?
https://learn.microsoft.com/en-us/windows/win32/api/gdiplusgraphics/nf-gdiplusgraphics-graphics-getclipbounds(rectf)
I have a D2D render target that has been transformed (translate, rotate and scale). How do I now calculate the clipped bounds? Any sample code or a function to calculate this?
Thanks
|
[
"I 'd create a rectangle geometry on the target rectangle, then and calculate the bounds passing the transform. You don't even need a target, geometries are target-indepentent.\n"
] |
[
0
] |
[] |
[] |
[
"direct2d",
"winapi",
"windows"
] |
stackoverflow_0074660941_direct2d_winapi_windows.txt
|
Q:
Unable to import nonsense from Nostril
I am trying to import nonsense from Nostril (
from nostril import nonsense)
but I get this error;
ImportError Traceback (most recent call last)
Cell In [12], line 1
----> 1 from nostril import nonsense
ImportError: cannot import name 'nonsense' from 'nostril' (c:\Users\GithuaG\AppData\Local\Programs\Python\Python310\lib\site-packages\nostril\__init__.py)
Here is what the init.py file contains:
from .__version__ import __version__, __title__, __url__, __description__
from .__version__ import __author__, __email__
from .__version__ import __license__, __copyright__
from .ng import NGramData
from .nonsense_detector import (
nonsense, generate_nonsense_detector, test_unlabeled, test_labeled,
ngrams, dataset_from_pickle, sanitize_string
)
Tried researching on the web but no success.
Any help will be appreciated, Thanks
A:
You most probably did pip install nostril before you installed the actual nostril package that you needed (just like I did). This would have caused another package that is used for testing to be installed alongside. You can either uninstall both nostril packages and then re-install just the nostril package you need.
Or you can directly import the nonsense object from nonsense_detector as below if you need both the packages
from nostril.nonsense_detector import nonsense
|
Unable to import nonsense from Nostril
|
I am trying to import nonsense from Nostril (
from nostril import nonsense)
but I get this error;
ImportError Traceback (most recent call last)
Cell In [12], line 1
----> 1 from nostril import nonsense
ImportError: cannot import name 'nonsense' from 'nostril' (c:\Users\GithuaG\AppData\Local\Programs\Python\Python310\lib\site-packages\nostril\__init__.py)
Here is what the init.py file contains:
from .__version__ import __version__, __title__, __url__, __description__
from .__version__ import __author__, __email__
from .__version__ import __license__, __copyright__
from .ng import NGramData
from .nonsense_detector import (
nonsense, generate_nonsense_detector, test_unlabeled, test_labeled,
ngrams, dataset_from_pickle, sanitize_string
)
Tried researching on the web but no success.
Any help will be appreciated, Thanks
|
[
"You most probably did pip install nostril before you installed the actual nostril package that you needed (just like I did). This would have caused another package that is used for testing to be installed alongside. You can either uninstall both nostril packages and then re-install just the nostril package you need.\nOr you can directly import the nonsense object from nonsense_detector as below if you need both the packages\nfrom nostril.nonsense_detector import nonsense\n\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0074386232_python.txt
|
Q:
Jetpack compose remember function not working
I'm trying to create a scrollable background in Jetpack Compose.
The problem is that the variable "currentPadding" isn't updating it's state after the value "padding" is modified after recomposition. In the first composition (loading state) the "padding" value is set to 112.dp and after load the value changes to 160.dp.
It's strange because I have used the remember function this way multiple times in other places in the app and it's the first time that this happens.
Could you help me out?
Thanks a lot.
@Composable
fun ScrollableBackground(
scrollState: ScrollState,
composable: ComposableFun,
modifier: Modifier = Modifier,
isBannerListEmpty: Boolean,
) {
val padding = if (isBannerListEmpty) {
112.dp
} else {
160.dp
}
val minPadding: Dp = 29.dp
val dp0 = dimensionResource(id = R.dimen.no_dp)
var currentPadding: Dp by remember { mutableStateOf(padding) }
val state: Dp by animateDpAsState(targetValue = currentPadding)
val nestedScrollConnection: NestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val percent = scrollState.value.toFloat() / scrollState.maxValue.toFloat() * 100f
val delta = available.y.dp
val newSize = currentPadding + delta / 3
currentPadding = when {
percent > 20f -> minPadding
newSize < minPadding -> minPadding
newSize > padding -> padding
else -> newSize
}
return Offset.Zero
}
}
}
Box(
modifier = modifier
.fillMaxSize()
.nestedScroll(nestedScrollConnection)
) {
Surface(
color = White,
modifier = Modifier
.padding(top = state)
.fillMaxSize()
.clip(
CircleShape.copy(
topStart = Shapes.medium.topStart,
topEnd = Shapes.medium.topEnd,
bottomEnd = CornerSize(dp0),
bottomStart = CornerSize(dp0)
)
)
) {}
composable.invoke()
}
}
I tried sending other kind of parameters from the view model to the composable (instead of a boolean, in this case "isBannerListEmpty"), like the current desired padding value, and nothing seems to work.
A:
You have put nestedScrollConnection in remember. It also remembers the padding variable when first encountered. So when the actual value of padding is changed, this change is not propagated in remember of nestedScrollConnection.
Put padding inside onPreScroll.
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val padding = if (...) { //Don't use isBannerListEmpty here as neither this will update on recomposition
112.dp
} else {
160.dp
}
...
|
Jetpack compose remember function not working
|
I'm trying to create a scrollable background in Jetpack Compose.
The problem is that the variable "currentPadding" isn't updating it's state after the value "padding" is modified after recomposition. In the first composition (loading state) the "padding" value is set to 112.dp and after load the value changes to 160.dp.
It's strange because I have used the remember function this way multiple times in other places in the app and it's the first time that this happens.
Could you help me out?
Thanks a lot.
@Composable
fun ScrollableBackground(
scrollState: ScrollState,
composable: ComposableFun,
modifier: Modifier = Modifier,
isBannerListEmpty: Boolean,
) {
val padding = if (isBannerListEmpty) {
112.dp
} else {
160.dp
}
val minPadding: Dp = 29.dp
val dp0 = dimensionResource(id = R.dimen.no_dp)
var currentPadding: Dp by remember { mutableStateOf(padding) }
val state: Dp by animateDpAsState(targetValue = currentPadding)
val nestedScrollConnection: NestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
val percent = scrollState.value.toFloat() / scrollState.maxValue.toFloat() * 100f
val delta = available.y.dp
val newSize = currentPadding + delta / 3
currentPadding = when {
percent > 20f -> minPadding
newSize < minPadding -> minPadding
newSize > padding -> padding
else -> newSize
}
return Offset.Zero
}
}
}
Box(
modifier = modifier
.fillMaxSize()
.nestedScroll(nestedScrollConnection)
) {
Surface(
color = White,
modifier = Modifier
.padding(top = state)
.fillMaxSize()
.clip(
CircleShape.copy(
topStart = Shapes.medium.topStart,
topEnd = Shapes.medium.topEnd,
bottomEnd = CornerSize(dp0),
bottomStart = CornerSize(dp0)
)
)
) {}
composable.invoke()
}
}
I tried sending other kind of parameters from the view model to the composable (instead of a boolean, in this case "isBannerListEmpty"), like the current desired padding value, and nothing seems to work.
|
[
"You have put nestedScrollConnection in remember. It also remembers the padding variable when first encountered. So when the actual value of padding is changed, this change is not propagated in remember of nestedScrollConnection.\nPut padding inside onPreScroll.\n override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {\n\n val padding = if (...) { //Don't use isBannerListEmpty here as neither this will update on recomposition\n 112.dp\n } else {\n 160.dp\n }\n\n...\n\n"
] |
[
1
] |
[] |
[] |
[
"android_jetpack_compose",
"composable",
"kotlin"
] |
stackoverflow_0074661659_android_jetpack_compose_composable_kotlin.txt
|
Q:
How to verify that indexed type extends string?
let's say I have function func with 2 generic arguments
const func = <T extends {}, K extends keyof T>() => {};
and a type
interface Form {
a: boolean;
b: string;
}
then I can invoke them like so without any errors
func<Form, "a">();
func<Form, "b">();
Now I want func to accept only keys for which T[K] = string
In other words
func<Form, "a">(); // should pass
func<Form, "b">(); // should fail
My pseduo-typescript solution would be
const func = <T extends {}, K extends keyof T : where T[K] extends string>() => {};
but that of course doesn't go far. Is it even possible?
Any help is appreciated.
A:
With a little helper type to get all the string types keys:
type StringKeys<T> = {
[K in keyof T]:
T[K] extends string ? K : never
}[keyof T]
type Test = StringKeys<{ a: boolean, b: string, c: string }>
// type: 'b' | 'c'
This utility type maps over all property of T, and if the value type extends string the key name is preserved, and otherwise it is discarded as never.
Then you simply use that like:
interface Form {
a: boolean;
b: string;
}
const func = <T, K extends StringKeys<T>>() => {};
func<Form, "a">(); // error
func<Form, "b">(); // fine
See Playground
|
How to verify that indexed type extends string?
|
let's say I have function func with 2 generic arguments
const func = <T extends {}, K extends keyof T>() => {};
and a type
interface Form {
a: boolean;
b: string;
}
then I can invoke them like so without any errors
func<Form, "a">();
func<Form, "b">();
Now I want func to accept only keys for which T[K] = string
In other words
func<Form, "a">(); // should pass
func<Form, "b">(); // should fail
My pseduo-typescript solution would be
const func = <T extends {}, K extends keyof T : where T[K] extends string>() => {};
but that of course doesn't go far. Is it even possible?
Any help is appreciated.
|
[
"With a little helper type to get all the string types keys:\ntype StringKeys<T> = {\n [K in keyof T]:\n T[K] extends string ? K : never\n}[keyof T]\n\ntype Test = StringKeys<{ a: boolean, b: string, c: string }>\n// type: 'b' | 'c'\n\nThis utility type maps over all property of T, and if the value type extends string the key name is preserved, and otherwise it is discarded as never.\nThen you simply use that like:\ninterface Form {\n a: boolean;\n b: string;\n}\n\nconst func = <T, K extends StringKeys<T>>() => {};\n\nfunc<Form, \"a\">(); // error\nfunc<Form, \"b\">(); // fine\n\nSee Playground\n"
] |
[
2
] |
[] |
[] |
[
"extends",
"generics",
"keyof",
"typescript"
] |
stackoverflow_0074662257_extends_generics_keyof_typescript.txt
|
Q:
Python TkInter: How can I get the canvas coordinates of the visible area of a scrollable canvas?
I need to find out what the visible coordinates of a vertically scrollable canvas are using python and tkinter.
Let's assume I have a canvas that is 800 x 5000 pixels, and the visible, vertically scrollable window is 800x800. If I am scrolled all the way to the top of the canvas, I would like to have a function that, when run, would return something like:
x=0
y=0,
w=800
h=800
But if I were to scroll down and then run the function, I would get something like this:
x=0
y=350
w=800
h=800
And if I resized the window vertically to, say, 1000, I would get:
x=0
y=350
w=800
h=1000
I tried this code:
self.canvas.update()
print(f"X={self.canvas.canvasx(0)}")
print(f"Y={self.canvas.canvasy(0)}")
print(f"W={self.canvas.canvasx(self.canvas.winfo_width())}")
print(f"H={self.canvas.canvasy(self.canvas.winfo_height())}")
But it gives me the size of the whole canvas, not the visible window inside the canvas.
I have tried searching for the answer, but am surprised not to have found anyone else with the same question. Perhaps I just don't have the right search terms.
Context for anyone who cares:
I am writing a thumbnail browser that is a grid of thumbnails. Since there may be thousands of thumbnails, I want to update the ones that are visible first, and then use a thread to update the remaining (hidden) thumbnails as needed.
A:
The methods canvasx and canvasy of the Canvas widget will convert screen pixels (ie: what's visible on the screen) into canvas pixels (the location in the larger virtual canvas).
You can feed it an x or y of zero to get the virtual pixel at the top-left of the visible window, and you can give it the width and height of the widget to get the pixel at the bottom-right of the visible window.
x0 = canvas.canvasx(0)
y0 = canvas.canvasy(0)
x1 = canvas.canvasx(canvas.winfo_width())
y1 = canvas.canvasy(canvas.winfo_height())
The canonical tcl/tk documentation says this about the canvasx method:
pathName canvasx screenx ?gridspacing?: Given a window x-coordinate in the canvas screenx, this command returns the canvas x-coordinate that is displayed at that location. If gridspacing is specified, then the canvas coordinate is rounded to the nearest multiple of gridspacing units.
Here is a contrived program that will print the coordinates of the top-left and bottom right visible pixels every five seconds.
import tkinter as tk
root = tk.Tk()
canvas_frame = tk.Frame(root, bd=1, relief="sunken")
statusbar = tk.Label(root, bd=1, relief="sunken")
statusbar.pack(side="bottom", fill="x")
canvas_frame.pack(fill="both", expand=True)
canvas = tk.Canvas(canvas_frame, width=800, height=800, bd=0, highlightthickness=0)
ysb = tk.Scrollbar(canvas_frame, orient="vertical", command=canvas.yview)
xsb = tk.Scrollbar(canvas_frame, orient="horizontal", command=canvas.xview)
canvas.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)
canvas_frame.grid_rowconfigure(0, weight=1)
canvas_frame.grid_columnconfigure(0, weight=1)
canvas.grid(row=0, column=0, sticky="nsew")
ysb.grid(row=0, column=1, sticky="ns")
xsb.grid(row=1, column=0, sticky="ew")
for row in range(70):
for column in range(10):
x = column * 80
y = row * 80
canvas.create_rectangle(x, y, x+64, y+64, fill="gray")
canvas.create_text(x+32, y+32, anchor="c", text=f"{row},{column}")
canvas.configure(scrollregion=canvas.bbox("all"))
def show_coords():
x0 = int(canvas.canvasx(0))
y0 = int(canvas.canvasy(0))
x1 = int(canvas.canvasx(canvas.winfo_width()))
y1 = int(canvas.canvasy(canvas.winfo_height()))
statusbar.configure(text=f"{x0},{y0} / {x1},{y1}")
root.after(5000, show_coords)
show_coords()
root.mainloop()
|
Python TkInter: How can I get the canvas coordinates of the visible area of a scrollable canvas?
|
I need to find out what the visible coordinates of a vertically scrollable canvas are using python and tkinter.
Let's assume I have a canvas that is 800 x 5000 pixels, and the visible, vertically scrollable window is 800x800. If I am scrolled all the way to the top of the canvas, I would like to have a function that, when run, would return something like:
x=0
y=0,
w=800
h=800
But if I were to scroll down and then run the function, I would get something like this:
x=0
y=350
w=800
h=800
And if I resized the window vertically to, say, 1000, I would get:
x=0
y=350
w=800
h=1000
I tried this code:
self.canvas.update()
print(f"X={self.canvas.canvasx(0)}")
print(f"Y={self.canvas.canvasy(0)}")
print(f"W={self.canvas.canvasx(self.canvas.winfo_width())}")
print(f"H={self.canvas.canvasy(self.canvas.winfo_height())}")
But it gives me the size of the whole canvas, not the visible window inside the canvas.
I have tried searching for the answer, but am surprised not to have found anyone else with the same question. Perhaps I just don't have the right search terms.
Context for anyone who cares:
I am writing a thumbnail browser that is a grid of thumbnails. Since there may be thousands of thumbnails, I want to update the ones that are visible first, and then use a thread to update the remaining (hidden) thumbnails as needed.
|
[
"The methods canvasx and canvasy of the Canvas widget will convert screen pixels (ie: what's visible on the screen) into canvas pixels (the location in the larger virtual canvas).\nYou can feed it an x or y of zero to get the virtual pixel at the top-left of the visible window, and you can give it the width and height of the widget to get the pixel at the bottom-right of the visible window.\nx0 = canvas.canvasx(0)\ny0 = canvas.canvasy(0)\nx1 = canvas.canvasx(canvas.winfo_width())\ny1 = canvas.canvasy(canvas.winfo_height())\n\nThe canonical tcl/tk documentation says this about the canvasx method:\n\npathName canvasx screenx ?gridspacing?: Given a window x-coordinate in the canvas screenx, this command returns the canvas x-coordinate that is displayed at that location. If gridspacing is specified, then the canvas coordinate is rounded to the nearest multiple of gridspacing units.\n\n\nHere is a contrived program that will print the coordinates of the top-left and bottom right visible pixels every five seconds.\nimport tkinter as tk\n\nroot = tk.Tk()\ncanvas_frame = tk.Frame(root, bd=1, relief=\"sunken\")\nstatusbar = tk.Label(root, bd=1, relief=\"sunken\")\n\nstatusbar.pack(side=\"bottom\", fill=\"x\")\ncanvas_frame.pack(fill=\"both\", expand=True)\n\ncanvas = tk.Canvas(canvas_frame, width=800, height=800, bd=0, highlightthickness=0)\nysb = tk.Scrollbar(canvas_frame, orient=\"vertical\", command=canvas.yview)\nxsb = tk.Scrollbar(canvas_frame, orient=\"horizontal\", command=canvas.xview)\ncanvas.configure(yscrollcommand=ysb.set, xscrollcommand=xsb.set)\n\ncanvas_frame.grid_rowconfigure(0, weight=1)\ncanvas_frame.grid_columnconfigure(0, weight=1)\ncanvas.grid(row=0, column=0, sticky=\"nsew\")\nysb.grid(row=0, column=1, sticky=\"ns\")\nxsb.grid(row=1, column=0, sticky=\"ew\")\n\nfor row in range(70):\n for column in range(10):\n x = column * 80\n y = row * 80\n canvas.create_rectangle(x, y, x+64, y+64, fill=\"gray\")\n canvas.create_text(x+32, y+32, anchor=\"c\", text=f\"{row},{column}\")\n\ncanvas.configure(scrollregion=canvas.bbox(\"all\"))\n\ndef show_coords():\n x0 = int(canvas.canvasx(0))\n y0 = int(canvas.canvasy(0))\n x1 = int(canvas.canvasx(canvas.winfo_width()))\n y1 = int(canvas.canvasy(canvas.winfo_height()))\n statusbar.configure(text=f\"{x0},{y0} / {x1},{y1}\")\n root.after(5000, show_coords)\n\nshow_coords()\n\nroot.mainloop()\n\n"
] |
[
1
] |
[] |
[] |
[
"canvas",
"python",
"scroll",
"tkinter",
"visible"
] |
stackoverflow_0074661864_canvas_python_scroll_tkinter_visible.txt
|
Q:
Recursively iterate trough Pydantic Model
Lets say I have a model and I want to do some preprocessing on it. (for this problem it does not matter it this is pydantic model, or some kid of nested iterable, its a general question).
def preprocess(string):
# Accepts some preprocessing and returnes that string
class OtherModel(BaseModel):
other_id:int
some_name: str
class DummyModel(BaseModel):
location_id: int
other_models: List[OtherModel]
name:str
surname:str
one_other_model : OtherModel
I want to make a recursive function that will iterate trough every attribute of a Model and run some preprocessing funciton on it. For example that function can be removing some letter from a string.
I came this far and I dont know how to move further:
from collections.abc import Iterable
def preprocess_item(request: BaseModel) -> BaseModel:
for attribute_key, attribute_value in request:
if isinstance(attribute_value, str):
setattr(
request,
attribute_key,
_remove_html_tag(getattr(request, attribute_key)),
)
elif isinstance(attribute_value, BaseModel):
preprocess_item(attribute_value)
elif isinstance(attribute_value, Iterable):
for item in getattr(request,attribute_key):
preprocess_item(item)
This gives me the wrong answer, it basically unpacks every value. I want the same request object returned but with string fields preprocessed.
A:
If you are actually dealing with Pydantic models, I would argue this is one of the use cases for validators.
There is not really any need for recursion because you can just define the validator on your own base model, if you want it to apply to all models (that inherit from it):
from pydantic import BaseModel as PydanticBaseModel
from pydantic import validator
def process_string(string: str) -> str:
return string.replace("a", "")
class BaseModel(PydanticBaseModel):
@validator("*", pre=True, each_item=True)
def preprocess(cls, v: object) -> object:
if isinstance(v, str):
return process_string(v)
return v
class OtherModel(BaseModel):
other_id: int
some_name: str
class DummyModel(BaseModel):
location_id: int
other_models: list[OtherModel]
name: str
surname: str
one_other_model: OtherModel
If you want to be more selective and apply the same validator to specific models, they can be made reusable as well:
from pydantic import BaseModel, validator
def preprocess(v: object) -> object:
if isinstance(v, str):
return v.replace("a", "")
return v
class OtherModel(BaseModel):
other_id: int
some_name: str
_preprocess = validator("*", pre=True, allow_reuse=True)(preprocess)
class DummyModel(BaseModel):
location_id: int
other_models: list[OtherModel]
name: str
surname: str
one_other_model: OtherModel
_preprocess = validator(
"*",
pre=True,
each_item=True,
allow_reuse=True,
)(preprocess)
class NotProcessed(BaseModel):
field: str
We can test both versions like this:
if __name__ == "__main__":
dummy = DummyModel.parse_obj({
"location_id": 1,
"other_models": [
{"other_id": 1, "some_name": "foo"},
{"other_id": 2, "some_name": "spam"},
],
"name": "bar",
"surname": "baz",
"one_other_model": {"other_id": 2, "some_name": "eggs"},
})
print(dummy.json(indent=4))
The output in both cases is the same:
{
"location_id": 1,
"other_models": [
{
"other_id": 1,
"some_name": "foo"
},
{
"other_id": 2,
"some_name": "spm"
}
],
"name": "br",
"surname": "bz",
"one_other_model": {
"other_id": 2,
"some_name": "eggs"
}
}
|
Recursively iterate trough Pydantic Model
|
Lets say I have a model and I want to do some preprocessing on it. (for this problem it does not matter it this is pydantic model, or some kid of nested iterable, its a general question).
def preprocess(string):
# Accepts some preprocessing and returnes that string
class OtherModel(BaseModel):
other_id:int
some_name: str
class DummyModel(BaseModel):
location_id: int
other_models: List[OtherModel]
name:str
surname:str
one_other_model : OtherModel
I want to make a recursive function that will iterate trough every attribute of a Model and run some preprocessing funciton on it. For example that function can be removing some letter from a string.
I came this far and I dont know how to move further:
from collections.abc import Iterable
def preprocess_item(request: BaseModel) -> BaseModel:
for attribute_key, attribute_value in request:
if isinstance(attribute_value, str):
setattr(
request,
attribute_key,
_remove_html_tag(getattr(request, attribute_key)),
)
elif isinstance(attribute_value, BaseModel):
preprocess_item(attribute_value)
elif isinstance(attribute_value, Iterable):
for item in getattr(request,attribute_key):
preprocess_item(item)
This gives me the wrong answer, it basically unpacks every value. I want the same request object returned but with string fields preprocessed.
|
[
"If you are actually dealing with Pydantic models, I would argue this is one of the use cases for validators.\nThere is not really any need for recursion because you can just define the validator on your own base model, if you want it to apply to all models (that inherit from it):\nfrom pydantic import BaseModel as PydanticBaseModel\nfrom pydantic import validator\n\n\ndef process_string(string: str) -> str:\n return string.replace(\"a\", \"\")\n\n\nclass BaseModel(PydanticBaseModel):\n @validator(\"*\", pre=True, each_item=True)\n def preprocess(cls, v: object) -> object:\n if isinstance(v, str):\n return process_string(v)\n return v\n\n\nclass OtherModel(BaseModel):\n other_id: int\n some_name: str\n\n\nclass DummyModel(BaseModel):\n location_id: int\n other_models: list[OtherModel]\n name: str\n surname: str\n one_other_model: OtherModel\n\nIf you want to be more selective and apply the same validator to specific models, they can be made reusable as well:\nfrom pydantic import BaseModel, validator\n\n\ndef preprocess(v: object) -> object:\n if isinstance(v, str):\n return v.replace(\"a\", \"\")\n return v\n\n\nclass OtherModel(BaseModel):\n other_id: int\n some_name: str\n\n _preprocess = validator(\"*\", pre=True, allow_reuse=True)(preprocess)\n\n\nclass DummyModel(BaseModel):\n location_id: int\n other_models: list[OtherModel]\n name: str\n surname: str\n one_other_model: OtherModel\n\n _preprocess = validator(\n \"*\",\n pre=True,\n each_item=True,\n allow_reuse=True,\n )(preprocess)\n\n\nclass NotProcessed(BaseModel):\n field: str\n\nWe can test both versions like this:\nif __name__ == \"__main__\":\n dummy = DummyModel.parse_obj({\n \"location_id\": 1,\n \"other_models\": [\n {\"other_id\": 1, \"some_name\": \"foo\"},\n {\"other_id\": 2, \"some_name\": \"spam\"},\n ],\n \"name\": \"bar\",\n \"surname\": \"baz\",\n \"one_other_model\": {\"other_id\": 2, \"some_name\": \"eggs\"},\n })\n print(dummy.json(indent=4))\n\nThe output in both cases is the same:\n{\n \"location_id\": 1,\n \"other_models\": [\n {\n \"other_id\": 1,\n \"some_name\": \"foo\"\n },\n {\n \"other_id\": 2,\n \"some_name\": \"spm\"\n }\n ],\n \"name\": \"br\",\n \"surname\": \"bz\",\n \"one_other_model\": {\n \"other_id\": 2,\n \"some_name\": \"eggs\"\n }\n}\n\n"
] |
[
2
] |
[] |
[] |
[
"pydantic",
"python",
"python_3.x",
"recursion"
] |
stackoverflow_0074657576_pydantic_python_python_3.x_recursion.txt
|
Q:
firebase-tools error: EACCES: permission denied
I am trying to deploy Firebase hosting of my web app.
At the command line, when I type firebase deploy, I get the following error.
Note: firebase deploy is just one example. The same error occurs for all firebase commands. (e.g., firebase --help, firebase -v, firebase login, firebase logout, etc.)
Error
/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:53
throw err;
^
Error: EACCES: permission denied, open '/Users/mowzer/.config/configstore/update-notifier-firebase-tools.json'
You don't have access to this file.
at Error (native)
at Object.fs.openSync (fs.js:549:18)
at Object.fs.readFileSync (fs.js:397:15)
at Object.create.all.get (/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:34:26)
at Object.Configstore (/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:27:44)
at new UpdateNotifier (/usr/local/lib/node_modules/firebase-tools/node_modules/update-notifier/index.js:34:17)
at module.exports (/usr/local/lib/node_modules/firebase-tools/node_modules/update-notifier/index.js:123:23)
at Object. (/usr/local/lib/node_modules/firebase-tools/bin/firebase:5:48)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
Everything I have tried so far (including every CLI firebase instruction) rejects me for lack of access.
What can I do? What should I try?
(I am on a Mac OSX Yosemite v10.10.5 and firebase-tools v3.0.3)
Edit: When I do sudo firebase deploy, I get the following error.
Error: The entered credentials were incorrect.
I tried the following solution.
I tried to delete problem files then reinstall firebase-tools.
Terminal.sh
cd
cd .config/configstore
# Delete problematic files
rm firebase-tools.json
override rw------- root/staff for firebase-tools.json? y
rm update-notifier-firebase-tools.json
override rw------- root/staff for update-notifier-firebase-tools.json? y
# Reinstall firebase-tools
cd
sudo npm install -g firebase-tools
Then...
cd path/to/directory
cd firebase deploy
Now this file generates the error:
/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:53
cd /usr/local/lib/node_modules/firebase-tools/node_modules/configstore
A:
I fix it by adding sudo at the beginning of the command line!
A:
This looks like an issue with the permissions of modules you have npm installed. This is something lots of developers run into, and npm actually has some documentation on how to resolve it. Once you go through that, try again (you may need to re-install firebase-tools) and things should work.
A:
Add sudo prior to command it should work
sudo npm -g i firebase-tools
A:
I had the same issue, and I fixed it by using this command curl -sL firebase.tools | upgrade=true bash
A:
I had the same issue, and I fixed it by doing chmod 755 on all the files in the configstore directory
A:
Expanding more detail to the solution provided by @jacobawenger:
The most robust solution is to install Homebrew and let Homebrew manage the npm package installation for you.
Terminal.sh
# EACCESS error reference: https://docs.npmjs.com/getting-started/fixing-npm-permissions
# Install Homebrew # Reference: brew.sh # Ensures NPM is installed properly to avoid EACCESS errors
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
# Install npm # Reference: brew.sh
brew install node
# Install firebase-tools
npm install -g firebase-tools # Non-recurring task # Also updates to newest version (see notice)
A:
Easy Way:
Back up your computer.
if you have Permission issue run first this
sudo chown -R $USER /usr/local/lib/node_modules
then 2nd
1)- mkdir ~/.npm-global
2)- npm config set prefix '~/.npm-global'
3)- export PATH=~/.npm-global/bin:$PATH
4)- source ~/.profile
5)- npm install -g jshint
6)- NPM_CONFIG_PREFIX=~/.npm-global
A:
You can try using the --unsafe-perm flag. Just like this:
sudo npm install -g firebase-tools --unsafe-perm
A:
Try run the command as
su root
if you are using ubuntu.
For me, just use sudo, did not work.
I'm using Ubuntu 18.x.x and I was trying install firebase through npm
A:
What worked for me was basically reinstalling the node using the node version manager.
For this, you just install latest node js version this way
In my case at the point of this reply, the LTS Version of the Node JS is v14.17.0 hence nvm use 14.17.0 now try re-running the build.
A:
i faced the same issue recently.
running this command solved the issue for me
sudo chown -R $USER ~/.config/configstore
A:
There's information explaining why the sudo command makes the difference, and generally, when we are calling commands in terminal mode, we are not recognised as the computer's administrator, whereas certain commands are reserved for the administrator only. The sudo command enables terminal commands to be executed as the administrator. You can read about the sudo command here : )
Thank you for your contributions towards resolving this issue.
|
firebase-tools error: EACCES: permission denied
|
I am trying to deploy Firebase hosting of my web app.
At the command line, when I type firebase deploy, I get the following error.
Note: firebase deploy is just one example. The same error occurs for all firebase commands. (e.g., firebase --help, firebase -v, firebase login, firebase logout, etc.)
Error
/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:53
throw err;
^
Error: EACCES: permission denied, open '/Users/mowzer/.config/configstore/update-notifier-firebase-tools.json'
You don't have access to this file.
at Error (native)
at Object.fs.openSync (fs.js:549:18)
at Object.fs.readFileSync (fs.js:397:15)
at Object.create.all.get (/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:34:26)
at Object.Configstore (/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:27:44)
at new UpdateNotifier (/usr/local/lib/node_modules/firebase-tools/node_modules/update-notifier/index.js:34:17)
at module.exports (/usr/local/lib/node_modules/firebase-tools/node_modules/update-notifier/index.js:123:23)
at Object. (/usr/local/lib/node_modules/firebase-tools/bin/firebase:5:48)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
Everything I have tried so far (including every CLI firebase instruction) rejects me for lack of access.
What can I do? What should I try?
(I am on a Mac OSX Yosemite v10.10.5 and firebase-tools v3.0.3)
Edit: When I do sudo firebase deploy, I get the following error.
Error: The entered credentials were incorrect.
I tried the following solution.
I tried to delete problem files then reinstall firebase-tools.
Terminal.sh
cd
cd .config/configstore
# Delete problematic files
rm firebase-tools.json
override rw------- root/staff for firebase-tools.json? y
rm update-notifier-firebase-tools.json
override rw------- root/staff for update-notifier-firebase-tools.json? y
# Reinstall firebase-tools
cd
sudo npm install -g firebase-tools
Then...
cd path/to/directory
cd firebase deploy
Now this file generates the error:
/usr/local/lib/node_modules/firebase-tools/node_modules/configstore/index.js:53
cd /usr/local/lib/node_modules/firebase-tools/node_modules/configstore
|
[
"I fix it by adding sudo at the beginning of the command line!\n",
"This looks like an issue with the permissions of modules you have npm installed. This is something lots of developers run into, and npm actually has some documentation on how to resolve it. Once you go through that, try again (you may need to re-install firebase-tools) and things should work.\n",
"Add sudo prior to command it should work\nsudo npm -g i firebase-tools\n\n",
"I had the same issue, and I fixed it by using this command curl -sL firebase.tools | upgrade=true bash\n",
"I had the same issue, and I fixed it by doing chmod 755 on all the files in the configstore directory\n",
"Expanding more detail to the solution provided by @jacobawenger:\nThe most robust solution is to install Homebrew and let Homebrew manage the npm package installation for you.\n\nTerminal.sh\n\n# EACCESS error reference: https://docs.npmjs.com/getting-started/fixing-npm-permissions\n# Install Homebrew # Reference: brew.sh # Ensures NPM is installed properly to avoid EACCESS errors\n/usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"\n# Install npm # Reference: brew.sh\nbrew install node\n# Install firebase-tools\nnpm install -g firebase-tools # Non-recurring task # Also updates to newest version (see notice)\n\n",
"Easy Way: \nBack up your computer.\nif you have Permission issue run first this \n sudo chown -R $USER /usr/local/lib/node_modules\n\nthen 2nd\n1)- mkdir ~/.npm-global\n2)- npm config set prefix '~/.npm-global'\n3)- export PATH=~/.npm-global/bin:$PATH\n4)- source ~/.profile\n5)- npm install -g jshint\n6)- NPM_CONFIG_PREFIX=~/.npm-global\n\n",
"You can try using the --unsafe-perm flag. Just like this:\nsudo npm install -g firebase-tools --unsafe-perm\n\n",
"Try run the command as \n\nsu root\n\nif you are using ubuntu.\nFor me, just use sudo, did not work.\nI'm using Ubuntu 18.x.x and I was trying install firebase through npm\n",
"What worked for me was basically reinstalling the node using the node version manager.\nFor this, you just install latest node js version this way\nIn my case at the point of this reply, the LTS Version of the Node JS is v14.17.0 hence nvm use 14.17.0 now try re-running the build.\n",
"i faced the same issue recently.\nrunning this command solved the issue for me\nsudo chown -R $USER ~/.config/configstore\n\n",
"There's information explaining why the sudo command makes the difference, and generally, when we are calling commands in terminal mode, we are not recognised as the computer's administrator, whereas certain commands are reserved for the administrator only. The sudo command enables terminal commands to be executed as the administrator. You can read about the sudo command here : )\nThank you for your contributions towards resolving this issue.\n"
] |
[
23,
16,
5,
4,
2,
1,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"firebase",
"firebase_hosting",
"firebase_tools",
"npm",
"unix"
] |
stackoverflow_0038067572_firebase_firebase_hosting_firebase_tools_npm_unix.txt
|
Q:
debug with VScode a fastAPI project built with docker-compose with a postgresql database
I would like to be able to make my code stop on breakpoints with VScode. My project is built with docker-compose and works without debugging on port 8000.
Here are my configurations files:
docker-compose:
version: '3.4'
services:
murmurside:
image: murmurside
build: ./murmur_side
command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 -m uvicorn app.main:app --host 0.0.0.0 --port 8000"]
volumes:
- ./murmur_side/:/murmur_side/
ports:
- 8000:8000
- 5678:5678
environment:
- DATABASE_URL=postgresql://USERNAME:PASSWORD@db/fastapi_db_2
db:
image: postgres:13-alpine
volumes:
- postgres_data2:/var/lib/postgresql/data/
expose:
- 5432
environment:
- POSTGRES_USER=USERNAME
- POSTGRES_PASSWORD=PASSWORD
- POSTGRES_DB=fastapi_db_2
volumes:
postgres_data2:
dockerfile :
# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.10-slim
EXPOSE 8000
WORKDIR /murmur_side
# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
# Install pip requirements
COPY requirements.txt .
RUN python -m pip install -r requirements.txt
COPY . /murmur_side
# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /murmur_side
USER appuser
# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "-k", "uvicorn.workers.UvicornWorker", "app.main:app"]
launch.json :
I tested a 'launch' configuration but the debugger then bumps on the database related code. It does not seem to properly link to the database : after DATABASE_URL = os.getenv("DATABASE_URL") DATABASE_URL stays empty.
{
"configurations": [
{
"name": "Docker: Python - Fastapi",
"type": "docker",
"request": "launch",
"preLaunchTask": "docker-run: debug",
"python": {
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}
],
"projectType": "fastapi"
}
}
]
}
I also tested an 'attach' configuration. In that case, I get a debugger container launched at a random port but I get nothing when I browse to 127.0.0.1:randomPort
{
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "0.0.0.0",
"port": 8000 # I also tried with 5678
},
"preLaunchTask": "docker-run: debug",
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/murmur_side"
}
]
}
]
}
On this project I see that they added database credentials in the tasks.json. But I did not find any documentation stating that elsewhere. I tried that but I am unsure for the options other than username, password and dbname since I did not have to mention them in the docker-compose. Maybe I am also mistaking on the ports since there are several ones.
tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"type": "docker-build",
"label": "docker-build",
"platform": "python",
"dockerBuild": {
"tag": "sd4timapi_pip_debug:latest",
"dockerfile": "${workspaceFolder}/murmur_side/Dockerfile",
"context": "${workspaceFolder}/murmur_side/",
"pull": true
}
},
{
"type": "docker-run",
"label": "docker-run: debug",
"dependsOn": [
"docker-build"
],
"dockerRun": { # I also tried without this section
"image": "sd4timapi_pip_debug:latest",
"volumes": [
{
"containerPath": "/murmur_side/",
"localPath": "${workspaceFolder}/murmur_side/"
}
],
"ports": [
{
"containerPort": 8000,
"hostPort": 8001, # because it doesn't allow me to put 8000 : "port is already allocated"
"protocol": "tcp"
}
],
"env": {
"APP_PORT": "8000", #UNSURE
"DEBUG": "TRUE",
"ENVIRONMENT": "local", #UNSURE
"POSTGRES_USER": "USERNAME",
"POSTGRES_PASS": "PASSWORD",
"POSTGRES_DBNAME": "fastapi_db_2",
"POSTGRES_HOST": "db_host", #UNSURE
"POSTGRES_PORT": "5432", #UNSURE
"POSTGRES_APPLICATION_NAME": "sd4timapi_pip_debug", #UNSURE
}
},
"python": {
"args": [
"app.main:app",
"--host",
"0.0.0.0",
"--port",
"8000"
],
"module": "uvicorn"
}
}
]
}
A:
This works for me, for debugging my FastAPI app in VS Code.
Here's the ".vscode/launch.json" file:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
// Debug with FastAPI
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": [
"app.main:app",
"--host",
"0.0.0.0",
"--port",
"81",
"--reload"
],
"jinja": true,
"justMyCode": false
},
]
}
I get the following messages in the VS Code terminal logs, and then I can debug with breakpoints, etc.
Go to http://localhost:81/docs in your browser since I deployed to port 81.
INFO: Will watch for changes in these directories: ['/workspace']
INFO: Uvicorn running on http://0.0.0.0:81 (Press CTRL+C to quit)
INFO: Started reloader process [13707] using WatchFiles
INFO: Started server process [13801]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:36070 - "GET /docs HTTP/1.1" 200 OK
|
debug with VScode a fastAPI project built with docker-compose with a postgresql database
|
I would like to be able to make my code stop on breakpoints with VScode. My project is built with docker-compose and works without debugging on port 8000.
Here are my configurations files:
docker-compose:
version: '3.4'
services:
murmurside:
image: murmurside
build: ./murmur_side
command: ["sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 -m uvicorn app.main:app --host 0.0.0.0 --port 8000"]
volumes:
- ./murmur_side/:/murmur_side/
ports:
- 8000:8000
- 5678:5678
environment:
- DATABASE_URL=postgresql://USERNAME:PASSWORD@db/fastapi_db_2
db:
image: postgres:13-alpine
volumes:
- postgres_data2:/var/lib/postgresql/data/
expose:
- 5432
environment:
- POSTGRES_USER=USERNAME
- POSTGRES_PASSWORD=PASSWORD
- POSTGRES_DB=fastapi_db_2
volumes:
postgres_data2:
dockerfile :
# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.10-slim
EXPOSE 8000
WORKDIR /murmur_side
# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
# Install pip requirements
COPY requirements.txt .
RUN python -m pip install -r requirements.txt
COPY . /murmur_side
# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /murmur_side
USER appuser
# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "-k", "uvicorn.workers.UvicornWorker", "app.main:app"]
launch.json :
I tested a 'launch' configuration but the debugger then bumps on the database related code. It does not seem to properly link to the database : after DATABASE_URL = os.getenv("DATABASE_URL") DATABASE_URL stays empty.
{
"configurations": [
{
"name": "Docker: Python - Fastapi",
"type": "docker",
"request": "launch",
"preLaunchTask": "docker-run: debug",
"python": {
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/app"
}
],
"projectType": "fastapi"
}
}
]
}
I also tested an 'attach' configuration. In that case, I get a debugger container launched at a random port but I get nothing when I browse to 127.0.0.1:randomPort
{
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"connect": {
"host": "0.0.0.0",
"port": 8000 # I also tried with 5678
},
"preLaunchTask": "docker-run: debug",
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/murmur_side"
}
]
}
]
}
On this project I see that they added database credentials in the tasks.json. But I did not find any documentation stating that elsewhere. I tried that but I am unsure for the options other than username, password and dbname since I did not have to mention them in the docker-compose. Maybe I am also mistaking on the ports since there are several ones.
tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"type": "docker-build",
"label": "docker-build",
"platform": "python",
"dockerBuild": {
"tag": "sd4timapi_pip_debug:latest",
"dockerfile": "${workspaceFolder}/murmur_side/Dockerfile",
"context": "${workspaceFolder}/murmur_side/",
"pull": true
}
},
{
"type": "docker-run",
"label": "docker-run: debug",
"dependsOn": [
"docker-build"
],
"dockerRun": { # I also tried without this section
"image": "sd4timapi_pip_debug:latest",
"volumes": [
{
"containerPath": "/murmur_side/",
"localPath": "${workspaceFolder}/murmur_side/"
}
],
"ports": [
{
"containerPort": 8000,
"hostPort": 8001, # because it doesn't allow me to put 8000 : "port is already allocated"
"protocol": "tcp"
}
],
"env": {
"APP_PORT": "8000", #UNSURE
"DEBUG": "TRUE",
"ENVIRONMENT": "local", #UNSURE
"POSTGRES_USER": "USERNAME",
"POSTGRES_PASS": "PASSWORD",
"POSTGRES_DBNAME": "fastapi_db_2",
"POSTGRES_HOST": "db_host", #UNSURE
"POSTGRES_PORT": "5432", #UNSURE
"POSTGRES_APPLICATION_NAME": "sd4timapi_pip_debug", #UNSURE
}
},
"python": {
"args": [
"app.main:app",
"--host",
"0.0.0.0",
"--port",
"8000"
],
"module": "uvicorn"
}
}
]
}
|
[
"This works for me, for debugging my FastAPI app in VS Code.\nHere's the \".vscode/launch.json\" file:\n{\n // Use IntelliSense to learn about possible attributes.\n // Hover to view descriptions of existing attributes.\n // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n \"version\": \"0.2.0\",\n \"configurations\": [\n // Debug with FastAPI\n {\n \"name\": \"Python: FastAPI\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"module\": \"uvicorn\",\n \"args\": [\n \"app.main:app\",\n \"--host\",\n \"0.0.0.0\",\n \"--port\",\n \"81\",\n \"--reload\"\n ],\n \"jinja\": true,\n \"justMyCode\": false\n },\n ]\n}\n\nI get the following messages in the VS Code terminal logs, and then I can debug with breakpoints, etc.\nGo to http://localhost:81/docs in your browser since I deployed to port 81.\nINFO: Will watch for changes in these directories: ['/workspace']\nINFO: Uvicorn running on http://0.0.0.0:81 (Press CTRL+C to quit)\nINFO: Started reloader process [13707] using WatchFiles\nINFO: Started server process [13801]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\nINFO: 127.0.0.1:36070 - \"GET /docs HTTP/1.1\" 200 OK\n\n"
] |
[
0
] |
[] |
[] |
[
"fastapi",
"visual_studio_code",
"vscode_debugger",
"vscode_tasks"
] |
stackoverflow_0073958157_fastapi_visual_studio_code_vscode_debugger_vscode_tasks.txt
|
Q:
WildFly - is missing [jboss.naming.context.java.jdbc.__TimerPool]
I have followed this manual to migrate from GlassFish to WildFly:
http://wildfly.org/news/2014/02/06/GlassFish-to-WildFly-migration/
However I'm getting the following error when running my application in WildFly:
ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "exampleProject-ear-1.0-SNAPSHOT.ear")]) - failure description: {"WFLYCTL0180: Services with missing/unavailable dependencies" => [
"jboss.persistenceunit.\"exampleProject-ear-1.0-SNAPSHOT.ear/exampleProject-web-1.0-SNAPSHOT.war#exampleProjectPU\".FIRST_PHASE is missing [jboss.naming.context.java.jdbc.__TimerPool]",
"jboss.persistenceunit.\"exampleProject-ear-1.0-SNAPSHOT.ear/exampleProject-web-1.0-SNAPSHOT.war#exampleProjectPU\" is missing [jboss.naming.context.java.jdbc.__TimerPool]"
]}
The error talks about jboss.naming.context.java.jdbc.__TimerPool. Any idea of what should I do? I'm using WildFly 10 and MySQL as database.
A:
Forget about this. __TimerPool was the name of a Datasource in GlassFish and I was using it without knowing it, I simply removed the persistence.xml file that contained it and it worked.
A:
Check your standalone.xml. It must be having a datasource with pool-name "exampleProjectPU" . Something like this. Please remove the full xml block.
<datasources>
<datasource jndi-name="xxx:exampleProjectPU" pool-name="exampleProjectPU" enabled="true">
<connection-url>jdbc:oracle:thin:@//host:port/SID</connection-url>
<driver>oracle</driver>
<security>
<user-name></user-name>
<password></password>
</security>
</datasource>
Go to deployments folder and check if there is any sample project with name "example project.war". If yes, remove it and start the server again. It should work fine.
A:
try to change your mysql-connecter to bin file like mysql-connector-java-5.1.47-bin
make sure the name in is the some in jndi-name
|
WildFly - is missing [jboss.naming.context.java.jdbc.__TimerPool]
|
I have followed this manual to migrate from GlassFish to WildFly:
http://wildfly.org/news/2014/02/06/GlassFish-to-WildFly-migration/
However I'm getting the following error when running my application in WildFly:
ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "exampleProject-ear-1.0-SNAPSHOT.ear")]) - failure description: {"WFLYCTL0180: Services with missing/unavailable dependencies" => [
"jboss.persistenceunit.\"exampleProject-ear-1.0-SNAPSHOT.ear/exampleProject-web-1.0-SNAPSHOT.war#exampleProjectPU\".FIRST_PHASE is missing [jboss.naming.context.java.jdbc.__TimerPool]",
"jboss.persistenceunit.\"exampleProject-ear-1.0-SNAPSHOT.ear/exampleProject-web-1.0-SNAPSHOT.war#exampleProjectPU\" is missing [jboss.naming.context.java.jdbc.__TimerPool]"
]}
The error talks about jboss.naming.context.java.jdbc.__TimerPool. Any idea of what should I do? I'm using WildFly 10 and MySQL as database.
|
[
"Forget about this. __TimerPool was the name of a Datasource in GlassFish and I was using it without knowing it, I simply removed the persistence.xml file that contained it and it worked.\n",
"Check your standalone.xml. It must be having a datasource with pool-name \"exampleProjectPU\" . Something like this. Please remove the full xml block.\n<datasources>\n <datasource jndi-name=\"xxx:exampleProjectPU\" pool-name=\"exampleProjectPU\" enabled=\"true\">\n\n<connection-url>jdbc:oracle:thin:@//host:port/SID</connection-url>\n <driver>oracle</driver>\n <security>\n <user-name></user-name>\n <password></password>\n </security>\n </datasource>\n\n\nGo to deployments folder and check if there is any sample project with name \"example project.war\". If yes, remove it and start the server again. It should work fine.\n\n",
"\ntry to change your mysql-connecter to bin file like mysql-connector-java-5.1.47-bin\nmake sure the name in is the some in jndi-name\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"connection_pooling",
"datasource",
"jboss",
"jdbc",
"wildfly"
] |
stackoverflow_0036063404_connection_pooling_datasource_jboss_jdbc_wildfly.txt
|
Q:
Twisted sending files. python
I'm trying to transfer images and other files over the network using Twisted. I use for this the class "FileSender" and in particular the method "beginFileTransfer", which I use on the server. But the file is not fully received by the client and I can't open it. At the same time, if I send a small file it comes. So the problem is the size. Can you tell me how I can send big files? Below is the server and client code:
from twisted.internet.protocol import Protocol, connectionDone
from twisted.python import failure
from twisted.protocols.basic import FileSender
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
class TestServer(Protocol):
def connectionMade(self):
filesender = FileSender()
f = open('00000.jpg', 'rb')
filesender.beginFileTransfer(f, self.transport)
def dataReceived(self, data: bytes):
data = data.decode('UTF-8')
print(data)
def connectionLost(self, reason: failure.Failure = connectionDone):
print("Server lost Connection")
class QOTDFactory(Factory):
def buildProtocol(self, addr):
return TestServer()
# 8007 is the port you want to run under. Choose something >1024
endpoint = TCP4ServerEndpoint(reactor, 8007, interface="127.0.0.1")
endpoint.listen(QOTDFactory())
reactor.run()
from twisted.internet.protocol import Protocol, ClientFactory, connectionDone
from sys import stdout
from twisted.protocols.basic import FileSender
from twisted.python import failure
class TestClient(Protocol):
def connectionMade(self):
print("Client did connection")
def dataReceived(self, data):
f = open('13.jpg', 'wb')
f.write(data)
self.transport.write("Client take connection".encode('UTF-8'))
def connectionLost(self, reason: failure.Failure = connectionDone):
print("Client lost Connection Protocol")
class EchoClientFactory(ClientFactory):
def startedConnecting(self, connector):
print('Started to connect.')
def buildProtocol(self, addr):
print('Connected.')
return TestClient()
def clientConnectionLost(self, connector, reason):
print('Lost connection factory. Reason:', reason)
def clientConnectionFailed(self, connector, reason):
print('Connection failed factory. Reason:', reason)
from twisted.internet import reactor
reactor.connectTCP('127.0.0.1', 8007, EchoClientFactory())
reactor.run()
A:
Twisted uses non-blocking socket operations: data written to or read from sockets are just enough to not block. Filesender in effect sends chunks of data until all are sent and you need to buffer them until they are complete.
I would write the server part as:
class TestServer(Protocol):
def connectionMade(self):
filesender = FileSender()
f = open('00000.jpg', 'rb')
d = filesender.beginFileTransfer(f, self.transport)
d.addCallback(lambda _: self.transport.loseConnection()) # signals end of transmission
Then the client as:
class TestClient(Protocol):
def __init__(self):
self.f = open('13.jpg', 'wb')
def connectionMade(self):
print("Client did connection")
def dataReceived(self, data):
self.f.write(data) # I would buffer all the received data and
# write them all at once for efficiencey
# but this one will do
def connectionLost(self, reason: failure.Failure = connectionDone):
self.f.close() # server is done sending all chunks, close the file
print("Client lost Connection Protocol")
HTH
|
Twisted sending files. python
|
I'm trying to transfer images and other files over the network using Twisted. I use for this the class "FileSender" and in particular the method "beginFileTransfer", which I use on the server. But the file is not fully received by the client and I can't open it. At the same time, if I send a small file it comes. So the problem is the size. Can you tell me how I can send big files? Below is the server and client code:
from twisted.internet.protocol import Protocol, connectionDone
from twisted.python import failure
from twisted.protocols.basic import FileSender
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor
class TestServer(Protocol):
def connectionMade(self):
filesender = FileSender()
f = open('00000.jpg', 'rb')
filesender.beginFileTransfer(f, self.transport)
def dataReceived(self, data: bytes):
data = data.decode('UTF-8')
print(data)
def connectionLost(self, reason: failure.Failure = connectionDone):
print("Server lost Connection")
class QOTDFactory(Factory):
def buildProtocol(self, addr):
return TestServer()
# 8007 is the port you want to run under. Choose something >1024
endpoint = TCP4ServerEndpoint(reactor, 8007, interface="127.0.0.1")
endpoint.listen(QOTDFactory())
reactor.run()
from twisted.internet.protocol import Protocol, ClientFactory, connectionDone
from sys import stdout
from twisted.protocols.basic import FileSender
from twisted.python import failure
class TestClient(Protocol):
def connectionMade(self):
print("Client did connection")
def dataReceived(self, data):
f = open('13.jpg', 'wb')
f.write(data)
self.transport.write("Client take connection".encode('UTF-8'))
def connectionLost(self, reason: failure.Failure = connectionDone):
print("Client lost Connection Protocol")
class EchoClientFactory(ClientFactory):
def startedConnecting(self, connector):
print('Started to connect.')
def buildProtocol(self, addr):
print('Connected.')
return TestClient()
def clientConnectionLost(self, connector, reason):
print('Lost connection factory. Reason:', reason)
def clientConnectionFailed(self, connector, reason):
print('Connection failed factory. Reason:', reason)
from twisted.internet import reactor
reactor.connectTCP('127.0.0.1', 8007, EchoClientFactory())
reactor.run()
|
[
"Twisted uses non-blocking socket operations: data written to or read from sockets are just enough to not block. Filesender in effect sends chunks of data until all are sent and you need to buffer them until they are complete.\nI would write the server part as:\nclass TestServer(Protocol):\n \n def connectionMade(self):\n filesender = FileSender()\n f = open('00000.jpg', 'rb')\n d = filesender.beginFileTransfer(f, self.transport)\n d.addCallback(lambda _: self.transport.loseConnection()) # signals end of transmission\n\nThen the client as:\nclass TestClient(Protocol):\n\n def __init__(self):\n self.f = open('13.jpg', 'wb')\n\n def connectionMade(self):\n print(\"Client did connection\")\n\n def dataReceived(self, data):\n self.f.write(data) # I would buffer all the received data and\n # write them all at once for efficiencey\n # but this one will do\n\n def connectionLost(self, reason: failure.Failure = connectionDone):\n self.f.close() # server is done sending all chunks, close the file\n print(\"Client lost Connection Protocol\")\n\nHTH\n"
] |
[
0
] |
[] |
[] |
[
"networking",
"python",
"twisted"
] |
stackoverflow_0073391864_networking_python_twisted.txt
|
Q:
Why does Kotlin's compiler not realize when a variable is initialized in an if statement?
The following example of Kotlin source code returns an error when compiled:
fun main() {
var index: Int // create an integer used to call an index of an array
val myArray = Array(5) {i -> i + 1} // create an array to call from
val condition = true // makes an if statement run true later
if (condition) {
index = 2 // sets index to 2
}
println( myArray[index] ) // should print 2; errors
}
The error says that the example did not initialize the variable index by the time it is called, even though it is guaranteed to initialize within the if statement. I understand that this problem is easily solved by initializing index to anything before the if statement, but why does the compiler not initialize it? I also understand that Kotlin is still in beta; is this a bug, or is it intentional? Finally, I am using Replit as an online IDE; is there a chance that the compiler on the website simply is an outdated compiler?
A:
The compiler checks whether there is a path in your code that the index may not be initialized based on all the path available in your code apart from the value of the parameters. You have an if statement without any else. If you add the else statement you will not get any compile error.
|
Why does Kotlin's compiler not realize when a variable is initialized in an if statement?
|
The following example of Kotlin source code returns an error when compiled:
fun main() {
var index: Int // create an integer used to call an index of an array
val myArray = Array(5) {i -> i + 1} // create an array to call from
val condition = true // makes an if statement run true later
if (condition) {
index = 2 // sets index to 2
}
println( myArray[index] ) // should print 2; errors
}
The error says that the example did not initialize the variable index by the time it is called, even though it is guaranteed to initialize within the if statement. I understand that this problem is easily solved by initializing index to anything before the if statement, but why does the compiler not initialize it? I also understand that Kotlin is still in beta; is this a bug, or is it intentional? Finally, I am using Replit as an online IDE; is there a chance that the compiler on the website simply is an outdated compiler?
|
[
"The compiler checks whether there is a path in your code that the index may not be initialized based on all the path available in your code apart from the value of the parameters. You have an if statement without any else. If you add the else statement you will not get any compile error.\n"
] |
[
0
] |
[] |
[] |
[
"compiler_errors",
"kotlin"
] |
stackoverflow_0074661020_compiler_errors_kotlin.txt
|
Q:
How to copy my project folders and subfolders except contents (but PDF's must be included)
I'm a machine designer and I have a lots of project folders. I must copy my folders to public account, but public account area is limited. I must copy all folder structure include only pdf files. Other files must be except this. I.e. all folders and subfolders must be included and just pdf files.
If there is no pdf in that file, it should just copy the empty folder.
I can use only command prompt, I have no idea how I can with coding. Sorry for my English..
I tried search on google and I found this:
https://itigic.com/tr/use-xcopy-to-copy-a-folder-structure-in-windows/
"Xcopy" can be copy all folder structure but it can't copy pdf files.
I need only pdf files.
A:
Xcopy, Copies files and directory trees.
XCOPY source [destination] [/A | /M] [/D[:date]] [/P] [/S [/E]] [/V] [/W]
[/C] [/I] [/Q] [/F] [/L] [/G] [/H] [/R] [/T] [/U]
[/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z] [/B] [/J]
[/EXCLUDE:file1[+file2][+file3]...] [/COMPRESS]
It can seem daunting to a first-time user
" I must copy my folders to public account "
so first where in Public
Let us ASSUME "c:\users\PUBLIC\Public Documents" (WARNING note public is 2 times)
Make sure we will not destroy by overwrite other folders
WARNING Public Documents is a symbolic link thus that is NOT it's true folder name,
we must NOT have 2 Public, only 1 for xcopy, here I ask for a new folder called PDFs
Öte yandan /E, Xcopy'ye şunları da eklemesini söyler: alt klasörler tüm yapıyı kullanmak için boş olan, burada ilgilendiğimiz şey bu.
Navigate to the master folder you want to copy from
type cmd.exe in the address bar and press enter check cmd is showing that working folder>
and you want only all *.pdf and /E empty folders FROM THE CURRENT WORKING FOLDER. So from that working folder run xcopy, which should ask about the need for a new target.
xcopy *.pdf "c:\users\PUBLIC\DOCUMENTS\PDFs" /E
Does C:\users\PUBLIC\DOCUMENTS\PDFs specify a file name
or directory name on the target
(F = file, D = directory)? d
C:2022-11-16ExistingCustomerSRFINAL.pdf
C:2022-11-16NewBusinessSRFINAL.pdf
C:adobe_supplement_iso32000.pdf
....
many files and folders
...
C:tiff\TIFF6.pdf
C:tiff\TIFFphotoshop.pdf
C:tiff\TIFFPM6.pdf
|
How to copy my project folders and subfolders except contents (but PDF's must be included)
|
I'm a machine designer and I have a lots of project folders. I must copy my folders to public account, but public account area is limited. I must copy all folder structure include only pdf files. Other files must be except this. I.e. all folders and subfolders must be included and just pdf files.
If there is no pdf in that file, it should just copy the empty folder.
I can use only command prompt, I have no idea how I can with coding. Sorry for my English..
I tried search on google and I found this:
https://itigic.com/tr/use-xcopy-to-copy-a-folder-structure-in-windows/
"Xcopy" can be copy all folder structure but it can't copy pdf files.
I need only pdf files.
|
[
"Xcopy, Copies files and directory trees.\nXCOPY source [destination] [/A | /M] [/D[:date]] [/P] [/S [/E]] [/V] [/W]\n [/C] [/I] [/Q] [/F] [/L] [/G] [/H] [/R] [/T] [/U]\n [/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z] [/B] [/J]\n [/EXCLUDE:file1[+file2][+file3]...] [/COMPRESS]\n\nIt can seem daunting to a first-time user\n\" I must copy my folders to public account \"\nso first where in Public\n\nLet us ASSUME \"c:\\users\\PUBLIC\\Public Documents\" (WARNING note public is 2 times)\nMake sure we will not destroy by overwrite other folders\n\nWARNING Public Documents is a symbolic link thus that is NOT it's true folder name,\nwe must NOT have 2 Public, only 1 for xcopy, here I ask for a new folder called PDFs\n\nÖte yandan /E, Xcopy'ye şunları da eklemesini söyler: alt klasörler tüm yapıyı kullanmak için boş olan, burada ilgilendiğimiz şey bu.\n\nNavigate to the master folder you want to copy from\ntype cmd.exe in the address bar and press enter check cmd is showing that working folder>\n\nand you want only all *.pdf and /E empty folders FROM THE CURRENT WORKING FOLDER. So from that working folder run xcopy, which should ask about the need for a new target.\nxcopy *.pdf \"c:\\users\\PUBLIC\\DOCUMENTS\\PDFs\" /E\nDoes C:\\users\\PUBLIC\\DOCUMENTS\\PDFs specify a file name\nor directory name on the target\n(F = file, D = directory)? d\n\nC:2022-11-16ExistingCustomerSRFINAL.pdf\nC:2022-11-16NewBusinessSRFINAL.pdf\nC:adobe_supplement_iso32000.pdf\n....\nmany files and folders\n...\nC:tiff\\TIFF6.pdf\nC:tiff\\TIFFphotoshop.pdf\nC:tiff\\TIFFPM6.pdf\n\n\n\n"
] |
[
0
] |
[] |
[] |
[
"copy",
"copy_paste",
"directory",
"pdf",
"structure"
] |
stackoverflow_0074654860_copy_copy_paste_directory_pdf_structure.txt
|
Q:
.net 7 Razor pages with multiple route conventions not working
I got an old .net4.8 web app that uses MVC and controllers and trying to convert(Rewrite) it to .net 7 razor pages.
I am trying to change the old url routing to be a standard.
My Razor page routeing works fine and is as follows.
@page "/flights/{FromIata:length(3)?}/{ToIata:length(3)?}"
i have also tried
@page "/flights/{FromIata?}/{ToIata?}"
in my program.cs I added the other route conventions.
builder.Services.AddRazorPages()
.AddRazorPagesOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); })
.AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Flights", "/flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights", "/flights/{FromIata:length(3)}-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights", "/flights/{FromIata:length(3)}-to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights", "/flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}");
options.Conventions.AddPageRoute("/Flights", "/flights/to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights", "/flights/to-{ToIata:length(3)}-{CityName}");
options.Conventions.AddPageRoute("/Flights", "/flights/{*url}");
})
if I browse to the page with the standard convection it works fine but if i use any of the other conventions I get a 404 error.
What I am trying to do is either load the page with the other convention.
i.e /Flights/to-kul-kuala%20lumpur
or if i use that conventions it does a permanent redirect to the new url format.
i.e Flights/kul
Any suggestions would be greatly appreciated.
Thanks in advance.
A:
The route template that you provided to the @page directive begins with a forward slash. This makes it an override route, which negates all others. If you want to add other route templates, remove the leading forward slash:
@page "flights/{FromIata:length(3)?}/{ToIata:length(3)?}"
A:
the solutions was as above to remove the /
@page "flights/{FromIata:length(3)?}/{ToIata:length(3)?}"
and add index to the convention.
options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/{FromIata:length(3)}-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/{FromIata:length(3)}-to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}");
options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/Flights/to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/flights/to-{ToIata:length(3)}-{CityName}");
options.Conventions.AddPageRoute("/Flights/Index", "{Culture}/flights/{*url}");
|
.net 7 Razor pages with multiple route conventions not working
|
I got an old .net4.8 web app that uses MVC and controllers and trying to convert(Rewrite) it to .net 7 razor pages.
I am trying to change the old url routing to be a standard.
My Razor page routeing works fine and is as follows.
@page "/flights/{FromIata:length(3)?}/{ToIata:length(3)?}"
i have also tried
@page "/flights/{FromIata?}/{ToIata?}"
in my program.cs I added the other route conventions.
builder.Services.AddRazorPages()
.AddRazorPagesOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); })
.AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Flights", "/flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights", "/flights/{FromIata:length(3)}-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights", "/flights/{FromIata:length(3)}-to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights", "/flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}");
options.Conventions.AddPageRoute("/Flights", "/flights/to-{ToIata:length(3)}");
options.Conventions.AddPageRoute("/Flights", "/flights/to-{ToIata:length(3)}-{CityName}");
options.Conventions.AddPageRoute("/Flights", "/flights/{*url}");
})
if I browse to the page with the standard convection it works fine but if i use any of the other conventions I get a 404 error.
What I am trying to do is either load the page with the other convention.
i.e /Flights/to-kul-kuala%20lumpur
or if i use that conventions it does a permanent redirect to the new url format.
i.e Flights/kul
Any suggestions would be greatly appreciated.
Thanks in advance.
|
[
"The route template that you provided to the @page directive begins with a forward slash. This makes it an override route, which negates all others. If you want to add other route templates, remove the leading forward slash:\n@page \"flights/{FromIata:length(3)?}/{ToIata:length(3)?}\"\n\n",
"the solutions was as above to remove the /\n@page \"flights/{FromIata:length(3)?}/{ToIata:length(3)?}\"\n\nand add index to the convention.\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/from-{FromIata:length(3)}-to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/{FromIata:length(3)}-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/{FromIata:length(3)}-to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/from-{FromIata:length(3)}-{FromCity}-to-{ToIata:length(3)}-{ToCity}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/Flights/to-{ToIata:length(3)}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/flights/to-{ToIata:length(3)}-{CityName}\");\n options.Conventions.AddPageRoute(\"/Flights/Index\", \"{Culture}/flights/{*url}\");\n\n"
] |
[
1,
0
] |
[] |
[] |
[
".net_7.0",
"asp.net_mvc",
"razor_pages",
"routes",
"visual_studio_2022"
] |
stackoverflow_0074649965_.net_7.0_asp.net_mvc_razor_pages_routes_visual_studio_2022.txt
|
Q:
How do I automate subsetting a huge dataframe in R?
My data frame has many rows ( over 2 million), averaging around 60,000 per 359 samples.
One of my columns is called samples. I know how to subset the dataframe based on sample number
sample1 <- df[(df$sample ==1), ]
However, what I am unsure of is whether I can automate this for the 359 samples I have using something like a for loop or one of the apply functions
for(i in 1:nrow(df)){
sample(i) <- df[(df$sample == i), ]
}
So the output would be sample1, sample2 etc up until sample359 with the correct subsetting based on the sample column of the original file.
Would be grateful for any suggestions - thank you.
A:
It is not the best pratice, but this might work for you
for(i in 1:nrow(df)){
assign(value = df[(df$sample == i), ],x = paste0("sample",i),envir = globalenv())
}
A:
split() worked fine for what I needed (thank you for comments).
df_samp1 <- split(df, f=df$Sample ==1)
|
How do I automate subsetting a huge dataframe in R?
|
My data frame has many rows ( over 2 million), averaging around 60,000 per 359 samples.
One of my columns is called samples. I know how to subset the dataframe based on sample number
sample1 <- df[(df$sample ==1), ]
However, what I am unsure of is whether I can automate this for the 359 samples I have using something like a for loop or one of the apply functions
for(i in 1:nrow(df)){
sample(i) <- df[(df$sample == i), ]
}
So the output would be sample1, sample2 etc up until sample359 with the correct subsetting based on the sample column of the original file.
Would be grateful for any suggestions - thank you.
|
[
"It is not the best pratice, but this might work for you\nfor(i in 1:nrow(df)){\n assign(value = df[(df$sample == i), ],x = paste0(\"sample\",i),envir = globalenv())\n} \n\n",
"split() worked fine for what I needed (thank you for comments).\ndf_samp1 <- split(df, f=df$Sample ==1)\n"
] |
[
0,
0
] |
[] |
[] |
[
"r"
] |
stackoverflow_0074553551_r.txt
|
Q:
Python's range() analog in Common Lisp
How to create a list of consecutive numbers in Common Lisp?
In other words, what is the equivalent of Python's range function in Common Lisp?
In Python range(2, 10, 2) returns [2, 4, 6, 8], with first and last arguments being optional. I couldn't find the idiomatic way to create a sequence of numbers, though Emacs Lisp has number-sequence.
Range could be emulated using loop macro, but i want to know the accepted way to generate a sequence of numbers with start and end points and step.
Related: Analog of Python's range in Scheme
A:
There is no built-in way of generating a sequence of numbers, the canonical way of doing so is to do one of:
Use loop
Write a utility function that uses loop
An example implementation would be (this only accepts counting "from low" to "high"):
(defun range (max &key (min 0) (step 1))
(loop for n from min below max by step
collect n))
This allows you to specify an (optional) minimum value and an (optional) step value.
To generate odd numbers: (range 10 :min 1 :step 2)
A:
alexandria implements scheme's iota:
(ql:quickload :alexandria)
(alexandria:iota 4 :start 2 :step 2)
;; (2 4 6 8)
A:
Here's how I'd approach the problem:
(defun generate (from to &optional (by 1))
#'(lambda (f)
(when (< from to)
(prog1 (or (funcall f from) t)
(incf from by)))))
(defmacro with-generator ((var from to &optional (by 1)) &body body)
(let ((generator (gensym)))
`(loop with ,generator = (generate ,from ,to ,by)
while
(funcall ,generator
#'(lambda (,var) ,@body)))))
(with-generator (i 1 10)
(format t "~&i = ~s" i))
But this is just the general idea, there's a lot of room for improvement.
OK, since there seems to be a discussion here. I've assumed that what is really needed is the analogue to Python's range generator function. Which, in certain sense generates a list of numbers, but does it so by yielding a number each iteration (so that it doesn't create more then one item at a time). Generators are a somewhat rare concept (few languages implement it), so I assumed that the mention of Python suggested that this exact feature is desired.
Following some criticism of my example above, here's a different example that illustrates the reason to why a generator might be used rather then a simple loop.
(defun generate (from to &optional (by 1))
#'(lambda ()
(when (< from to)
(prog1 from
(incf from by)))))
(defmacro with-generator
((var generator &optional (exit-condition t)) &body body)
(let ((g (gensym)))
`(do ((,g ,generator))
(nil)
(let ((,var (funcall ,g)))
(when (or (null ,var) ,exit-condition)
(return ,g))
,@body))))
(let ((gen
(with-generator (i (generate 1 10) (> i 4))
(format t "~&i = ~s" i))))
(format t "~&in the middle")
(with-generator (j gen (> j 7))
(format t "~&j = ~s" j)))
;; i = 1
;; i = 2
;; i = 3
;; i = 4
;; in the middle
;; j = 6
;; j = 7
This is, again, only an illustration of the purpose of this function. It is probably wasteful to use it for generating integers, even if you need to do that in two steps, but generators are best with parsers, when you want to yield a more complex object which is built based upon the previous state of the parser, for example, and a bunch of other things. Well, you can read an argument about it here: http://en.wikipedia.org/wiki/Generator_%28computer_programming%29
A:
Using recursion:
(defun range (min max &optional (step 1))
(when (<= min max)
(cons min (range (+ min step) max step))))
A:
In simple form specifying start, stop, step:
(defun range (start stop step)
(do (
(i start (+ i step))
(acc '() (push i acc)))
((>= i stop) (nreverse acc))))
A:
You may want to try snakes:
"Python style generators for Common Lisp. Includes a port of itertools."
It is available in Quicklisp. There may be other Common Lisp libraries that can help.
A:
Not finding what I wanted nor wanting to use an external package, I ended up writing my own version which differs from the python version (hopefully improving on it) and avoids loop. If you think it is really inefficient and can improve on it, please do.
;; A version of range taking the form (range [[first] last [[step]]]).
;; It takes negative numbers and corrects STEP to the same direction
;; as FIRST to LAST then returns a list starting from FIRST and
;; ending before LAST
(defun range (&rest args)
(case (length args)
( (0) '())
( (1) (range 0 (car args) (if (minusp (car args)) -1 1)))
( (2) (range (car args) (cadr args)
(if (>= (car args) (cadr args)) -1 1)))
( (3) (let* ((start (car args)) (end (cadr args))
(step (abs (caddr args))))
(if (>= end start)
(do ((i start (+ i step))
(acc '() (push i acc)))
((>= i end) (nreverse acc)))
(do ((i start (- i step))
(acc '() (push i acc)))
((<= i end) (nreverse acc))))))
(t (error "ERROR, too many arguments for range"))))
;; (range-inc [[first] last [[step]]] ) includes LAST in the returned range
(defun range-inc (&rest args)
(case (length args)
( (0) '())
( (1) (append (range (car args)) args))
( (2) (append (range (car args) (cadr args)) (cdr args)))
( (3) (append (range (car args) (cadr args) (caddr args))
(list (cadr args))))
(t (error "ERROR, too many arguments for range-inc"))))
Note: I wrote a scheme version as well
A:
Here is a range function to generate a list of numbers.
We use the do "loop". If there is such a thing as a functional loop, then do macro is it. Although there is no recursion, when you construct a do, I find the thinking is very similar. You consider each variable in the do in the same way you consider each argument in a recursive call.
I use list* instead of cons. list* is exactly the same as cons except you can have 1, 2, or more arguments. (list 1 2 3 4 nil) and (cons 1 (cons 2 (cons 3 (cons 4 nil)))).
(defun range (from-n to-n &optional (step 1)) ; step defaults to 1
(do ((n from-n (+ n step)) ; n initializes to from-n, increments by step
(lst nil (list* n lst))) ; n "pushed" or "prepended" to lst
((> n to-n) ; the "recursion" termination condition
(reverse lst)))) ; prepending with list* more efficient than using append
; however, need extra step to reverse lst so that
; numbers are in order
Here is a test session:
CL-USER 23 > (range 0 10)
(0 1 2 3 4 5 6 7 8 9 10)
CL-USER 24 > (range 10 0 -1)
NIL
CL-USER 25 > (range 10 0 1)
NIL
CL-USER 26 > (range 1 21 2)
(1 3 5 7 9 11 13 15 17 19 21)
CL-USER 27 > (reverse (range 1 21 2))
(21 19 17 15 13 11 9 7 5 3 1)
CL-USER 28 >
This version does not work for decreasing sequences. However, you see that you can use reverse to get a decreasing sequence.
A:
Needed to implement (range n) in a tiny Lisp that just had dotimes and setq available:
(defun range (&rest args)
(let ( (to '()) )
(cond
((= (length args) 1) (dotimes (i (car args))
(push i to)))
((= (length args) 2) (dotimes (i (- (cadr args) (car args)))
(push (+ i (car args)) to))))
(nreverse to)))
Example:
> (range 10)
(0 1 2 3 4 5 6 7 8 9)
> (range 10 15)
(10 11 12 13 14)
A:
Just in case, here is an analogue to user1969453's answer that returns a vector instead of a list:
(defun seq (from to &optional (step 1))
(do ((acc (make-array 1 :adjustable t :fill-pointer 0))
(i from (+ i step)))
((> i to) acc) (vector-push-extend i acc)))
Or, if you want to pre-allocate the vector and skip the 'vector-push' idiom:
(defun seq2 (from to &optional (step 1))
(let ((size (+ 1 (floor (/ (- to from) step))))) ; size is 1 + floor((to - from) / step))
(do ((acc (make-array size))
(i from (+ i step))
(count 0 (1+ count)))
((> i to) acc) (setf (aref acc count) i))))
|
Python's range() analog in Common Lisp
|
How to create a list of consecutive numbers in Common Lisp?
In other words, what is the equivalent of Python's range function in Common Lisp?
In Python range(2, 10, 2) returns [2, 4, 6, 8], with first and last arguments being optional. I couldn't find the idiomatic way to create a sequence of numbers, though Emacs Lisp has number-sequence.
Range could be emulated using loop macro, but i want to know the accepted way to generate a sequence of numbers with start and end points and step.
Related: Analog of Python's range in Scheme
|
[
"There is no built-in way of generating a sequence of numbers, the canonical way of doing so is to do one of:\n\nUse loop\nWrite a utility function that uses loop\n\nAn example implementation would be (this only accepts counting \"from low\" to \"high\"):\n(defun range (max &key (min 0) (step 1))\n (loop for n from min below max by step\n collect n))\n\nThis allows you to specify an (optional) minimum value and an (optional) step value.\nTo generate odd numbers: (range 10 :min 1 :step 2)\n",
"alexandria implements scheme's iota:\n(ql:quickload :alexandria)\n(alexandria:iota 4 :start 2 :step 2)\n;; (2 4 6 8)\n\n",
"Here's how I'd approach the problem:\n(defun generate (from to &optional (by 1))\n #'(lambda (f)\n (when (< from to)\n (prog1 (or (funcall f from) t)\n (incf from by)))))\n\n(defmacro with-generator ((var from to &optional (by 1)) &body body)\n (let ((generator (gensym)))\n `(loop with ,generator = (generate ,from ,to ,by)\n while\n (funcall ,generator\n #'(lambda (,var) ,@body)))))\n\n(with-generator (i 1 10)\n (format t \"~&i = ~s\" i))\n\nBut this is just the general idea, there's a lot of room for improvement.\n\nOK, since there seems to be a discussion here. I've assumed that what is really needed is the analogue to Python's range generator function. Which, in certain sense generates a list of numbers, but does it so by yielding a number each iteration (so that it doesn't create more then one item at a time). Generators are a somewhat rare concept (few languages implement it), so I assumed that the mention of Python suggested that this exact feature is desired.\nFollowing some criticism of my example above, here's a different example that illustrates the reason to why a generator might be used rather then a simple loop.\n(defun generate (from to &optional (by 1))\n #'(lambda ()\n (when (< from to)\n (prog1 from\n (incf from by)))))\n\n(defmacro with-generator\n ((var generator &optional (exit-condition t)) &body body)\n (let ((g (gensym)))\n `(do ((,g ,generator))\n (nil)\n (let ((,var (funcall ,g)))\n (when (or (null ,var) ,exit-condition)\n (return ,g))\n ,@body))))\n\n(let ((gen\n (with-generator (i (generate 1 10) (> i 4))\n (format t \"~&i = ~s\" i))))\n (format t \"~&in the middle\")\n (with-generator (j gen (> j 7))\n (format t \"~&j = ~s\" j)))\n\n;; i = 1\n;; i = 2\n;; i = 3\n;; i = 4\n;; in the middle\n;; j = 6\n;; j = 7\n\nThis is, again, only an illustration of the purpose of this function. It is probably wasteful to use it for generating integers, even if you need to do that in two steps, but generators are best with parsers, when you want to yield a more complex object which is built based upon the previous state of the parser, for example, and a bunch of other things. Well, you can read an argument about it here: http://en.wikipedia.org/wiki/Generator_%28computer_programming%29\n",
"Using recursion:\n(defun range (min max &optional (step 1))\n (when (<= min max)\n (cons min (range (+ min step) max step))))\n\n",
"In simple form specifying start, stop, step:\n(defun range (start stop step) \n (do (\n (i start (+ i step)) \n (acc '() (push i acc))) \n ((>= i stop) (nreverse acc))))\n\n",
"You may want to try snakes:\n\"Python style generators for Common Lisp. Includes a port of itertools.\"\nIt is available in Quicklisp. There may be other Common Lisp libraries that can help.\n",
"Not finding what I wanted nor wanting to use an external package, I ended up writing my own version which differs from the python version (hopefully improving on it) and avoids loop. If you think it is really inefficient and can improve on it, please do. \n;; A version of range taking the form (range [[first] last [[step]]]).\n;; It takes negative numbers and corrects STEP to the same direction\n;; as FIRST to LAST then returns a list starting from FIRST and\n;; ending before LAST\n(defun range (&rest args)\n (case (length args) \n ( (0) '()) \n ( (1) (range 0 (car args) (if (minusp (car args)) -1 1))) \n ( (2) (range (car args) (cadr args) \n (if (>= (car args) (cadr args)) -1 1))) \n ( (3) (let* ((start (car args)) (end (cadr args)) \n (step (abs (caddr args))))\n (if (>= end start)\n (do ((i start (+ i step))\n (acc '() (push i acc)))\n ((>= i end) (nreverse acc)))\n (do ((i start (- i step))\n (acc '() (push i acc)))\n ((<= i end) (nreverse acc))))))\n (t (error \"ERROR, too many arguments for range\"))))\n\n\n;; (range-inc [[first] last [[step]]] ) includes LAST in the returned range\n(defun range-inc (&rest args)\n (case (length args)\n ( (0) '())\n ( (1) (append (range (car args)) args))\n ( (2) (append (range (car args) (cadr args)) (cdr args)))\n ( (3) (append (range (car args) (cadr args) (caddr args))\n (list (cadr args))))\n (t (error \"ERROR, too many arguments for range-inc\"))))\n\nNote: I wrote a scheme version as well\n",
"Here is a range function to generate a list of numbers.\nWe use the do \"loop\". If there is such a thing as a functional loop, then do macro is it. Although there is no recursion, when you construct a do, I find the thinking is very similar. You consider each variable in the do in the same way you consider each argument in a recursive call.\nI use list* instead of cons. list* is exactly the same as cons except you can have 1, 2, or more arguments. (list 1 2 3 4 nil) and (cons 1 (cons 2 (cons 3 (cons 4 nil)))).\n(defun range (from-n to-n &optional (step 1)) ; step defaults to 1\n (do ((n from-n (+ n step)) ; n initializes to from-n, increments by step\n (lst nil (list* n lst))) ; n \"pushed\" or \"prepended\" to lst\n\n ((> n to-n) ; the \"recursion\" termination condition\n (reverse lst)))) ; prepending with list* more efficient than using append\n ; however, need extra step to reverse lst so that\n ; numbers are in order\n\nHere is a test session:\n\nCL-USER 23 > (range 0 10)\n(0 1 2 3 4 5 6 7 8 9 10)\nCL-USER 24 > (range 10 0 -1)\nNIL\nCL-USER 25 > (range 10 0 1)\nNIL\nCL-USER 26 > (range 1 21 2)\n(1 3 5 7 9 11 13 15 17 19 21)\nCL-USER 27 > (reverse (range 1 21 2))\n(21 19 17 15 13 11 9 7 5 3 1)\nCL-USER 28 > \n\nThis version does not work for decreasing sequences. However, you see that you can use reverse to get a decreasing sequence.\n",
"Needed to implement (range n) in a tiny Lisp that just had dotimes and setq available:\n(defun range (&rest args)\n (let ( (to '()) )\n (cond \n ((= (length args) 1) (dotimes (i (car args))\n (push i to)))\n ((= (length args) 2) (dotimes (i (- (cadr args) (car args)))\n (push (+ i (car args)) to))))\n (nreverse to)))\n\nExample:\n> (range 10)\n(0 1 2 3 4 5 6 7 8 9)\n\n> (range 10 15)\n(10 11 12 13 14)\n\n",
"Just in case, here is an analogue to user1969453's answer that returns a vector instead of a list:\n(defun seq (from to &optional (step 1))\n (do ((acc (make-array 1 :adjustable t :fill-pointer 0))\n (i from (+ i step)))\n ((> i to) acc) (vector-push-extend i acc)))\n\nOr, if you want to pre-allocate the vector and skip the 'vector-push' idiom:\n(defun seq2 (from to &optional (step 1))\n (let ((size (+ 1 (floor (/ (- to from) step))))) ; size is 1 + floor((to - from) / step))\n (do ((acc (make-array size))\n (i from (+ i step))\n (count 0 (1+ count)))\n ((> i to) acc) (setf (aref acc count) i))))\n\n"
] |
[
41,
19,
6,
4,
2,
1,
1,
0,
0,
0
] |
[
"Recursive solution:\n(defun range(min max &optional (step 1))\n (if (> min max)\n ()\n (cons min (range (+ min step) max step))))\n\nExample:\n(range 1 10 3)\n(1 4 7 10)\n\n"
] |
[
-1
] |
[
"common_lisp",
"number_sequence",
"python"
] |
stackoverflow_0013937520_common_lisp_number_sequence_python.txt
|
Q:
Get maximum rows from all subgroups with groupby method (Python)
I have this data frame, inside of it I have 3 columns 'Region', 'State or Province', 'Sales'
I already grouped by Regions and State or Province and wanted to get values in sales. But I want to get maximum State from every Region!how can I get that?
sales_by_state = df_n.groupby(['Region', 'State or Province'])['Sales'].sum()
sales_by_state = sales_by_state.to_frame()
sales_by_state
A:
To get the maximum value of sales for each region, you can use the 'idxmax()' function on the groupby object. This will return the index of the maximum value for each group, which you can then use to index into the original data frame to get the corresponding rows.
Here is an example:
# Get the maximum sales for each region
max_sales = sales_by_state.groupby(level=0)['Sales'].idxmax()
# Use the index of the maximum sales to index into the original data frame
max_sales_by_state = df_n.loc[max_sales]
This will return a new data frame containing the rows from the original data frame that correspond to the maximum sales for each region. You can then access the values in the 'State or Province' column to get the maximum state for each region.
Alternatively, you can use the 'apply()' method on the groupby object to apply a custom function to each group. This function can return the state with the maximum sales for the group, which you can then use to create a new column in the data frame containing the maximum state for each region.
Here is an example:
# Define a custom function that returns the state with the maximum sales for a group
def get_max_state(group):
# Index into the group to get the state with the maximum sales
return group.loc[group['Sales'].idxmax()]['State or Province']
# Apply the custom function to each group and create a new column with the results
sales_by_state['Max State'] = sales_by_state.groupby(level=0).apply(get_max_state)
This will add a new column to the 'sales_by_state' data frame containing the maximum state for each region.
|
Get maximum rows from all subgroups with groupby method (Python)
|
I have this data frame, inside of it I have 3 columns 'Region', 'State or Province', 'Sales'
I already grouped by Regions and State or Province and wanted to get values in sales. But I want to get maximum State from every Region!how can I get that?
sales_by_state = df_n.groupby(['Region', 'State or Province'])['Sales'].sum()
sales_by_state = sales_by_state.to_frame()
sales_by_state
|
[
"To get the maximum value of sales for each region, you can use the 'idxmax()' function on the groupby object. This will return the index of the maximum value for each group, which you can then use to index into the original data frame to get the corresponding rows.\nHere is an example:\n# Get the maximum sales for each region\nmax_sales = sales_by_state.groupby(level=0)['Sales'].idxmax()\n\n# Use the index of the maximum sales to index into the original data frame\nmax_sales_by_state = df_n.loc[max_sales]\n\nThis will return a new data frame containing the rows from the original data frame that correspond to the maximum sales for each region. You can then access the values in the 'State or Province' column to get the maximum state for each region.\nAlternatively, you can use the 'apply()' method on the groupby object to apply a custom function to each group. This function can return the state with the maximum sales for the group, which you can then use to create a new column in the data frame containing the maximum state for each region.\nHere is an example:\n# Define a custom function that returns the state with the maximum sales for a group\ndef get_max_state(group):\n # Index into the group to get the state with the maximum sales\n return group.loc[group['Sales'].idxmax()]['State or Province']\n\n# Apply the custom function to each group and create a new column with the results\nsales_by_state['Max State'] = sales_by_state.groupby(level=0).apply(get_max_state)\n\nThis will add a new column to the 'sales_by_state' data frame containing the maximum state for each region.\n"
] |
[
1
] |
[] |
[] |
[
"dataframe",
"group_by",
"max",
"pandas",
"python"
] |
stackoverflow_0074662271_dataframe_group_by_max_pandas_python.txt
|
Q:
Is there any function similar to Python's max(a, b) in Solidity, to find the maximum value between several given?
Of course, it could be done via conditionals but I would like to know if there is a more straight-forward approach.
If there isnt any explicit way, what would be the optimal way to implement it?
A:
In the current version 0.8, there's no native function to get a min/max value from a set of input numbers.
For a static number of values, you could implement a simple condition (or a set of conditions if there's more than 2 values):
function max(uint256 a, uint256 b) external pure returns (uint256) {
return a >= b ? a : b;
}
For a dynamic number of values, you can simply loop through the input array and keep track of the smallest/largest value:
function max(uint256[] memory numbers) external pure returns (uint256) {
require(numbers.length > 0); // throw an exception if the condition is not met
uint256 maxNumber; // default 0, the lowest value of `uint256`
for (uint256 i = 0; i < numbers.length; i++) {
if (numbers[i] > maxNumber) {
maxNumber = numbers[i];
}
}
return maxNumber;
}
This functions has a linear complexity. Read-only calls are gas free, but mind the complexity if you're executing the max() from another function as a result of a transaction (that cost gas fees).
A:
OpenZeppelin offers a Math.max function that you can use for this:
import "openzeppelin-contracts/utils/math/Math.sol";
uint256 max = Math.max(a, b);
https://docs.openzeppelin.com/contracts/3.x/api/math#Math-max-uint256-uint256-
|
Is there any function similar to Python's max(a, b) in Solidity, to find the maximum value between several given?
|
Of course, it could be done via conditionals but I would like to know if there is a more straight-forward approach.
If there isnt any explicit way, what would be the optimal way to implement it?
|
[
"In the current version 0.8, there's no native function to get a min/max value from a set of input numbers.\nFor a static number of values, you could implement a simple condition (or a set of conditions if there's more than 2 values):\nfunction max(uint256 a, uint256 b) external pure returns (uint256) {\n return a >= b ? a : b;\n}\n\nFor a dynamic number of values, you can simply loop through the input array and keep track of the smallest/largest value:\nfunction max(uint256[] memory numbers) external pure returns (uint256) {\n require(numbers.length > 0); // throw an exception if the condition is not met\n uint256 maxNumber; // default 0, the lowest value of `uint256`\n\n for (uint256 i = 0; i < numbers.length; i++) {\n if (numbers[i] > maxNumber) {\n maxNumber = numbers[i];\n }\n }\n\n return maxNumber;\n}\n\nThis functions has a linear complexity. Read-only calls are gas free, but mind the complexity if you're executing the max() from another function as a result of a transaction (that cost gas fees).\n",
"OpenZeppelin offers a Math.max function that you can use for this:\nimport \"openzeppelin-contracts/utils/math/Math.sol\";\n\nuint256 max = Math.max(a, b);\n\n\nhttps://docs.openzeppelin.com/contracts/3.x/api/math#Math-max-uint256-uint256-\n"
] |
[
4,
0
] |
[] |
[] |
[
"solidity"
] |
stackoverflow_0070940361_solidity.txt
|
Q:
Initialize an array of structs containing dynamic arrays
I am trying to create a table of elements (structs) where each element contains a dynamic list of enums in C. However, it seems this is not possible in C as I keep getting the following error:
error: initialization of flexible array member in a nested context
Here is a small sample of my code:
#include <stdio.h>
#include <stdint.h>
typedef enum {
NET_0 = 0,
NET_1,
NET_2,
TOTAL_NETS,
} net_t;
typedef struct {
uint8_t num_nets;
net_t net_list[];
} sig_to_net_t;
sig_to_net_t SIG_NET_MAPPING[] = {
{1, {NET_0}},
{2, {NET_1, NET_2}},
{1, {NET_2}},
};
Any solution for this issue in C?
FYI, the only solution I found would be to replace the dynamic array net_list with a fixed-size array. However, this solution is not optimal as this code will be flashed on memory-limited devices and I have cases where the net_list will contain 5 elements which are only a few cases out of 1000 entries in the SIG_NET_MAPPING table.
A:
You can use pointer to array of enums:
typedef enum {
NET_0 = 0,
NET_1,
NET_2,
TOTAL_NETS,
} net_t;
typedef struct {
uint8_t num_nets;
net_t *net_list;
} sig_to_net_t;
sig_to_net_t SIG_NET_MAPPING[] = {
{.num_nets = 1, .net_list = (net_t[]){NET_0}},
{.num_nets = 2, .net_list = (net_t[]){NET_1, NET_2}},
};
https://godbolt.org/z/EMz9qqeYc
If you want to have in FLASH in embedded system add some consts
typedef struct {
uint8_t num_nets;
const net_t *const net_list;
} sig_to_net_t;
const sig_to_net_t SIG_NET_MAPPING[] = {
{.num_nets = 1, .net_list = (const net_t[]){NET_0}},
{.num_nets = 2, .net_list = (const net_t[]){NET_1, NET_2}},
};
A:
Using a fixed size array is your only option.
A struct with a flexible array member is not allowed to be a member of an array (or another struct). One reason for this is that there's no way to know exactly where one array element ends and another one starts if each one could have a different size.
One way you can manage the size is to either change the type of the net_list member to char or use a compiler option like gcc's -fshort-enums to make the enum type only take up one byte.
A:
To add to 0___________'s answer; you can use macros to make sure num_nets is correct:
https://godbolt.org/z/8PE617YbT
/* gcc -Wno-incompatible-pointer-types .\multisize_array.c -o .\multisize_array.exe */
#include <stdio.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
typedef enum {
NET_0 = 0,
NET_1,
NET_2,
TOTAL_NETS,
} net_t;
typedef struct {
uint8_t num_nets;
net_t * net_list;
} sig_to_net_t;
#define array_size(ARR) (sizeof(ARR)/sizeof(ARR[0]))
#define NET_MAPPING(...) { \
.num_nets = array_size(((net_t[]){__VA_ARGS__})), \
.net_list = (net_t[]){__VA_ARGS__} \
}
sig_to_net_t SIG_NET_MAPPING[] = {
NET_MAPPING(NET_0),
NET_MAPPING(NET_1, NET_2),
NET_MAPPING(NET_1, NET_2),
NET_MAPPING(NET_2, NET_2, NET_2, NET_2, NET_2, NET_2, NET_2, NET_2),
};
#define array_size(ARR) (sizeof(ARR)/sizeof(ARR[0]))
int main(void)
{
int ret = 0;
for (int i = 0 ; i < array_size(SIG_NET_MAPPING) ; i++ ) {
const sig_to_net_t * const pStn = &SIG_NET_MAPPING[i];
printf("{");
const char * sep = "";
for (int ii = 0 ; ii < pStn->num_nets ; ii++ ) {
printf("%s%d", sep, pStn->net_list[ii]);
sep = ", ";
}
printf("}\n");
}
return ret;
}
|
Initialize an array of structs containing dynamic arrays
|
I am trying to create a table of elements (structs) where each element contains a dynamic list of enums in C. However, it seems this is not possible in C as I keep getting the following error:
error: initialization of flexible array member in a nested context
Here is a small sample of my code:
#include <stdio.h>
#include <stdint.h>
typedef enum {
NET_0 = 0,
NET_1,
NET_2,
TOTAL_NETS,
} net_t;
typedef struct {
uint8_t num_nets;
net_t net_list[];
} sig_to_net_t;
sig_to_net_t SIG_NET_MAPPING[] = {
{1, {NET_0}},
{2, {NET_1, NET_2}},
{1, {NET_2}},
};
Any solution for this issue in C?
FYI, the only solution I found would be to replace the dynamic array net_list with a fixed-size array. However, this solution is not optimal as this code will be flashed on memory-limited devices and I have cases where the net_list will contain 5 elements which are only a few cases out of 1000 entries in the SIG_NET_MAPPING table.
|
[
"You can use pointer to array of enums:\ntypedef enum {\n NET_0 = 0,\n NET_1,\n NET_2,\n TOTAL_NETS,\n} net_t;\n\ntypedef struct {\n uint8_t num_nets;\n net_t *net_list;\n} sig_to_net_t;\n\nsig_to_net_t SIG_NET_MAPPING[] = {\n {.num_nets = 1, .net_list = (net_t[]){NET_0}},\n {.num_nets = 2, .net_list = (net_t[]){NET_1, NET_2}},\n};\n\nhttps://godbolt.org/z/EMz9qqeYc\nIf you want to have in FLASH in embedded system add some consts\ntypedef struct {\n uint8_t num_nets;\n const net_t *const net_list;\n} sig_to_net_t;\n\nconst sig_to_net_t SIG_NET_MAPPING[] = {\n {.num_nets = 1, .net_list = (const net_t[]){NET_0}},\n {.num_nets = 2, .net_list = (const net_t[]){NET_1, NET_2}},\n};\n\n",
"Using a fixed size array is your only option.\nA struct with a flexible array member is not allowed to be a member of an array (or another struct). One reason for this is that there's no way to know exactly where one array element ends and another one starts if each one could have a different size.\nOne way you can manage the size is to either change the type of the net_list member to char or use a compiler option like gcc's -fshort-enums to make the enum type only take up one byte.\n",
"To add to 0___________'s answer; you can use macros to make sure num_nets is correct:\nhttps://godbolt.org/z/8PE617YbT\n/* gcc -Wno-incompatible-pointer-types .\\multisize_array.c -o .\\multisize_array.exe */\n\n#include <stdio.h>\n#include <stdbool.h>\n\n#include <stdio.h>\n#include <stdint.h>\n\ntypedef enum {\n NET_0 = 0,\n NET_1,\n NET_2,\n TOTAL_NETS,\n} net_t;\n\ntypedef struct {\n uint8_t num_nets;\n net_t * net_list;\n} sig_to_net_t;\n\n#define array_size(ARR) (sizeof(ARR)/sizeof(ARR[0]))\n\n#define NET_MAPPING(...) { \\\n .num_nets = array_size(((net_t[]){__VA_ARGS__})), \\\n .net_list = (net_t[]){__VA_ARGS__} \\\n}\n\nsig_to_net_t SIG_NET_MAPPING[] = {\n NET_MAPPING(NET_0),\n NET_MAPPING(NET_1, NET_2),\n NET_MAPPING(NET_1, NET_2),\n NET_MAPPING(NET_2, NET_2, NET_2, NET_2, NET_2, NET_2, NET_2, NET_2),\n};\n\n#define array_size(ARR) (sizeof(ARR)/sizeof(ARR[0]))\n\nint main(void)\n{\n int ret = 0;\n for (int i = 0 ; i < array_size(SIG_NET_MAPPING) ; i++ ) {\n const sig_to_net_t * const pStn = &SIG_NET_MAPPING[i];\n printf(\"{\");\n const char * sep = \"\";\n for (int ii = 0 ; ii < pStn->num_nets ; ii++ ) {\n printf(\"%s%d\", sep, pStn->net_list[ii]);\n sep = \", \";\n }\n printf(\"}\\n\");\n }\n return ret;\n}\n\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"arrays",
"c",
"dynamic",
"struct"
] |
stackoverflow_0074661513_arrays_c_dynamic_struct.txt
|
Q:
Python can't locate .so shared library with ctypes.CDLL - Windows
I am trying to run a C function in Python. I followed examples online, and compiled the C source file into a .so shared library, and tried to pass it into the ctypes CDLL() initializer function.
import ctypes
cFile = ctypes.CDLL("libchess.so")
At this point python crashes with the message:
Could not find module 'C:\Users\user\PycharmProjects\project\libchess.so' (or one of its dependencies). Try using the full path with constructor syntax.
libchess.so is in the same directory as this Python file, so I don't see why there would be an issue finding it.
I read some stuff about how shared libraries might be hidden from later versions of python, but the suggested solutions I tried did not work. Most solutions were also referring to fixes involving linux system environment variables, but I'm on Windows.
Things I've tried that have not worked:
changing "libchess.so" to "./libchess.so" or the full path
using cdll.LoadLibrary() instead of CDLL() (apparently both do the same thing)
adding the parent directory to system PATH variable
putting os.add_dll_directory(os.getcwd()) in the code before trying to load the file
Any more suggestions are appreciated.
A:
Solved:
Detailed explanation here: https://stackoverflow.com/a/64472088/16044321
The issue is specific to how Python performs a DLL/SO search on Windows. While the ctypes docs do not specify this, the CDLL() function requires the optional argument winmode=0 to work correctly on Windows when loading a .dll or .so. This issue is also specific to Python versions greater than 3.8.
Thus, simply changing the 2nd line to cFile = ctypes.CDLL("libchess.so", winmode=0) works as expected.
|
Python can't locate .so shared library with ctypes.CDLL - Windows
|
I am trying to run a C function in Python. I followed examples online, and compiled the C source file into a .so shared library, and tried to pass it into the ctypes CDLL() initializer function.
import ctypes
cFile = ctypes.CDLL("libchess.so")
At this point python crashes with the message:
Could not find module 'C:\Users\user\PycharmProjects\project\libchess.so' (or one of its dependencies). Try using the full path with constructor syntax.
libchess.so is in the same directory as this Python file, so I don't see why there would be an issue finding it.
I read some stuff about how shared libraries might be hidden from later versions of python, but the suggested solutions I tried did not work. Most solutions were also referring to fixes involving linux system environment variables, but I'm on Windows.
Things I've tried that have not worked:
changing "libchess.so" to "./libchess.so" or the full path
using cdll.LoadLibrary() instead of CDLL() (apparently both do the same thing)
adding the parent directory to system PATH variable
putting os.add_dll_directory(os.getcwd()) in the code before trying to load the file
Any more suggestions are appreciated.
|
[
"Solved:\nDetailed explanation here: https://stackoverflow.com/a/64472088/16044321\nThe issue is specific to how Python performs a DLL/SO search on Windows. While the ctypes docs do not specify this, the CDLL() function requires the optional argument winmode=0 to work correctly on Windows when loading a .dll or .so. This issue is also specific to Python versions greater than 3.8.\nThus, simply changing the 2nd line to cFile = ctypes.CDLL(\"libchess.so\", winmode=0) works as expected.\n"
] |
[
0
] |
[] |
[] |
[
"ctypes",
"python",
"shared_libraries"
] |
stackoverflow_0074655061_ctypes_python_shared_libraries.txt
|
Q:
How do I store data from form and display it on a new page using javascript?
I need to make a form with 2 input fields. When you press submit it should take you to a new page and display the input data.
This is my html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Film survey</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form id="form" action="./Success.html">
<h1>Movie survey</h1>
<p>Thank you for participating in the film festival!</p>
<p>Please fill out this short survey so we can record your feedback</p>
<div>
<label for="film">What film did you watch?</label>
</div>
<div>
<input type="text" id="film" name="film" required />
</div>
<div>
<label for="rating"
>How would you rate the film? (1 - very bad, 5 - very good)
</label>
</div>
<input type="text" id="rating" name="rating" required />
<div><button class="submit">Submit</button></div>
</form>
<script src="script.js"></script>
</body>
</html>
This is my js code
const formEl = document.querySelector("#form");
formEl.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(formEl);
fetch("https://reqres.in/api/form", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
film: formData.get("film"),
rating: formData.get("rating"),
}),
})
.then((response) => {
window.location.href = "./Success.html";
})
.catch((error) => {
console.error(error);
});
});
I have a second html page called Success.html which I want to display tha data given in the form. I need to make a mock API so I tried using reqres.
This is my Success.html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Success</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Thank you for your feedback!</h1>
<p>You watched: <span id="film"></span></p>
<p>You rated it: <span id="rating"></span></p>
<script>
const formData = JSON.parse(request.body);
const filmEl = document.querySelector("#film");
const ratingEl = document.querySelector("#rating");
filmEl.textContent = formData.film;
ratingEl.textContent = formData.rating;
</script>
</body>
</html>
I thought this would work but I get this error after pressing submit:
`` Success.html:16 Uncaught ReferenceError: request is not defined
at Success.html:16:35
A:
The line const formData = JSON.parse(request.body); in your success.html is trying to reference a variable named request, which isn't defined in the scope of the <script> tag that it's contained in - that's why you're getting the ReferenceError: request is not defined error.
This other Stackoverflow question seems similar to yours - I have linked you to an answer that I think would be helpful. In short, you could pull the values you care about out of your response, then pass them via query parameters to be displayed in your success.html.
Along those same lines, it might make sense for your mock API to respond with a 302 status code and location header including film and rating query parameters that points to your success page.
A:
You can pass along data between web pages in several ways, using JSON data { foo: 'bar' } as an example:
1. Use URL parameter:
Stringify and URL encode your JSON response (full or needed data only), and pass along via a URL parameter
Example: 'data=' + encodeURIComponent(JSON.stringify(data)), resulting in data=%7B%20foo%3A%20'bar'%20%7D
Keep in mind that there is a limit to URL length, varying from 2k to 64k depending on browser
2. Use browser local storage:
The quota is browser specific, in range of 5-10MB, e.g. much larger than URL length
To set in the form page: localStorage.setItem('myFormData', JSON.stringify(data));
To read in success page: let data = JSON.parse(localStorage.getItem('myFormData'); (you likely want to add some error handling)
3. Temporarily POST data
You post the JSON data back to the server to /success
Your success page is delivered dynamically via a server side script that receives the data via a POST, and regurgitates it as JSON or in any other preferred format
Extra work, so not recommended
Having listed that, why not show the content in the form page itself? You can easily update the DOM using native JavaScript or jQuery.
|
How do I store data from form and display it on a new page using javascript?
|
I need to make a form with 2 input fields. When you press submit it should take you to a new page and display the input data.
This is my html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Film survey</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form id="form" action="./Success.html">
<h1>Movie survey</h1>
<p>Thank you for participating in the film festival!</p>
<p>Please fill out this short survey so we can record your feedback</p>
<div>
<label for="film">What film did you watch?</label>
</div>
<div>
<input type="text" id="film" name="film" required />
</div>
<div>
<label for="rating"
>How would you rate the film? (1 - very bad, 5 - very good)
</label>
</div>
<input type="text" id="rating" name="rating" required />
<div><button class="submit">Submit</button></div>
</form>
<script src="script.js"></script>
</body>
</html>
This is my js code
const formEl = document.querySelector("#form");
formEl.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(formEl);
fetch("https://reqres.in/api/form", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
film: formData.get("film"),
rating: formData.get("rating"),
}),
})
.then((response) => {
window.location.href = "./Success.html";
})
.catch((error) => {
console.error(error);
});
});
I have a second html page called Success.html which I want to display tha data given in the form. I need to make a mock API so I tried using reqres.
This is my Success.html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Success</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Thank you for your feedback!</h1>
<p>You watched: <span id="film"></span></p>
<p>You rated it: <span id="rating"></span></p>
<script>
const formData = JSON.parse(request.body);
const filmEl = document.querySelector("#film");
const ratingEl = document.querySelector("#rating");
filmEl.textContent = formData.film;
ratingEl.textContent = formData.rating;
</script>
</body>
</html>
I thought this would work but I get this error after pressing submit:
`` Success.html:16 Uncaught ReferenceError: request is not defined
at Success.html:16:35
|
[
"The line const formData = JSON.parse(request.body); in your success.html is trying to reference a variable named request, which isn't defined in the scope of the <script> tag that it's contained in - that's why you're getting the ReferenceError: request is not defined error.\nThis other Stackoverflow question seems similar to yours - I have linked you to an answer that I think would be helpful. In short, you could pull the values you care about out of your response, then pass them via query parameters to be displayed in your success.html.\nAlong those same lines, it might make sense for your mock API to respond with a 302 status code and location header including film and rating query parameters that points to your success page.\n",
"You can pass along data between web pages in several ways, using JSON data { foo: 'bar' } as an example:\n1. Use URL parameter:\n\nStringify and URL encode your JSON response (full or needed data only), and pass along via a URL parameter\nExample: 'data=' + encodeURIComponent(JSON.stringify(data)), resulting in data=%7B%20foo%3A%20'bar'%20%7D\nKeep in mind that there is a limit to URL length, varying from 2k to 64k depending on browser\n\n2. Use browser local storage:\n\nThe quota is browser specific, in range of 5-10MB, e.g. much larger than URL length\nTo set in the form page: localStorage.setItem('myFormData', JSON.stringify(data));\nTo read in success page: let data = JSON.parse(localStorage.getItem('myFormData'); (you likely want to add some error handling)\n\n3. Temporarily POST data\n\nYou post the JSON data back to the server to /success\nYour success page is delivered dynamically via a server side script that receives the data via a POST, and regurgitates it as JSON or in any other preferred format\nExtra work, so not recommended\n\nHaving listed that, why not show the content in the form page itself? You can easily update the DOM using native JavaScript or jQuery.\n"
] |
[
1,
1
] |
[] |
[] |
[
"html",
"javascript"
] |
stackoverflow_0074661120_html_javascript.txt
|
Q:
Unable to use keytool and OpenSSL for Facebook Android SDK installation
I'm trying to create a Facebook integrated Android app, but trying to use Facebook's Android SDK is tiring. Here's the tutorial I'm following.
I'm stuck on the step Using the Keytool. I've searched around a bit and apparently I have to install OpenSSL which I promptly did.
I found keytool under these directories on my Windows machine:
C:\Program Files\Java\jdk1.6.0_25
C:\Program Files\Java\jdk1.7.0
When I run
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 from the tutorial on openssl
I get the following error:
openssl:Error: 'keytool' is an invalid command.
A:
I followed Maulik J's post from the link provided by Venky here and tried this command in the command prompt and it worked:
C:\Program Files\Java\jdk1.7.0\bin>keytool -export -alias androiddebugkey -keystore "C:\Users\MyUser\.android\debug.keystore" | C:\Users\MyUser\Downloads\openssl-0.9.8k_X64\bin\openssl.exe sha1 -binary | C:\Users\MyUser\Downloads\openssl-0.9.8k_X64\bin\openssl.exe enc -a -e
A:
To be able to use keytool you need to have jdk installed and also openssl need to be on your pc you can download it here
https://code.google.com/archive/p/openssl-for-windows/downloads
So currently i have mine here, so i have to cd to the directory
C:\Program Files\Java\jdk-11.0.13\bin>
And once i am in this directory i need to
run the command
keytool -exportcert -alias <alias> -keystore "C:\Users\Codertjay\.android\debug.keystore" | "C:\Users\Codertjay\Downloads\Compressed\openssl-0.9.8e_X64\bin\openssl.exe" sha1 -binary | "C:\Users\Codertjay\Downloads\Compressed\openssl-0.9.8e_X64\bin\openssl.exe" base64
Notice that the path in here has my name on PC you need to update yours to the right path
|
Unable to use keytool and OpenSSL for Facebook Android SDK installation
|
I'm trying to create a Facebook integrated Android app, but trying to use Facebook's Android SDK is tiring. Here's the tutorial I'm following.
I'm stuck on the step Using the Keytool. I've searched around a bit and apparently I have to install OpenSSL which I promptly did.
I found keytool under these directories on my Windows machine:
C:\Program Files\Java\jdk1.6.0_25
C:\Program Files\Java\jdk1.7.0
When I run
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64 from the tutorial on openssl
I get the following error:
openssl:Error: 'keytool' is an invalid command.
|
[
"I followed Maulik J's post from the link provided by Venky here and tried this command in the command prompt and it worked:\nC:\\Program Files\\Java\\jdk1.7.0\\bin>keytool -export -alias androiddebugkey -keystore \"C:\\Users\\MyUser\\.android\\debug.keystore\" | C:\\Users\\MyUser\\Downloads\\openssl-0.9.8k_X64\\bin\\openssl.exe sha1 -binary | C:\\Users\\MyUser\\Downloads\\openssl-0.9.8k_X64\\bin\\openssl.exe enc -a -e\n\n",
"To be able to use keytool you need to have jdk installed and also openssl need to be on your pc you can download it here\nhttps://code.google.com/archive/p/openssl-for-windows/downloads\nSo currently i have mine here, so i have to cd to the directory\nC:\\Program Files\\Java\\jdk-11.0.13\\bin>\n\nAnd once i am in this directory i need to\nrun the command\nkeytool -exportcert -alias <alias> -keystore \"C:\\Users\\Codertjay\\.android\\debug.keystore\" | \"C:\\Users\\Codertjay\\Downloads\\Compressed\\openssl-0.9.8e_X64\\bin\\openssl.exe\" sha1 -binary | \"C:\\Users\\Codertjay\\Downloads\\Compressed\\openssl-0.9.8e_X64\\bin\\openssl.exe\" base64\n\nNotice that the path in here has my name on PC you need to update yours to the right path\n"
] |
[
8,
0
] |
[] |
[] |
[
"android",
"facebook",
"keytool"
] |
stackoverflow_0011131960_android_facebook_keytool.txt
|
Q:
Add many new default routes to Route::resource in laravel 8
I want to add some default routes for the whole model, since my models all use these methods, is there a way to do this?
Specifically the methods: trash(), restore(), forceDelete(), removeAll(), restoreAll(), forceDeleteAll();
`
<?php
namespace App\Http\Controllers\Article;
use App\Http\Controllers\Controller;
class ArticleController extends Controller
{
public function index(){}
public function create(){}
public function store(ArticleRequest $request){}
public function update(ArticleRequest $request, $id){}
public function destroy($id){}
public function trash(){}
public function restore($id){}
public function forceDelete($id)v
public function removeAll(Request $request){}
public function restoreAll(Request $request){}
public function forceDeleteAll(Request $request){}
}
`
Thanks!
A:
You can customise the stubs that are used when using artisan make commands by executing the artisan stub:publish command. Then customise the controller stub in stubs/controller.stub (or any other stub) to your needs.
More info here: https://laravel.com/docs/9.x/artisan#stub-customization
|
Add many new default routes to Route::resource in laravel 8
|
I want to add some default routes for the whole model, since my models all use these methods, is there a way to do this?
Specifically the methods: trash(), restore(), forceDelete(), removeAll(), restoreAll(), forceDeleteAll();
`
<?php
namespace App\Http\Controllers\Article;
use App\Http\Controllers\Controller;
class ArticleController extends Controller
{
public function index(){}
public function create(){}
public function store(ArticleRequest $request){}
public function update(ArticleRequest $request, $id){}
public function destroy($id){}
public function trash(){}
public function restore($id){}
public function forceDelete($id)v
public function removeAll(Request $request){}
public function restoreAll(Request $request){}
public function forceDeleteAll(Request $request){}
}
`
Thanks!
|
[
"You can customise the stubs that are used when using artisan make commands by executing the artisan stub:publish command. Then customise the controller stub in stubs/controller.stub (or any other stub) to your needs.\nMore info here: https://laravel.com/docs/9.x/artisan#stub-customization\n"
] |
[
0
] |
[] |
[] |
[
"laravel",
"laravel_8"
] |
stackoverflow_0074662012_laravel_laravel_8.txt
|
Q:
add column age from column birthdate in R
Name
Date
A
1990-10-7
B
1997-11-20
and i want to add column age the convert the date to the age
i try this
data$age <- age_calc(as.Date(data$dob, "%Y/%m/%d"), units = "years")
but i got this error
Error in if (any(enddate < dob)) { :
missing value where TRUE/FALSE needed
A:
The error is in the format you are giving to as.Date function
> df$age <- age_calc(as.Date(df$Date, "%Y-%m-%d"), units = "years")
> df
Name Date age
1 A 1990-10-7 32.15342
2 B 1997-11-20 25.03288
Note that your Date variable use - as separator instead of / so you have to use - inside as.Date
A:
I recommend installing and calling the lubridate package.
Then:
data$age <- trunc((data$Date %--% today()) / years(1))
|
add column age from column birthdate in R
|
Name
Date
A
1990-10-7
B
1997-11-20
and i want to add column age the convert the date to the age
i try this
data$age <- age_calc(as.Date(data$dob, "%Y/%m/%d"), units = "years")
but i got this error
Error in if (any(enddate < dob)) { :
missing value where TRUE/FALSE needed
|
[
"The error is in the format you are giving to as.Date function\n> df$age <- age_calc(as.Date(df$Date, \"%Y-%m-%d\"), units = \"years\")\n> df\n Name Date age\n1 A 1990-10-7 32.15342\n2 B 1997-11-20 25.03288\n\nNote that your Date variable use - as separator instead of / so you have to use - inside as.Date\n",
"I recommend installing and calling the lubridate package.\nThen:\ndata$age <- trunc((data$Date %--% today()) / years(1))\n"
] |
[
1,
0
] |
[
"It looks like the age_calc() function is expecting a dob (date of birth) and an enddate (end date) argument, but it's not receiving both. This is likely why you're seeing the error message about a missing value.\nTo fix this, you'll need to make sure that both the dob and enddate arguments are provided to the age_calc() function. For example, you could use the following code to calculate the age of each person in your data based on their date of birth and the current date:\ndata$age <- age_calc(as.Date(data$dob, \"%Y/%m/%d\"), \n as.Date(Sys.Date()), units = \"years\")\n\nAlternatively, you could provide a specific end date to the age_calc() function instead of using the current date. This would allow you to calculate the age of each person in your data based on a specific end date rather than the current date.\nI hope this helps!\n"
] |
[
-1
] |
[
"dataframe",
"multiple_columns",
"r"
] |
stackoverflow_0074662260_dataframe_multiple_columns_r.txt
|
Q:
How to move form to the middle of my webpage?
Image of my Form
I'd like to move this form to the middle of my web page. I have it center aligned currently, but it is at the top of my webpage. I want it smack dab in the middle. I've been trying to google around but this has been a surprisingly difficult answer to find.
html
<body>
<div class="form">
<form action="./script.js" method="post">
<ul>
<li>
<label for="date">Date:</label>
<input type="date" id="date" name="date" step="0.1" min="0"
placeholder="What's the date today?" size="50">
</li>
<li>
<label for="mileage">Mileage:</label>
<input type="number" id="mileage" name="mileage" step="0.1" min="0"
placeholder="How many miles today?" size="50">
</li>
<li>
<label for="note">Notes:</label>
<textarea id="note" name="user_message" placeholder="How did the run feel?"></textarea>
</li>
<li class="button">
<button type="submit">Submit</button>
</li>
</ul>
</form>
</div>
</body>
</html>
CSS
div.form {
display: block;
text-align: center;
}
form {
margin: 0 auto;
width: 600px;
padding: 1em;
border: 1px solid lightgrey;
border-radius: 1em;
display: inline-block;
margin-left: auto;
margin-right: auto;
text-align: left;
}
form li+li {
margin-top: 1em;
}
A:
This should work:
div.form {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
form {
margin: 0 auto;
width: 600px;
padding: 1em;
border: 1px solid lightgrey;
border-radius: 1em;
text-align: left;
}
form li+li {
margin-top: 1em;
}
<body>
<div class="form">
<form action="./script.js" method="post">
<ul>
<li>
<label for="date">Date:</label>
<input type="date" id="date" name="date" step="0.1" min="0"
placeholder="What's the date today?" size="50">
</li>
<li>
<label for="mileage">Mileage:</label>
<input type="number" id="mileage" name="mileage" step="0.1" min="0"
placeholder="How many miles today?" size="50">
</li>
<li>
<label for="note">Notes:</label>
<textarea id="note" name="user_message" placeholder="How did the run feel?"></textarea>
</li>
<li class="button">
<button type="submit">Submit</button>
</li>
</ul>
</form>
</div>
</body>
</html>
|
How to move form to the middle of my webpage?
|
Image of my Form
I'd like to move this form to the middle of my web page. I have it center aligned currently, but it is at the top of my webpage. I want it smack dab in the middle. I've been trying to google around but this has been a surprisingly difficult answer to find.
html
<body>
<div class="form">
<form action="./script.js" method="post">
<ul>
<li>
<label for="date">Date:</label>
<input type="date" id="date" name="date" step="0.1" min="0"
placeholder="What's the date today?" size="50">
</li>
<li>
<label for="mileage">Mileage:</label>
<input type="number" id="mileage" name="mileage" step="0.1" min="0"
placeholder="How many miles today?" size="50">
</li>
<li>
<label for="note">Notes:</label>
<textarea id="note" name="user_message" placeholder="How did the run feel?"></textarea>
</li>
<li class="button">
<button type="submit">Submit</button>
</li>
</ul>
</form>
</div>
</body>
</html>
CSS
div.form {
display: block;
text-align: center;
}
form {
margin: 0 auto;
width: 600px;
padding: 1em;
border: 1px solid lightgrey;
border-radius: 1em;
display: inline-block;
margin-left: auto;
margin-right: auto;
text-align: left;
}
form li+li {
margin-top: 1em;
}
|
[
"This should work:\n\n\ndiv.form {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}\n\nform {\n margin: 0 auto;\n width: 600px;\n padding: 1em;\n border: 1px solid lightgrey;\n border-radius: 1em;\n text-align: left;\n}\n\nform li+li {\n margin-top: 1em;\n}\n<body>\n <div class=\"form\">\n <form action=\"./script.js\" method=\"post\">\n <ul>\n <li>\n <label for=\"date\">Date:</label>\n <input type=\"date\" id=\"date\" name=\"date\" step=\"0.1\" min=\"0\" \n placeholder=\"What's the date today?\" size=\"50\">\n </li>\n <li>\n <label for=\"mileage\">Mileage:</label>\n <input type=\"number\" id=\"mileage\" name=\"mileage\" step=\"0.1\" min=\"0\" \n placeholder=\"How many miles today?\" size=\"50\">\n </li>\n <li>\n <label for=\"note\">Notes:</label>\n <textarea id=\"note\" name=\"user_message\" placeholder=\"How did the run feel?\"></textarea>\n </li>\n <li class=\"button\">\n <button type=\"submit\">Submit</button>\n </li>\n </ul>\n </form>\n </div>\n</body>\n</html>\n\n\n\n"
] |
[
1
] |
[
"Super easy, give your container all the view height and then super center it with grid.\nI forced your form to half of the view width just to show it was centered.\n\n\n.form-container {\n height: 100vh;\n display: grid;\n place-items: center;\n}\n\n/* this is just style */\nform {\n margin: 0 auto;\n width: 50vw;\n padding: 1em;\n border: 1px solid lightgrey;\n border-radius: 1em;\n display: inline-block;\n margin-left: auto;\n margin-right: auto;\n text-align: left;\n}\n\nform li+li {\n margin-top: 1em;\n}\n<div class=\"form form-container\">\n <form action=\"./script.js\" method=\"post\">\n <ul>\n <li>\n <label for=\"date\">Date:</label>\n <input type=\"date\" id=\"date\" name=\"date\" step=\"0.1\" min=\"0\" placeholder=\"What's the date today?\" size=\"50\">\n </li>\n <li>\n <label for=\"mileage\">Mileage:</label>\n <input type=\"number\" id=\"mileage\" name=\"mileage\" step=\"0.1\" min=\"0\" placeholder=\"How many miles today?\" size=\"50\">\n </li>\n <li>\n <label for=\"note\">Notes:</label>\n <textarea id=\"note\" name=\"user_message\" placeholder=\"How did the run feel?\"></textarea>\n </li>\n <li class=\"button\">\n <button type=\"submit\">Submit</button>\n </li>\n </ul>\n </form>\n</div>\n\n\n\n",
"\n\nform {\n margin: 0 auto;\n width: 600px;\n padding: 1em;\n border: 1px solid lightgrey;\n border-radius: 1em;\n \n text-align: left;\n}\n\nform li+li {\n margin-top: 1em;\n}\n\n.form{\ndisplay:flex;\nheight:calc(100vh - 2px);\njustify-content:center;\nalign-items:center;\nborder:solid 1px red;}\n\nbody,html,div{\nmargin:0;\npadding:0;}\n<body>\n <div class=\"form\">\n <form action=\"./script.js\" method=\"post\">\n <ul>\n <li>\n <label for=\"date\">Date:</label>\n <input type=\"date\" id=\"date\" name=\"date\" step=\"0.1\" min=\"0\" \n placeholder=\"What's the date today?\" size=\"50\">\n </li>\n <li>\n <label for=\"mileage\">Mileage:</label>\n <input type=\"number\" id=\"mileage\" name=\"mileage\" step=\"0.1\" min=\"0\" \n placeholder=\"How many miles today?\" size=\"50\">\n </li>\n <li>\n <label for=\"note\">Notes:</label>\n <textarea id=\"note\" name=\"user_message\" placeholder=\"How did the run feel?\"></textarea>\n </li>\n <li class=\"button\">\n <button type=\"submit\">Submit</button>\n </li>\n </ul>\n </form>\n </div>\n</body>\n\n\n\n"
] |
[
-1,
-1
] |
[
"css",
"html"
] |
stackoverflow_0074662275_css_html.txt
|
Q:
Phyton: Hvplot negative values coloring
I try to do interactive bar chart with hvplot, but I have negatives values there and would like to color them other color.
enter image description here
I tried using cmap, but it colors positives values negatively too.
enter image description here
I would be happy for any tip or help!
Thank you in advantage.
A:
You can use a compositional HoloView plot for this.
plot1 = df[df['Results']>0].hvplot.bar(y='Results')
plot2 = df[df['Results']<0].hvplot.bar(y='Results')
plot1*plot2
Note: sorry I can't post images directly yet as this is my first entry on stackoverflow, but this link will show you the plot result https://i.stack.imgur.com/bnoFg.png
Here the full code below, you can adapt it to your dataframe :
# create a dataframe with column 'Name' as index
dict = {'Name':["Rick", "Sam", "Kelly", "Al"],
'Results':[-90, +40, +80, -28]}
df = pd.DataFrame(dict)
df.index=df['Name']
# create 2 hvplots: 1 for positive results, and 1 for negative results
plot1 = df[df['Results']>0].hvplot.bar(y='Results')
plot2 = df[df['Results']<0].hvplot.bar(y='Results')
# layout plot1 and plot2 content on the same frame using a compositional plot
plot1*plot2
|
Phyton: Hvplot negative values coloring
|
I try to do interactive bar chart with hvplot, but I have negatives values there and would like to color them other color.
enter image description here
I tried using cmap, but it colors positives values negatively too.
enter image description here
I would be happy for any tip or help!
Thank you in advantage.
|
[
"You can use a compositional HoloView plot for this.\nplot1 = df[df['Results']>0].hvplot.bar(y='Results')\nplot2 = df[df['Results']<0].hvplot.bar(y='Results')\n\nplot1*plot2\n\nNote: sorry I can't post images directly yet as this is my first entry on stackoverflow, but this link will show you the plot result https://i.stack.imgur.com/bnoFg.png\nHere the full code below, you can adapt it to your dataframe :\n# create a dataframe with column 'Name' as index\ndict = {'Name':[\"Rick\", \"Sam\", \"Kelly\", \"Al\"],\n 'Results':[-90, +40, +80, -28]}\n\ndf = pd.DataFrame(dict)\ndf.index=df['Name']\n\n# create 2 hvplots: 1 for positive results, and 1 for negative results \nplot1 = df[df['Results']>0].hvplot.bar(y='Results')\nplot2 = df[df['Results']<0].hvplot.bar(y='Results')\n\n# layout plot1 and plot2 content on the same frame using a compositional plot \nplot1*plot2\n\n\n"
] |
[
0
] |
[] |
[] |
[
"conditional_formatting",
"graph_coloring",
"hvplot"
] |
stackoverflow_0074321428_conditional_formatting_graph_coloring_hvplot.txt
|
Q:
Material UI with React: How to style with rounded corners
I've always been a fan of Google's search bar, with nice rounded corners and ample padding around the text.
I'm trying to replicate this style using Material UI's <Autocomplete/> component, but I can't seem to do it. I'm using Next.js. What I have so far is:
import React, { useState, useEffect } from 'react';
import TextField from '@mui/material/TextField';
import Stack from '@mui/material/Stack';
import Autocomplete from '@mui/material/Autocomplete';
import { borderRadius, Box } from '@mui/system';
import SearchIcon from '@material-ui/icons/Search';
const LiveSearch = (props) => {
const [jsonResults, setJsonResults] = useState([]);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/users`)
.then(res => res.json())
.then(json => setJsonResults(json));
}, []);
return (
<Stack sx={{ width: 400, margin: "auto"}}>
<Autocomplete
id="Hello"
getOptionLabel={(jsonResults) => jsonResults.name}
options={jsonResults}
noOptionsText="No results"
isOptionEqualToValue={(option, value) => {
option.name === value.name
}}
renderOption={(props, jsonResults) => (
<Box component="li" {...props} key={jsonResults.id}>
{jsonResults.name} - Ahhh
</Box>
)}
renderInput={(params) => <TextField {...params} label="Search users..." />}
/>
</Stack>
)
}
export default LiveSearch;
The above code should run as-is – there's an axios call in there to populate the autocomplete results too.
I've tried various way to get the <SearchIcon /> icon prefix inside the input with no success, but really I'd just be happy if I could figure out how to pad it. You can see in the google screenshot how the autocomplete lines up really well with the box, but in my version, the border-radius just rounds the element, and so it no longer lines up with the dropdown.
I'm new to Material UI, so I'm still not quite sure how to do these styles, but I think the issue is that the border is being drawn by some internal element, and although I can set the borderRadius on the component itself global CSS:
.MuiOutlinedInput-root {
border-radius: 30px;
}
I can't seem to set the padding or borders anywhere. I've also tried setting style with sx but it does nothing.
A:
You have to look at the autocomplete css classes and override them in your component or use them in your theme, if you use one.
<Autocomplete
componentsProps={{
paper: {
sx: {
width: 350,
margin: "auto"
}
}
}}
id="Hello"
notched
getOptionLabel={(jsonResults) => jsonResults.name}
options={jsonResults}
noOptionsText="No results"
isOptionEqualToValue={(option, value) => {
option.name === value.name;
}}
renderOption={(props, jsonResults) => (
<Box component="li" {...props} key={jsonResults.id}>
{jsonResults.name} - Ahhh
</Box>
)}
renderInput={(params) => (
<TextField
{...params}
label="Search users..."
sx={{
"& .MuiOutlinedInput-root": {
borderRadius: "50px",
legend: {
marginLeft: "30px"
}
},
"& .MuiAutocomplete-inputRoot": {
paddingLeft: "20px !important",
borderRadius: "50px"
},
"& .MuiInputLabel-outlined": {
paddingLeft: "20px"
},
"& .MuiInputLabel-shrink": {
marginLeft: "20px",
paddingLeft: "10px",
paddingRight: 0,
background: "white"
}
}}
/>
)}
/>
Sandbox: https://codesandbox.io/s/infallible-field-qsstrs?file=/src/Search.js
A:
I'm trying to figure out how to line up the edges (figured it out, see update), but this is how I was able to insert the Search icon, via renderInput and I got rid of the expand and collapse arrows at the end of the bar by setting freeSolo={true} (but this allows user input to not be bound to provided options).
import { Search } from '@mui/icons-material';
import { Autocomplete, AutocompleteRenderInputParams, InputAdornment } from '@mui/material';
...
<Autocomplete
freeSolo={true}
renderInput={(renderInputParams: AutocompleteRenderInputParams) => (
<div ref={renderInputParams.InputProps.ref}
style={{
alignItems: 'center',
width: '100%',
display: 'flex',
flexDirection: 'row'
}}>
<TextField style={{ flex: 1 }} InputProps={{
...renderInputParams.InputProps, startAdornment: (<InputAdornment position='start'> <Search /> </InputAdornment>),
}}
placeholder='Search'
inputProps={{
...renderInputParams.inputProps
}}
InputLabelProps={{ style: { display: 'none' } }}
/>
</div >
)}
...
/>
Ignore the colors and other styling, but this is what it looks like:
Update
I was able to line up the edges by controlling the border-radius via css and setting the bottom left and right to 0 and top ones to 20px.
Here's a demo:
Here are the changes I had to make in css. I also left the bottom border so there is a division between the search and the results, but you can style if however you like. (Also I'm using scss so I declared colors as variables at the top).
div.MuiAutocomplete-root div.MuiOutlinedInput-root { /* Search bar when not in focus */
border-radius: 40px;
background-color: $dark-color;
}
div.MuiAutocomplete-root div.MuiOutlinedInput-root.Mui-focused { /* Search bar when focused */
border-radius: 20px 20px 0px 0px !important;
}
div.MuiAutocomplete-root div.Mui-focused fieldset { /* fieldset element is what controls the border color. Leaving only the bottom border when dropdown is visible */
border-width: 1px !important;
border-color: transparent transparent $light-gray-color transparent !important;
}
.MuiAutocomplete-listbox { /* To control the background color of the listbox, which is the dropdown */
background-color: $dark-color;
}
div.MuiAutocomplete-popper div { /* To get rid of the rounding applied by Mui-paper on the dropdown */
border-top-right-radius: 0px;
border-top-left-radius: 0px;
}
|
Material UI with React: How to style with rounded corners
|
I've always been a fan of Google's search bar, with nice rounded corners and ample padding around the text.
I'm trying to replicate this style using Material UI's <Autocomplete/> component, but I can't seem to do it. I'm using Next.js. What I have so far is:
import React, { useState, useEffect } from 'react';
import TextField from '@mui/material/TextField';
import Stack from '@mui/material/Stack';
import Autocomplete from '@mui/material/Autocomplete';
import { borderRadius, Box } from '@mui/system';
import SearchIcon from '@material-ui/icons/Search';
const LiveSearch = (props) => {
const [jsonResults, setJsonResults] = useState([]);
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/users`)
.then(res => res.json())
.then(json => setJsonResults(json));
}, []);
return (
<Stack sx={{ width: 400, margin: "auto"}}>
<Autocomplete
id="Hello"
getOptionLabel={(jsonResults) => jsonResults.name}
options={jsonResults}
noOptionsText="No results"
isOptionEqualToValue={(option, value) => {
option.name === value.name
}}
renderOption={(props, jsonResults) => (
<Box component="li" {...props} key={jsonResults.id}>
{jsonResults.name} - Ahhh
</Box>
)}
renderInput={(params) => <TextField {...params} label="Search users..." />}
/>
</Stack>
)
}
export default LiveSearch;
The above code should run as-is – there's an axios call in there to populate the autocomplete results too.
I've tried various way to get the <SearchIcon /> icon prefix inside the input with no success, but really I'd just be happy if I could figure out how to pad it. You can see in the google screenshot how the autocomplete lines up really well with the box, but in my version, the border-radius just rounds the element, and so it no longer lines up with the dropdown.
I'm new to Material UI, so I'm still not quite sure how to do these styles, but I think the issue is that the border is being drawn by some internal element, and although I can set the borderRadius on the component itself global CSS:
.MuiOutlinedInput-root {
border-radius: 30px;
}
I can't seem to set the padding or borders anywhere. I've also tried setting style with sx but it does nothing.
|
[
"You have to look at the autocomplete css classes and override them in your component or use them in your theme, if you use one.\n<Autocomplete\n componentsProps={{\n paper: {\n sx: {\n width: 350,\n margin: \"auto\"\n }\n }\n }}\n id=\"Hello\"\n notched\n getOptionLabel={(jsonResults) => jsonResults.name}\n options={jsonResults}\n noOptionsText=\"No results\"\n isOptionEqualToValue={(option, value) => {\n option.name === value.name;\n }}\n renderOption={(props, jsonResults) => (\n <Box component=\"li\" {...props} key={jsonResults.id}>\n {jsonResults.name} - Ahhh\n </Box>\n )}\n renderInput={(params) => (\n <TextField\n {...params}\n label=\"Search users...\"\n sx={{\n \"& .MuiOutlinedInput-root\": {\n borderRadius: \"50px\",\n\n legend: {\n marginLeft: \"30px\"\n }\n },\n \"& .MuiAutocomplete-inputRoot\": {\n paddingLeft: \"20px !important\",\n borderRadius: \"50px\"\n },\n \"& .MuiInputLabel-outlined\": {\n paddingLeft: \"20px\"\n },\n \"& .MuiInputLabel-shrink\": {\n marginLeft: \"20px\",\n paddingLeft: \"10px\",\n paddingRight: 0,\n background: \"white\"\n }\n }}\n />\n )}\n />\n\nSandbox: https://codesandbox.io/s/infallible-field-qsstrs?file=/src/Search.js\n",
"I'm trying to figure out how to line up the edges (figured it out, see update), but this is how I was able to insert the Search icon, via renderInput and I got rid of the expand and collapse arrows at the end of the bar by setting freeSolo={true} (but this allows user input to not be bound to provided options).\nimport { Search } from '@mui/icons-material';\nimport { Autocomplete, AutocompleteRenderInputParams, InputAdornment } from '@mui/material';\n\n...\n<Autocomplete\n freeSolo={true}\n renderInput={(renderInputParams: AutocompleteRenderInputParams) => (\n <div ref={renderInputParams.InputProps.ref}\n style={{\n alignItems: 'center',\n width: '100%',\n display: 'flex',\n flexDirection: 'row'\n }}>\n <TextField style={{ flex: 1 }} InputProps={{\n ...renderInputParams.InputProps, startAdornment: (<InputAdornment position='start'> <Search /> </InputAdornment>),\n }}\n placeholder='Search'\n inputProps={{\n ...renderInputParams.inputProps\n }}\n InputLabelProps={{ style: { display: 'none' } }}\n />\n </div >\n )}\n ...\n/>\n\nIgnore the colors and other styling, but this is what it looks like:\n\nUpdate\nI was able to line up the edges by controlling the border-radius via css and setting the bottom left and right to 0 and top ones to 20px.\nHere's a demo:\n\nHere are the changes I had to make in css. I also left the bottom border so there is a division between the search and the results, but you can style if however you like. (Also I'm using scss so I declared colors as variables at the top).\ndiv.MuiAutocomplete-root div.MuiOutlinedInput-root { /* Search bar when not in focus */\n border-radius: 40px;\n background-color: $dark-color;\n}\n\ndiv.MuiAutocomplete-root div.MuiOutlinedInput-root.Mui-focused { /* Search bar when focused */\n border-radius: 20px 20px 0px 0px !important;\n}\n\ndiv.MuiAutocomplete-root div.Mui-focused fieldset { /* fieldset element is what controls the border color. Leaving only the bottom border when dropdown is visible */\n border-width: 1px !important;\n border-color: transparent transparent $light-gray-color transparent !important;\n}\n\n.MuiAutocomplete-listbox { /* To control the background color of the listbox, which is the dropdown */\n background-color: $dark-color;\n}\n\ndiv.MuiAutocomplete-popper div { /* To get rid of the rounding applied by Mui-paper on the dropdown */\n border-top-right-radius: 0px;\n border-top-left-radius: 0px;\n}\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"css",
"javascript",
"material_ui",
"next.js",
"reactjs"
] |
stackoverflow_0073092296_css_javascript_material_ui_next.js_reactjs.txt
|
Q:
How to Check if discord is running?
I'm trying to add discord rich presence in my game(made using Unity 2022.1, on Windows 10), but as many may know, trying to use rich presence when discord isn't open crashes the game/editor and opens discord.
My work around this has been using System.Diagnostics.Process.GetProcesses() to check if discord is open and running(by checking each returned value and seeing if they're equal to "System.Diagnostics.Process (Discord)")
The issue is, when within the editor(On windows) it works fine, but outside of the editor, still on Windows, it doesn't seem to, and I don't know why.(I've tested without that check, and discord's rich presence doesn't seem to be the cause of the issue)
How do I fix this? Is there an alternative way to check if discord is running?
A:
I think it solves this problem. You should check the discord list process.
if (Process.GetProcessesByName("Discord").Length > 0)
{
Debug.Log("Discord is Running..");
}
else
{
Debug.Log("Discord doesn't Running...");
}
A:
It may be a little late, but still...
Discord Game SDK requires the client to be running when using the standard flags in the class constructor. To remove this dependency, you can use Discord.CreateFlags.NoRequireDiscord instead of Discord.CreateFlags.Default
Don't forget to check for NullRef because if the client is not running and you try to call the constructor, you won't get anything.
There is another answer to finding the Discord process... In conjunction with my answer, you can simply not enable Discord Rich Presence if the client is not running, as there is a pitfall: I get an exception somewhere on the ctor statement inside the library (this is a CIL language statement).
So it's better to immediately check for a running client in the operating system processes and if it's not there, just don't initialize the library.
For more information, you can take a closer look here:
https://discord.com/developers/docs/game-sdk/discord#discord
|
How to Check if discord is running?
|
I'm trying to add discord rich presence in my game(made using Unity 2022.1, on Windows 10), but as many may know, trying to use rich presence when discord isn't open crashes the game/editor and opens discord.
My work around this has been using System.Diagnostics.Process.GetProcesses() to check if discord is open and running(by checking each returned value and seeing if they're equal to "System.Diagnostics.Process (Discord)")
The issue is, when within the editor(On windows) it works fine, but outside of the editor, still on Windows, it doesn't seem to, and I don't know why.(I've tested without that check, and discord's rich presence doesn't seem to be the cause of the issue)
How do I fix this? Is there an alternative way to check if discord is running?
|
[
"I think it solves this problem. You should check the discord list process.\nif (Process.GetProcessesByName(\"Discord\").Length > 0)\n{\n Debug.Log(\"Discord is Running..\");\n}\nelse\n{\n Debug.Log(\"Discord doesn't Running...\");\n}\n\n",
"It may be a little late, but still...\nDiscord Game SDK requires the client to be running when using the standard flags in the class constructor. To remove this dependency, you can use Discord.CreateFlags.NoRequireDiscord instead of Discord.CreateFlags.Default\nDon't forget to check for NullRef because if the client is not running and you try to call the constructor, you won't get anything.\nThere is another answer to finding the Discord process... In conjunction with my answer, you can simply not enable Discord Rich Presence if the client is not running, as there is a pitfall: I get an exception somewhere on the ctor statement inside the library (this is a CIL language statement).\nSo it's better to immediately check for a running client in the operating system processes and if it's not there, just don't initialize the library.\nFor more information, you can take a closer look here:\nhttps://discord.com/developers/docs/game-sdk/discord#discord\n"
] |
[
1,
0
] |
[] |
[] |
[
"c#",
"unity3d"
] |
stackoverflow_0072638918_c#_unity3d.txt
|
Q:
i don´t know how acces to the pet object (EXCERCISE WITH OBJECTS IN JS)
im doing a project-excercise of debugging using objects, im already done all the other´s excercises but im very stuck in this, i dont know how to solve.
/*
Fix the `feedPet` function. `feedPet` should take in a pet name and return a
function that, when invoked with a food, will return the pet's name and a list
of foods that you have fed that pet.
*/
function feedPet(name) {
const foods = [];
return (food) => {
return "Fed " + name + " " + foods.push(food) + ".";
}
}
const feedHydra = feedPet('Hydra');
console.log(feedHydra('bones')); // Fed Hyrda bones.
console.log(feedHydra('Hercules')); // Fed Hyrda bones, Hercules.
const feedHippogriff = feedPet('Hippogriff');
console.log(feedHippogriff('worms')); // Fed Hyrda worms.
console.log(feedHippogriff('crickets')); // Fed Hyrda worms, crickets.
console.log(feedHippogriff('chicken')); // Fed Hyrda worms, crickets, chicken.
A:
push returns a new length of the array, but you want to have the items
function feedPet(name) {
const foods = [];
return (food) => {
foods.push(food)
return "Fed " + name + " " + foods + ".";
}
}
function feedPet(name) {
const foods = [];
return (food) => {
foods.push(food)
return "Fed " + name + " " + foods.join(', ') + ".";
}
}
const feedHydra = feedPet('Hydra');
console.log(feedHydra('bones')); // Fed Hyrda bones.
console.log(feedHydra('Hercules')); // Fed Hyrda bones, Hercules.
const feedHippogriff = feedPet('Hippogriff');
console.log(feedHippogriff('worms')); // Fed Hyrda worms.
console.log(feedHippogriff('crickets')); // Fed Hyrda worms, crickets.
console.log(feedHippogriff('chicken')); // Fed Hyrda worms, crickets, chicken.
A:
foods.push(food) returns the array length, which is the reason for the numbers.
Fixed your code to print the array correctly:
/*
Fix the `feedPet` function. `feedPet` should take in a pet name and return a
function that, when invoked with a food, will return the pet's name and a list
of foods that you have fed that pet.
*/
function feedPet(name) {
const foods = [];
return (food) => {
foods.push(food);
// Equivalent to foods.join(", ");
/*
var ret = "";
for(var i = 0; i < foods.length; ++i)
{
ret += foods[i];
if(i < foods.length - 1)
{
ret += ", ";
}
}
*/
return "Fed " + name + " " + foods.join(", ") + ".";
}
}
const feedHydra = feedPet('Hydra');
console.log(feedHydra('bones')); // Fed Hyrda bones.
console.log(feedHydra('Hercules')); // Fed Hyrda bones, Hercules.
const feedHippogriff = feedPet('Hippogriff');
console.log(feedHippogriff('worms')); // Fed Hyrda worms.
console.log(feedHippogriff('crickets')); // Fed Hyrda worms, crickets.
console.log(feedHippogriff('chicken')); // Fed Hyrda worms, crickets, chicken.
|
i don´t know how acces to the pet object (EXCERCISE WITH OBJECTS IN JS)
|
im doing a project-excercise of debugging using objects, im already done all the other´s excercises but im very stuck in this, i dont know how to solve.
/*
Fix the `feedPet` function. `feedPet` should take in a pet name and return a
function that, when invoked with a food, will return the pet's name and a list
of foods that you have fed that pet.
*/
function feedPet(name) {
const foods = [];
return (food) => {
return "Fed " + name + " " + foods.push(food) + ".";
}
}
const feedHydra = feedPet('Hydra');
console.log(feedHydra('bones')); // Fed Hyrda bones.
console.log(feedHydra('Hercules')); // Fed Hyrda bones, Hercules.
const feedHippogriff = feedPet('Hippogriff');
console.log(feedHippogriff('worms')); // Fed Hyrda worms.
console.log(feedHippogriff('crickets')); // Fed Hyrda worms, crickets.
console.log(feedHippogriff('chicken')); // Fed Hyrda worms, crickets, chicken.
|
[
"push returns a new length of the array, but you want to have the items\nfunction feedPet(name) {\n const foods = [];\n return (food) => {\n foods.push(food)\n return \"Fed \" + name + \" \" + foods + \".\";\n }\n}\n\n\n\nfunction feedPet(name) {\n const foods = [];\n return (food) => {\n foods.push(food)\n return \"Fed \" + name + \" \" + foods.join(', ') + \".\";\n }\n}\n\nconst feedHydra = feedPet('Hydra');\n\nconsole.log(feedHydra('bones')); // Fed Hyrda bones.\nconsole.log(feedHydra('Hercules')); // Fed Hyrda bones, Hercules.\n\nconst feedHippogriff = feedPet('Hippogriff');\n\nconsole.log(feedHippogriff('worms')); // Fed Hyrda worms.\nconsole.log(feedHippogriff('crickets')); // Fed Hyrda worms, crickets.\nconsole.log(feedHippogriff('chicken')); // Fed Hyrda worms, crickets, chicken.\n\n\n\n",
"foods.push(food) returns the array length, which is the reason for the numbers.\nFixed your code to print the array correctly:\n\n\n /*\n\nFix the `feedPet` function. `feedPet` should take in a pet name and return a\nfunction that, when invoked with a food, will return the pet's name and a list\nof foods that you have fed that pet.\n\n*/\n\nfunction feedPet(name) {\n const foods = [];\n return (food) => {\n foods.push(food);\n \n // Equivalent to foods.join(\", \");\n /*\n var ret = \"\";\n for(var i = 0; i < foods.length; ++i)\n {\n ret += foods[i];\n if(i < foods.length - 1)\n {\n ret += \", \";\n }\n }\n */\n\n return \"Fed \" + name + \" \" + foods.join(\", \") + \".\";\n }\n}\n\nconst feedHydra = feedPet('Hydra');\n\nconsole.log(feedHydra('bones')); // Fed Hyrda bones.\nconsole.log(feedHydra('Hercules')); // Fed Hyrda bones, Hercules.\n\nconst feedHippogriff = feedPet('Hippogriff');\n\nconsole.log(feedHippogriff('worms')); // Fed Hyrda worms.\nconsole.log(feedHippogriff('crickets')); // Fed Hyrda worms, crickets.\nconsole.log(feedHippogriff('chicken')); // Fed Hyrda worms, crickets, chicken.\n\n\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"arrays",
"javascript",
"object",
"pojo"
] |
stackoverflow_0074662295_arrays_javascript_object_pojo.txt
|
Q:
Can I extend default javascript function prototype to let some code been executed on every function call?
Lets say there are functions
function a(someparams){
console.log('a called')
}
function b(){
console.log('b called')
}
...
const c (someParam) => { console.log('c called')}
I want to extend default function prototype something like
Function.prototype.onCall = (args) => {console.log('Proxy fn called!',args)}
in a very begining of a page code, so every existing and new functions, upon call, will log 'Proxy fn called!'.
There are solutions to map window.functions - but they only work for existing functions, and I want to extend prototype to let it execute my piece of code.
The goal is to automatically check if args are valid. No I don't want typescript or flow, thanks for suggestion.
Is this possible? where to look at?
I found
(function() {
var call = Function.prototype.call;
Function.prototype.call = function() {
console.log(this, arguments); // Here you can do whatever actions you want
return call.apply(this, arguments);
};
}());
to be the closest to what I want so far, but these aren't called when calling a function normally, e.g. someFunction();, without explicit .call or .apply.
I have found maybe decorators is a way to go? the official doc said they are still not a standard https://github.com/tc39/proposal-decorators but there is a babel plugin https://babeljs.io/docs/en/babel-plugin-proposal-decorators is it possible that it would do the job or am I looking into wrong direction?
A:
Proposal
What the OP is looking for is best described with method modification. There are specialized modifiers like around, before, after, afterThrowing and afterFinally.
In case of a search for modifier implementations one should be aware that such a modifier has to support a thisArg parameter in order to create a modified function which operates upon the correct this context (hence a method).
Answer
There is no single point where one could implement the interception of any function's invocation, be it existing functions or the ones yet to come (e.g. functions/methods generated while an application is running).
Regardless of the possible approaches like a Proxy's apply or construct method's or decorators (as proposed by another answer) or the just mentioned method modifiers (which are specialized abstractions for otherwise more complex manual wrapping tasks), one always has to know and explicitly refer to the to be proxyfied / decorated / modified functions and methods.
Example code which implements and uses Function.prototype.around ...
// 1st example ... wrapping **around** a simple function
function consumeAnyParameter(...params) {
console.log('inside `consumeAnyParameter` ... params ...', params);
}
function interceptor(originalFunction, interceptorReference, ...params) {
// intercept.
console.log('inside `interceptor` ... ', {
params,
originalFunction,
interceptorReference,
});
// proceed.
originalFunction(...params);
}
// reassignment of ... a modified version of itself.
consumeAnyParameter = consumeAnyParameter.around(interceptor);
// invoke modified version.
consumeAnyParameter('foo', 'bar', 'baz');
// 2nd example ... wrapping **around** a type's method.
const type = {
foo: 'foo',
bar: 'bar',
whoAmI: function () {
console.log('Who am I? I\'m `this` ...', this);
}
}
type.whoAmI();
type.whoAmI = type
.whoAmI
.around(function (proceed, interceptor, ...params) {
console.log('interceptor\'s `this` context ...', this);
console.log('interceptor\'s `params` ...', params);
// proceed.apply(this, params);
proceed.call(this);
}, type); // for method modification do pass the context/target.
type.whoAmI();
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
// poor man's module.
(function (Function) {
// module scope.
function getSanitizedTarget(value) {
return value ?? null;
}
function isFunction(value) {
return (
'function' === typeof value &&
'function' === typeof value.call &&
'function' === typeof value.apply
);
}
// modifier implementation.
function around/*Modifier*/(handler, target) {
target = getSanitizedTarget(target);
const proceed = this;
return (
isFunction(handler) &&
isFunction(proceed) &&
function aroundType(...argumentArray) {
// the target/context of the initial modifier/modification time
// still can be overruled by a handler's apply/call time context.
const context = getSanitizedTarget(this) ?? target;
return handler.call(
context,
proceed,
handler,
argumentArray,
);
}
) || proceed;
}
// modifier assignment.
Object.defineProperty(Function.prototype, 'around', {
configurable: true,
writable: true,
value: around/*Modifier*/,
});
}(Function));
</script>
A:
Yes, you can use decorators to achieve this. Decorators are a feature in JavaScript that allows you to modify a class or method by attaching additional functionality to it. In your case, you can use a decorator to log a message every time a function is called.
Here's an example of how you could implement a decorator to log a message whenever a function is called:
function onCall(target, name, descriptor) {
const original = descriptor.value;
if (typeof original === 'function') {
descriptor.value = function(...args) {
console.log('Proxy fn called!');
return original.apply(this, args);
};
}
return descriptor;
}
class MyClass {
@onCall
myMethod(a, b) {
// do something
}
}
const instance = new MyClass();
instance.myMethod(1, 2); // logs 'Proxy fn called!'
In this example, the onCall decorator is applied to the myMethod method of the MyClass class. Whenever myMethod is called, the onCall decorator will log a message before calling the original method.
To use decorators in your project, you will need to use a transpiler like Babel to transform your code into a form that is supported by most browsers. The Babel plugin that you mentioned, babel-plugin-proposal-decorators, can be used to enable decorators in your code.
|
Can I extend default javascript function prototype to let some code been executed on every function call?
|
Lets say there are functions
function a(someparams){
console.log('a called')
}
function b(){
console.log('b called')
}
...
const c (someParam) => { console.log('c called')}
I want to extend default function prototype something like
Function.prototype.onCall = (args) => {console.log('Proxy fn called!',args)}
in a very begining of a page code, so every existing and new functions, upon call, will log 'Proxy fn called!'.
There are solutions to map window.functions - but they only work for existing functions, and I want to extend prototype to let it execute my piece of code.
The goal is to automatically check if args are valid. No I don't want typescript or flow, thanks for suggestion.
Is this possible? where to look at?
I found
(function() {
var call = Function.prototype.call;
Function.prototype.call = function() {
console.log(this, arguments); // Here you can do whatever actions you want
return call.apply(this, arguments);
};
}());
to be the closest to what I want so far, but these aren't called when calling a function normally, e.g. someFunction();, without explicit .call or .apply.
I have found maybe decorators is a way to go? the official doc said they are still not a standard https://github.com/tc39/proposal-decorators but there is a babel plugin https://babeljs.io/docs/en/babel-plugin-proposal-decorators is it possible that it would do the job or am I looking into wrong direction?
|
[
"Proposal\nWhat the OP is looking for is best described with method modification. There are specialized modifiers like around, before, after, afterThrowing and afterFinally.\nIn case of a search for modifier implementations one should be aware that such a modifier has to support a thisArg parameter in order to create a modified function which operates upon the correct this context (hence a method).\nAnswer\nThere is no single point where one could implement the interception of any function's invocation, be it existing functions or the ones yet to come (e.g. functions/methods generated while an application is running).\nRegardless of the possible approaches like a Proxy's apply or construct method's or decorators (as proposed by another answer) or the just mentioned method modifiers (which are specialized abstractions for otherwise more complex manual wrapping tasks), one always has to know and explicitly refer to the to be proxyfied / decorated / modified functions and methods.\nExample code which implements and uses Function.prototype.around ...\n\n\n// 1st example ... wrapping **around** a simple function\n\nfunction consumeAnyParameter(...params) {\n console.log('inside `consumeAnyParameter` ... params ...', params);\n}\nfunction interceptor(originalFunction, interceptorReference, ...params) {\n // intercept.\n console.log('inside `interceptor` ... ', {\n params,\n originalFunction,\n interceptorReference,\n });\n // proceed.\n originalFunction(...params);\n}\n\n// reassignment of ... a modified version of itself.\nconsumeAnyParameter = consumeAnyParameter.around(interceptor);\n\n// invoke modified version.\nconsumeAnyParameter('foo', 'bar', 'baz');\n\n\n// 2nd example ... wrapping **around** a type's method.\n\nconst type = {\n foo: 'foo',\n bar: 'bar',\n whoAmI: function () {\n console.log('Who am I? I\\'m `this` ...', this);\n }\n}\ntype.whoAmI();\n\ntype.whoAmI = type\n .whoAmI\n .around(function (proceed, interceptor, ...params) {\n\n console.log('interceptor\\'s `this` context ...', this);\n console.log('interceptor\\'s `params` ...', params);\n\n // proceed.apply(this, params);\n proceed.call(this);\n\n }, type); // for method modification do pass the context/target. \n\ntype.whoAmI();\n.as-console-wrapper { min-height: 100%!important; top: 0; }\n<script>\n// poor man's module.\n(function (Function) {\n\n // module scope.\n\n function getSanitizedTarget(value) {\n return value ?? null;\n }\n function isFunction(value) {\n return (\n 'function' === typeof value &&\n 'function' === typeof value.call &&\n 'function' === typeof value.apply\n );\n }\n\n // modifier implementation.\n\n function around/*Modifier*/(handler, target) {\n target = getSanitizedTarget(target);\n\n const proceed = this;\n\n return (\n isFunction(handler) &&\n isFunction(proceed) &&\n\n function aroundType(...argumentArray) {\n // the target/context of the initial modifier/modification time\n // still can be overruled by a handler's apply/call time context.\n const context = getSanitizedTarget(this) ?? target;\n\n return handler.call(\n context,\n proceed,\n handler,\n argumentArray,\n );\n }\n ) || proceed;\n }\n\n // modifier assignment.\n\n Object.defineProperty(Function.prototype, 'around', {\n configurable: true,\n writable: true,\n value: around/*Modifier*/,\n });\n\n}(Function));\n</script>\n\n\n\n",
"Yes, you can use decorators to achieve this. Decorators are a feature in JavaScript that allows you to modify a class or method by attaching additional functionality to it. In your case, you can use a decorator to log a message every time a function is called.\nHere's an example of how you could implement a decorator to log a message whenever a function is called:\nfunction onCall(target, name, descriptor) {\n const original = descriptor.value;\n\n if (typeof original === 'function') {\n descriptor.value = function(...args) {\n console.log('Proxy fn called!');\n return original.apply(this, args);\n };\n }\n\n return descriptor;\n}\n\nclass MyClass {\n @onCall\n myMethod(a, b) {\n // do something\n }\n}\n\nconst instance = new MyClass();\ninstance.myMethod(1, 2); // logs 'Proxy fn called!'\n\nIn this example, the onCall decorator is applied to the myMethod method of the MyClass class. Whenever myMethod is called, the onCall decorator will log a message before calling the original method.\nTo use decorators in your project, you will need to use a transpiler like Babel to transform your code into a form that is supported by most browsers. The Babel plugin that you mentioned, babel-plugin-proposal-decorators, can be used to enable decorators in your code.\n"
] |
[
1,
0
] |
[] |
[] |
[
"ecmascript_6",
"es6_proxy",
"javascript",
"javascript_proxy",
"node.js"
] |
stackoverflow_0074661800_ecmascript_6_es6_proxy_javascript_javascript_proxy_node.js.txt
|
Q:
Overlapping Text in Animation in Python
I'm making Terror Attacks analysis using Python. And I wanted make an animation. I made it but I have a problem the text above the animation overlaps in every frame. How can I fix it?
fig = plt.figure(figsize = (7,4))
def animate(Year):
ax = plt.axes()
ax.clear()
ax.set_title('Terrorism In Turkey\n'+ str(Year))
m5 = Basemap(projection='lcc',resolution='l' ,width=1800000, height=900000 ,lat_0=38.9637, lon_0=35.2433)
lat_gif=list(terror_turkey[terror_turkey['Year']==Year].Latitude)
long_gif=list(terror_turkey[terror_turkey['Year']==Year].Longitude)
x_gif,y_gif=m5(long_gif,lat_gif)
m5.scatter(x_gif, y_gif,s=[Death+Injured for Death,Injured in zip(terror_turkey[terror_turkey['Year']==Year].Death,terror_turkey[terror_turkey['Year']==Year].Injured)],color = 'r')
m5.drawcoastlines()
m5.drawcountries()
m5.fillcontinents(color='coral',lake_color='aqua', zorder = 1,alpha=0.4)
m5.drawmapboundary(fill_color='aqua')
ani = animation.FuncAnimation(fig,animate, list(terror_turkey.Year.unique()), interval = 1500)
ani.save('animation_tr.gif', writer='imagemagick', fps=1)
plt.close(1)
filename = 'animation_tr.gif'
video = io.open(filename, 'r+b').read()
encoded = base64.b64encode(video)
HTML(data='''<img src="data:image/gif;base64,{0}" type="gif" />'''.format(encoded.decode('ascii')))
Output:
A:
@JohanC's Answer:
Did you consider creating the axes the usual way, as in fig, ax = plt.subplots(figsize = (7,4)) (in the main code, not inside the animate function)? And leaving out the call to plt.axes()?
|
Overlapping Text in Animation in Python
|
I'm making Terror Attacks analysis using Python. And I wanted make an animation. I made it but I have a problem the text above the animation overlaps in every frame. How can I fix it?
fig = plt.figure(figsize = (7,4))
def animate(Year):
ax = plt.axes()
ax.clear()
ax.set_title('Terrorism In Turkey\n'+ str(Year))
m5 = Basemap(projection='lcc',resolution='l' ,width=1800000, height=900000 ,lat_0=38.9637, lon_0=35.2433)
lat_gif=list(terror_turkey[terror_turkey['Year']==Year].Latitude)
long_gif=list(terror_turkey[terror_turkey['Year']==Year].Longitude)
x_gif,y_gif=m5(long_gif,lat_gif)
m5.scatter(x_gif, y_gif,s=[Death+Injured for Death,Injured in zip(terror_turkey[terror_turkey['Year']==Year].Death,terror_turkey[terror_turkey['Year']==Year].Injured)],color = 'r')
m5.drawcoastlines()
m5.drawcountries()
m5.fillcontinents(color='coral',lake_color='aqua', zorder = 1,alpha=0.4)
m5.drawmapboundary(fill_color='aqua')
ani = animation.FuncAnimation(fig,animate, list(terror_turkey.Year.unique()), interval = 1500)
ani.save('animation_tr.gif', writer='imagemagick', fps=1)
plt.close(1)
filename = 'animation_tr.gif'
video = io.open(filename, 'r+b').read()
encoded = base64.b64encode(video)
HTML(data='''<img src="data:image/gif;base64,{0}" type="gif" />'''.format(encoded.decode('ascii')))
Output:
|
[
"@JohanC's Answer:\nDid you consider creating the axes the usual way, as in fig, ax = plt.subplots(figsize = (7,4)) (in the main code, not inside the animate function)? And leaving out the call to plt.axes()?\n"
] |
[
0
] |
[] |
[] |
[
"matplotlib",
"matplotlib_basemap",
"python"
] |
stackoverflow_0074640564_matplotlib_matplotlib_basemap_python.txt
|
Q:
How to get a valid RS256 token from Azure in a Flutter app?
I'm doing a Flutter app for iOS and Android, and I need to use authentification to access to the main content.
For that I used this pubdev package(aad_oauth), and it works very well. I need to get the token provided by Azure to send it to my API to authenticate my user.
I used this method :
var token = await oauth.getAccessToken();
But the token is considered invalid even by my API then by https://jwt.io/ with the error "invalid signature" but works in the Flutter app.
Here is a censored screen of jwt.io :
Did someone knows how to get a valid token to send it after ?
A:
The invalid signature thrown by jwt.io is well known. You will need to manually obtain and set the Azure AD signing certificate content. Follow the steps detailed in USING JWT.IO TO VERIFY THE SIGNATURE OF A JWT TOKEN.
Regarding validation at the API, you may have to fine-tune its token validation routine. This varies depending on the platform or library used for such end. you can find samples for Microsoft backed libraries here.
For more information on recommended validation please take a look to Validate tokens.
|
How to get a valid RS256 token from Azure in a Flutter app?
|
I'm doing a Flutter app for iOS and Android, and I need to use authentification to access to the main content.
For that I used this pubdev package(aad_oauth), and it works very well. I need to get the token provided by Azure to send it to my API to authenticate my user.
I used this method :
var token = await oauth.getAccessToken();
But the token is considered invalid even by my API then by https://jwt.io/ with the error "invalid signature" but works in the Flutter app.
Here is a censored screen of jwt.io :
Did someone knows how to get a valid token to send it after ?
|
[
"The invalid signature thrown by jwt.io is well known. You will need to manually obtain and set the Azure AD signing certificate content. Follow the steps detailed in USING JWT.IO TO VERIFY THE SIGNATURE OF A JWT TOKEN.\nRegarding validation at the API, you may have to fine-tune its token validation routine. This varies depending on the platform or library used for such end. you can find samples for Microsoft backed libraries here.\nFor more information on recommended validation please take a look to Validate tokens.\n"
] |
[
0
] |
[] |
[] |
[
"azure",
"azure_active_directory",
"flutter"
] |
stackoverflow_0074449261_azure_azure_active_directory_flutter.txt
|