text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
How to encode video with ffmpeg form videocapture Mat
I'm trying to make video editor tool.
[Environment]
C#
WPF
OpenCVSharp4.5
When encoding video,I have to set some config.(fps/width/height/codec/bitrate/field-order)
But,can't set field-order with opencv's videowriter.
VideoWriter video = new VideoWriter(
outPutFilePath,
VideoCaptureAPIs.FFMPEG,
VideoWriter.FourCC(Char.Parse("M"),
Char.Parse("P"),
Char.Parse("4"),
Char.Parse("V"),
fps,
new OpenCvSharp.Size(Width, Height),
true);
for (int movePos = StartFrame; movePos < EndFrame; movePos++)
{
PosFrames = movePos;
Mat mat = SetMatFromFrameNo(PosFrames);
video.Write(mat);
Cv2.WaitKey(1);
}
so,I'm trying to use piped ffmpeg.
But I have no idea.
Could you tell how to encode video From VideoCaptures. thanks.
https://stackoverflow.com/questions/19658415/how-to-use-pipe-in-ffmpeg-within-c-sharp
I refered this to encode with piped ffmpeg. but cant...
I solved it with runnning ffmpeg from Process backgroud
| common-pile/stackexchange_filtered |
Create an underlying taxonomy for tags
Motivation
I am quite fit in Java so I want to help people with their Java questions, but when I look at new questions with the Java tag, the vast majority of them relate to features of third-party libraries that I know nothing about so I give up after a while.
A lot of people seem to be frustrated by this, as shown by the many related questions linked to Is it OK to use language-specific tags for problems with that are not directly connected to coding in such language?.
Problem
Those questions come to the conclusion that there isn't anything one can do about it, because tags are created by people and that this is a folksonomy where you can't force millions of people to assign meta tags like "pure-java" or "third-party-library" to millions of questions, nor are such meta tags appreciated.
Solution
While I aggree that there isn't a good solution within the current tag system, I propose an enhancement to the tag system that requires a lower curation effort and that could help tackle some problems relating to how hard it pose certain kinds of questions within the tag system:
While there are millions of questions on SO, there are certainly much fewer tags. Unfortunately, I didn't find exact numbers, but one could restrict this solution to a few hundred of the most popular tags at first. A small number of people could now curate the those tags into a taxonomy. This could include meta tags, which are not allowed to be used directly in a question.
For example, the tag "jquery" could have two supertags: "library" and "javascript" and "javascript" could have a supertag "programming-language".
This has multiple advantages:
People don't need to use meta tags in their posts, because they are attached to the tags they use.
Meta data is complete and can be relied upon because it is automatically calculated.
People can finally do complex searches, for example for "pure language" specific posts by excluding all subtags of "library".
See also When a tag clearly falls under another tag, A proposal for tag hierarchy on Stack Exchange sites
Oh sorry, I searched for taxonomy but didn't think about searching for "hierarchy". I voted to close my question now.
@KonradHöffner It's all good, now there's one more word for other users to find this proposal on.
| common-pile/stackexchange_filtered |
Add Multiple extensions to string VB.net
I have the below code that looks for the value displayed in a combobox then populates a listbox with the selected file names that relate the extension selected (maybe the code will make more sense!)
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim lyxfle As New IO.DirectoryInfo(sPath)
Dim diar1 As IO.FileInfo() = lyxfle.GetFiles()
Dim MyExt As String = Nothing
Dim MyVariable As String
Dim sFile As String
MyVariable = ComboBox1.Text
If MyVariable = "Forms" Then MyExt = "*.pff"
If MyVariable = "Reports" Then MyExt = "*.mdb"
If MyVariable = "Spreadsheets" Then MyExt = "*.xlsm"
ListBox2.Items.Clear()
sFile = Dir$(sPath & MyExt)
Do While CBool(Len(sFile))
ListBox2.Items.Add(System.IO.Path.GetFileNameWithoutExtension(sFile))
sFile = Dir$()
Loop
End Sub
The following line is what i'm struggling with
If MyVariable = "Spreadsheets" Then MyExt = "*.xlsm"
I basically need it to also look at the extensions .xls & .xlsx and include all files within the list
Both Path and sPath are declared as Private Strings at the top of the class
Any advice
I would probably ditch the Dir$ command and do this: http://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters
Thanks for the link but being very new to vb (this week) I'm struggling to how to implement the change to the Dir$ command
I'll try to keep this simple and use what you have then. This code will get all the files from the folder. Then it will match it to your MyExt selection. As you can see I have added the excel file extensions with a comma between them (can be any special character really). Then all I have to do is see if MyExt contains the FileExtension and add it to the listbox:
Dim MyExt As String = Nothing
Dim MyVariable As String
Dim sFile As String
MyVariable = ComboBox1.Text
If MyVariable = "Forms" Then MyExt = "*.pff"
If MyVariable = "Reports" Then MyExt = "*.mdb"
If MyVariable = "Spreadsheets" Then MyExt = ".xlsm,.xls"
Dim lyxfle As New IO.DirectoryInfo(sPath)
Dim diar1 As IO.FileInfo() = lyxfle.GetFiles()
For Each file As IO.FileInfo In diar1
If MyExt.Contains(file.Extension) Then
ListBox2.Items.Add(IO.Path.GetFileNameWithoutExtension(file.Name))
End If
Next
| common-pile/stackexchange_filtered |
Creating a rich-text editor interface
I am new to html forms. I am trying to create TextArea that has an HTML interface (rich text editor interface). I do not an have idea on how to begin. I am using PHP and JavaScript on my site.
Can somebody please give me a hint?
Either way I don't have the answer for you but you should be more specific. Are you wanting to know how to install a drop in pre made tool for a problem that's already been solved may times over? Or are you wanting a tutorial on how they work under the hood? Each is valid, it just doesn't seem clear which you want an answer to.
You need javascript to have a rich text area.
read this link for more details: http://superdit.com/2011/05/21/12-jquery-based-rich-text-editor/
I guess you mean something like TinyMCE it is a JavaScript solution and can be integrated with any server side language.
| common-pile/stackexchange_filtered |
Additional prefix and suffix required when windowing an OFDM symbol?
To reduce out of band energy, it is common to apply a Raised Cosine filter to the front and back of an OFDM symbol. It is also common to overlap the windowed portions of adjacent symbols to eliminate amplitude dips.
For an OFDM symbol consisting of a Cyclic Prefix followed by NFFT points from an IFFT, is it common to insert an additional prefix and suffix for the windowed portion? If that isn't done then the CP and the IFFT data are shaped by the window, distorting the constellation. A pretty good description of what I am talking about is here:
http://zone.ni.com/reference/en-XX/help/373725A-01/wlangen/windowing/
Yes, it is necessary to add an additional pre/suffix to the OFDM symbol that corresponds to the window length when windowing is applied. As the length of the already existing cyclic prefix is usually chosen as the maximum delay spread of the channel no further Inter-symbol interference (ISI) must be introduced or otherwise orthogonality is lost. The windowing method described in the link you referenced is introducing additional ISI by overlapping consecutive symbols.
Furthermore, weighting some samples of the OFDM time-domain signal with different factors is a distortion that also distorts the constellation in frequency domain, as you say.
Note that windowing is not filtering. Windowing is the multiplication of the OFDM signal $x_k$ with some window function $w_k$. In contrast, a filter has a memory.
| common-pile/stackexchange_filtered |
How to exit a C++ program if the declaration of a global variable throws an exception?
I have a program where I need an instance of a class to be global (it is const), but the constructor of the class requires a particular text file to exist (if it doesn't exist the program should quit). If I throw an exception in the constructor it cannot be caught outside of the constructor because I can't have a try{ }catch{ } block outside of a function which I need to do in order for the instance of the class to be global.
How can I use exceptions to ensure memory is still cleaned up if the declaration of the global variable throws an exception?
Could you expand on what you mean by a global cleaning method? I spent a while trying to find such a thing earlier.
First of all, don't worry about the memory.
If the constructor of a global throws, your program isn't staying around long enough for it to matter, it's already on the way out.
Next, if you really insist, just make sure the destructors of all global objects are also able to destroy all associated resources, as they should be able to do for RAII to work anyway.
And if an object is only partially constructed, all dtors corresponding to successfully completed member (and base) ctors will be called, so it shouldn't be too hard to make sure your ctor does not leak anything on throwing.
Thanks, just did a quick check to see that if I called exit(EXIT_FAILURE) when the exception was thrown the destructors of previously declared globals would be called (and they are) :)
| common-pile/stackexchange_filtered |
Web preview equivalent in elastic beanstalk AWS
Does elasticbeanstalk have a same feature as web preview in aws amplify?
How can I deploy my PRs to elasticbeanstalk automatically to test if it is working properly?
CodePipeline integrates with beanstalk.
yea. but for every Pull request, i need to set up a new environment to run a test on it if i use code pipeline. Im looking for a way to automate it
Add CloudFormation actions that will create the new EB env for you each time you run your CP.
| common-pile/stackexchange_filtered |
Error: Local workspace file ('angular.json') could not be found
I have travis-ci integrated with my GitHub account (https://github.com/pradeep0601/Angular5-Router-App).
When I updated @angular/cli version from 1.7.4 to 6.0.0-rc.3, the build started failing with an error:
Local workspace file ('angular.json') could not be found.
Error: Local workspace file ('angular.json') could not be found.
at WorkspaceLoader._getProjectWorkspaceFilePath (/home/travis/build/pradeep0601/Angular5-Router-App/node_modules/@angular/cli/models/workspace-loader.js:37:19)
at WorkspaceLoader.loadWorkspace (/home/travis/build/pradeep0601/Angular5-Router-App/node_modules/@angular/cli/models/workspace-loader.js:24:21)
at TestCommand._loadWorkspaceAndArchitect (/home/travis/build/pradeep0601/Angular5-Router-App/node_modules/@angular/cli/models/architect-command.js:177:32)
at TestCommand.<anonymous> (/home/travis/build/pradeep0601/Angular5-Router-App/node_modules/@angular/cli/models/architect-command.js:45:25)
at Generator.next (<anonymous>)
at /home/travis/build/pradeep0601/Angular5-Router-App/node_modules/@angular/cli/models/architect-command.js:7:71
at new Promise (<anonymous>)
at __awaiter (/home/travis/build/pradeep0601/Angular5-Router-App/node_modules/@angular/cli/models/architect-command.js:3:12)
at TestCommand.initialize (/home/travis/build/pradeep0601/Angular5-Router-App/node_modules/@angular/cli/models/architect-command.js:44:16)
at /home/travis/build/pradeep0601/Angular5-Router-App/node_modules/@angular/cli/models/command-runner.js:100:23
package.json snippet to better understand the running environment:
"@angular/cli": "6.0.0-rc.3",
"@angular/compiler-cli": "^5.2.0",
"@angular/language-service": "^5.2.0",
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
I faced the same issue, and it was silly, this occurs when using terminal from visual studio code and and works when switching to windows default cli!
I just had the same problem.
It's related to release v6.0.0-rc.2, https://github.com/angular/angular-cli/releases:
New configuration format. The new file can be found at angular.json (but .angular.json is also accepted). Running ng update on a CLI 1.7 project will move you to the new configuration.
I needed to execute:
ng update @angular/cli --migrate-only --from=1.7.4
This removed .angular-cli.json and created angular.json.
If this leads to your project using 1.7.4, install v6 locally:
npm install --save-dev<EMAIL_ADDRESS>
And try once again to update your project with:
ng update @angular/cli --migrate-only --from=1.7.4
@FindOutIslamNow, You need to update webpack I guess
running ng update @angular/cli --migrate-only --from=1.7.4 results in error: Collection<EMAIL_ADDRESS>cannot be resolved.. any way to fix it?
I am also getting Unknown option: '--extractCss'
Make sure your npm and nodejs versions are up to date or you will likely get a failure. ng update @angular/cli is all that is needed.
@user1932595 I had to upgrade @schematics/angular to the latest version to get past that error.
A short note on above. The removing the .angula-cli.json did not happen for me until the second run of the ng update command.
I was getting the Unknown option: '--extractCss' error too - turned out the package.json contained it in the scripts section twice - deleting it solved the problem.
I was getting the same error messages. It was a silly mistake on my end, I was not running ng serve in the directory where my Angular project is. Make sure you are in the correct directory (project directory) before running this command.
I did the same thing. You create a directory to serve you project, and it creates another directory inside of that directory (slap myself)
i.e. ng new my-app, cd my-app (I saw this comment earlier but assumed it meant the top level one)
With recent version, without --migrate-only I got the repo updated.
I did ng update
The Angular CLI configuration format has been changed, and your existing configuration can be updated automatically by running the following command:
ng update @angular/cli
Updating karma configuration
Updating configuration
Removing old config file (.angular-cli.json)
Writing config file (angular.json)
Some configuration options have been changed, please make sure to update any npm scripts which you may have modified.
DELETE .angular-cli.json
CREATE angular.json (3684 bytes)
UPDATE karma.conf.js (1040 bytes)
UPDATE src/tsconfig.spec.json (322 bytes)
UPDATE package.json (1340 bytes)
UPDATE tslint.json (3140 bytes)
I get Incompatible peer dependencies found. See above.
An unexpected error happened; package @angular/flex-layout has no version null.
Well, I faced the same issue as soon as I updated my angular cli version.
Earlier I was using 1.7.4 and just now I upgraded it to angular cli 6.0.8.
To update Angular Cli global:
npm uninstall -g angular-cli
npm cache clean
npm install -g @angular/cli@latest
To update Angular Cli dev:
npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install
To fix audit issues after npm install:
npm audit fix
To fix the issue related to "angular.json":
ng update @angular/cli --migrate-only --from=1.7.4
Uninstall the old version of Angular cli, and install Angular CLI global:
Update Angular cli global package to the next version, "@angular/compiler-cli": "^6.0.0"
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@next
Generate a new project and default application by running the following command:
ng new my-project
cd my-project
ng serve
do not use cli@next, use cli@latest or you will get the beta versions.
Try using the below command:
ng update @angular/cli --migrate-only --from=1.7.4
It will perform the below
Updating karma configuration
Updating configuration
Removing old config file (.angular-cli.json)
Writing config file (angular.json)
Pls note that the above command should be run in the folder where you have file .angular-cli.json and it will be then replaced by angular.json.
I've run the command several times and the angular.json file never shows up. However, if i delete the angular-cli.json file, run the command, the angular-cli.json file is added back. what am i missing here?
If you don't know the version ,current project has been made, you can omit --from command and type --migrate-only
ng update @angular/cli --migrate-only
If all sorts of updating commando's won't do it. Try deleting package-lock.json. And then run npm install. Did the trick for me after going through tons of update commando's.
Any reason not to take this approach as a default (dropping node_modules folder and package-lock.json), and just running npm install?
Check your folder structure where you are executing the command, you should run the command 'ng serve' where there should be a angular.json file in the structure.
angular.json file will be generated by default when we run the command
npm install -g '@angular/cli'
ng new Project_name
then cd project_folder
then, run ng serve. it worked for me
It works for me:
Delete folder node_modules
Run command: npm install
( If it does not work for the first time, repeat this 2 or 3 times, Its funny but it works for me. )
Why would repeating this process have a different effect than the first time?
Just run ng update @angular/cli in your console.
You might find some vulnerabilities after running the command (if using npm), but then just runnpm audit fix in the console to fix them. This command will scan the project for any vulnerabilities and it will also fix compatibility issues by installing updates to these dependencies. If you do not wish to auto fix these vulnerabilities immediately, you can perform a Dry Run: by running npm audit fix --dry-run -json in the console. This will give you an idea of what the command npm audit fix will do, in the form of json in the console.
I had the same problem, and what I did that works for me was:
Inside package.json file, update the Angular CLI version to my desired one:
"devDependencies": { ...
"@angular/cli": "^6.0.8",
...
}
Delete the node_modules folder, in order to clean the project before update the dependencies with:
npm install
ng update @angular/cli
Try to build again my project (the last and successful attempt)
ng build --prod
For me what worked was creating a new Angular project and just copied the angular.json file in the project that had a problem due to the fact that the angular.json file was missing.
For me the problem was because of global @angular/cli version and @angular/compiler-cli were different. Look into package.json.
...
"@angular/cli": "6.0.0-rc.3",
"@angular/compiler-cli": "^5.2.0",
...
And if they don’t match, update or downgrade one of them.
I also faced same issue and i just executed below command.
ng update @angular/cli --migrate-only --from=1.6.4
It simply delete angular-cli.json and create angular.json. You can find this in logs.
Once you start execution. You will be able to see below logs in your terminal.
Updating karma configuration
Updating configuration
Removing old config file (.angular-cli.json)
Writing config file (angular.json)
Some configuration options have been changed, please make sure to update any
npm scripts which you may have modified.
DELETE .angular-cli.json
CREATE angular.json (3599 bytes)
UPDATE karma.conf.js (962 bytes)
UPDATE src/tsconfig.spec.json (324 bytes)
UPDATE package.json (1405 bytes)
UPDATE tsconfig.json (407 bytes)
UPDATE tslint.json (3026 bytes)
Just check your directory, you must run "ng serve " on the same directory where you have created the project.
So, first enter in your project directory.
Check out this link to migrate from Angular 5.2 to 6.
https://update.angular.io/
Upgrading to version 8.9 worked for me.
For me, the issue was that I have an angular project folder inside a rails project folder, and I ran all the angular update commands in the rails parent folder rather than the actual angular folder.
I was having this error message inside a docker container. I resolved it adding:
WORKDIR /usr/src
to Dockerfile.
I had the same problem and found that there was no package.json in my project (but only the package-lock.json). I then
restored the package.json from source control
uninstalled the global and local angular-cli versions (like the instruction says)
followed the standard upgrade procedure
..and all worked out fine. Took a while to figure it out, but that did it for me.
~/Desktop $ ng serve
Local workspace file ('angular.json') could not be found.
Error: Local workspace file ('angular.json') could not be found.
at WorkspaceLoader._getProjectWorkspaceFilePath (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:37:19)
at WorkspaceLoader.loadWorkspace (/usr/lib/node_modules/@angular/cli/models/workspace-loader.js:24:21)
at ServeCommand._loadWorkspaceAndArchitect (/usr/lib/node_modules/@angular/cli/models/architect-command.js:180:32)
at ServeCommand.<anonymous> (/usr/lib/node_modules/@angular/cli/models/architect-command.js:47:25)
at Generator.next (<anonymous>)
at /usr/lib/node_modules/@angular/cli/models/architect-command.js:7:71
at new Promise (<anonymous>)
at __awaiter (/usr/lib/node_modules/@angular/cli/models/architect-command.js:3:12)
at ServeCommand.initialize (/usr/lib/node_modules/@angular/cli/models/architect-command.js:46:16)
at Object.<anonymous> (/usr/lib/node_modules/@angular/cli/models/command-runner.js:87:23)
This is because I haven't choose the Angular project directory.
It should be like:
~/Desktop/angularproject $ ng serve
I was trying to set my Ionic 4 app to run as a pwa. When I run the command:
ng add @angular/pwa
...got the error message. After some try and error I discovered that when my project was created the start command was wrong. I was using an Ionic 3 version:
ionic start myApp tabs --type=ionic-angular
And the correct is:
ionic start myApp tabs --type=angular
with no 'ionic-' in type. This solved the error.
For people who have simply cloned a project and trying to run it, you need to run npm install first. I totally forgot to run this and was simply running ng serve before installing node modules.
| common-pile/stackexchange_filtered |
$H^s(\mathbb R^d) \subset \bigcap_{2<p<\infty} L^p(\mathbb R^d)$ $0<s<1/2$?
Consider Sobolev spaces
$$ H^s(\mathbb R^d)=\{f\in \mathcal{S}'(\mathbb R^d): \mathcal{F}^{-1} [\langle \cdot \rangle^s \mathcal{F}(f)] \in L^2(\mathbb R^d) \}$$
where $\langle \cdot \rangle = (1+ |\cdot|^2)^{1/2}, s\in \mathbb R,$ and $\mathcal{F}$ and $\mathcal{F}^{-1}$ are Fourier transform and the inverse Fourier transform.
My Question is: Let $0<s<1/2.$ Can we say that $$H^s(\mathbb R^d) \subset \bigcap_{2<p<\infty} L^p(\mathbb R^d)$$ ? If not, any counter example?
Do the usual Sobolev embedding theorems not answer this?
| common-pile/stackexchange_filtered |
Trouble recalling hashes from file in Perl
This phone book script works well in memory but I am having a difficult time recalling the saved data on re execution. The hashes go to the text file but I have no idea how to recall them when the script is starting. I have used "Storage" to save the data, and I have tried to use the "retrieve"function to bring the data back, with no luck. I think either I did not follow a good path from the start or I just don't know where in the code or which %hash should "retrieve" the stored data.
I am very new to Perl and programming so I hope I explained my situation clearly
#!/usr/bin/perl
use 5.18.2;
use strict;
use warnings;
use autodie;
use Scalar::Util qw(looks_like_number); # This is used to determine if the phone number entered is valid.
use Storable;
use Data::Dumper;
####################################
# Enables sub selections
my %contact; while (){
my $selection = list();
if ($selection == 1){
addContact();
}
elsif ($selection == 2){
removeContact();
}
elsif ($selection == 3){
findContact();
}
elsif ($selection == 4){
listAllContacts();
}
elsif ($selection == 5) {
clearScreen();
}
elsif ($selection == 888) {
quit();
}
else {
print "Invalid entry, Please try again.\n\n"; # displays error message
}
}
####################################
# Shows instructions for use
sub list{
print "\n------------------------------------------------------------------------\n";
print "- ----- Select an option ----- -\n";
print "- 1 = add, 2 = remove, 3 = find, 4 = list, 5 = tidy screen, 888 = quit -\n";
print "------------------------------------------------------------------------\n";
print "What would you like to do? ";
my $listChoice = <STDIN>; # enter sub choice here
return $listChoice;
}
####################################
# Add contact info sub
sub addContact{
print"Name?: ";
chomp (my $addContactName = <STDIN>); # contact name
$addContactName = lc($addContactName); # changes all letters to lower-case
if (exists $contact{$addContactName}){ # checks for duplicate contact
print"Duplicate Record!!! Please enter a different name\n\n"; # displays error message
}
else {
print"Phone Number?(omit dashes, ex.<PHONE_NUMBER>): ";
chomp (my $phoneNumber = <STDIN>); # phone number
if (looks_like_number($phoneNumber)){ # checks that its only numbers
$contact{$addContactName} = $phoneNumber; # adds hash to contact
# open (FILE, ">>pb.txt"); # file to save contact info
# print FILE $addContactName .= ":", $phoneNumber .= "\n"; # add a colon and new line to contact info in text file
}
else{
print "Phone Numbers do not have letters!, Let's start again.\n\n"; # displays error message
}
}
}
####################################
# sub to remove contact
sub removeContact {
print"Enter name to remove: \n";
chomp (my $removeContact = <STDIN>); # enter contact name to remove
$removeContact = lc($removeContact); # changes all letters to lower-case
if (exists $contact{$removeContact}){ # looks for contact name
delete($contact{$removeContact}); # delete contact name and all info
print"The contact \' $removeContact \' has been removed\n"; # gives confirmation of contact removal
}
else {
print"This name does not exist in the record!! Try Again.\n\n"; # displays error message
}
}
####################################
# sub to find a contact
sub findContact {
print"Whom are you looking for?: \n";
chomp(my $findContact = <STDIN>); # enter contact name to find
$findContact = lc($findContact); # changes all letters to lower-case
if (exists $contact{$findContact}) { # looks for contact name
print($contact{$findContact},"\n\n"); # prints info for found contact name
}
else {
print"This name does not exist in the record!!! Try Again.\n\n"; # displays error message
}
}
###############################################
# Lists all contacts entered alphabetically
sub listAllContacts {
for my $key (sort keys %contact) { # sorts contacts alphabetically
print "$key, $contact{$key}\n"; # shows all contacts on screen
}
}
#################################################
# Tidy sub - just clears the screen of clutter
sub clearScreen {
system("clear");
}
####################################
# sub to leave the program
sub quit{
store (\%contact, "pb.txt"); # save data to text file
system("clear"); # clears screen
exit(); # exits program
}
The store function comes from the module Storable (you can see full documentation for the module by typing perldoc Storable).
It's counterpart is called retrieve.
So in order to read back the contacts on the script start you can replace the line
my %contact; while (){
with
my %contact;
eval {
%contact = %{ retrieve "pb.txt" };
};
while (1) {
The eval makes the retrieval not die on error (whether because pb.txt is not there or does not contain the data in a format compatible with Storable). You might want to have somewhat more elaborate error handling instead of just ignoring any errors, but this should do as an example.
Thanks Grrrr! I'll look into the error catching, but this got me over a 3 day hurdle.
| common-pile/stackexchange_filtered |
Is smoking weed legal or just tolerated in Colorado?
On 1.1.2014 at least 24 pot shops opened in Colorado and I wonder if smoking marijuana is now legal or just tolerated as long as you don't smoke on the street (like in Amsterdam). What are the differences between Colorado and Amsterdam? Are there any restrictions for tourists?
It's 100% legal now, within some limits. Wikipedia summarizes the situation neatly:
Adults aged 21 or older can grow up to three immature and three mature cannabis plants privately in a locked space, legally possess all cannabis from the plants they grow (as long as it stays where it was grown), legally possess up to one ounce of cannabis while traveling, and give as a gift up to one ounce to other citizens 21 years of age or older. Consumption is permitted in a manner similar to alcohol, with equivalent offenses proscribed for driving. Public consumption remains illegal.
The one big difference to Amsterdam is that, unlike Dam's coffeeshops, you are not allowed to smoke pot in the stores that sell it, or any other business open to the public. In practice, this means the only place you can fully legally smoke is at your home (or someone else's with their permission).
This article has more practical details, including the important note that, without Colorado ID, you can only buy 1/4 oz (~7g) from a shop. Bringing cannabis to the airport is also illegal, and taking it out of state lines is also a bad idea (because it's illegal everywhere else except, soon, Washington).
It's also important to note that possession of marijuana is still a federal crime, and that that law is still applicable in Colorado. The Department of Justice has indicated that they'll turn a blind eye for the time being, but until the conflict between federal law and the new state regs is resolved, they will be on shaky footing - especially every 4 or 8 years when the White House changes hands.
True enough, but the momentum is pretty clear now, I can't really see the Feds cracking down hard anytime soon.
can one fly to CO, buy some weed and fly back with the weed to another state (say they want to be ready to smoke some when they are flying back in to CO again, because the plants woulda died of neglect in the mean while) ?
And is the 3 plant rule, per adult ? per family ?
@happybuddha it's illegal to transport across state lines, and possession in the airport is illegal as well IIRC.
| common-pile/stackexchange_filtered |
Linear integral with 2 points in space
$ \int_{AB} yz dx + zx dy + xy dz $
This is my line integral and I need to find out a method to solve it. I have 2 points A(1,1,0) and B(2,3,1). These 2 points form a line in space.
What I find hard to comprehend is that I have to apply this theory:
$ \frac {\partial P}{\partial y} = \frac{\partial Q}{\partial x} $
$ \frac {\partial Q}{\partial z} = \frac{\partial R}{\partial y} $
$ \frac{\partial R}{\partial x} = \frac{\partial P}{\partial z} $
What do these partial derivatives represent? Functions?
Besides that,there is another formula shown below that represent 3 integrals. These 3 integrals represent a function in space? If so,what does the variable $t$ means? A constant?
$V(x,y,z)= \int_{x_0}^{x} P(t,y_0,z_0) dt+\int_{y_0}^{y} Q(x,t,z_0)dt+\int_{z_0}^{z}R(x,y,t)dt$
Can someone explain each part to me? I would appreciate your help.
Anyone? I am really confused.
The notation $\int_C P \, dx + Q \, dy + R \, dz$ is also sometimes written as $\int_C \vec{F} \cdot d \vec{r}$, where $\vec{F} = \left< P,Q,R \right>$, so $P,Q,R$ are the components of the vector field. In your example, $P = yz$, $Q = zx$, and $R = xy$.
The equations you wrote with the partial derivatives are another way of saying that the "curl" of this vector field is zero. In math notation, $\nabla \times \vec{F} = \vec{0}$. I assume you've seen curl before? This means the vector field is "conservative".
When a vector field is conservative, it means there is a "potential function" $f(x,y,z)$, so that $\vec{F}$ is its gradient. In other words, $\vec{F} = \nabla f$.
The Fundamental Theorem of Line Integrals says that the value of this line integral is the difference of the values of the potential function at the endpoints:
$$ \int_{AB} \vec{F} \cdot d \vec{r} = f(B) - f(A) $$
So if you can find this potential function $f$ (I hope you can do that yourself, it's really quite easy in this example), then you don't need to do the integral at all! You just plug the points $A$ and $B$ into this function and subtract.
Do you mean something like this V(x,y,z)=(z,x,y) ?
Is $V$ the potential function? If so, then $V(x,y,z) = xyz$. This is what I was calling $f$ in my answer.
You have been given an excellent answer by Nick. I just upvoted it, and you should at least upvote it (it is a manner to say "thank you"), but even validate it : you will definitely not receive better answers to this question.
| common-pile/stackexchange_filtered |
ggplot2: use colour / shape / ... inside and outside of aes() in a flexible plotting function
The goal
I'd like to have a function that processes some input X and produces a gglot graph using geom_point.
That function should allow to map columns of X to various aesthetics inside aes() (via arguments .shapefac, .colfac, etc.), but also allow to set e.g. point colour and shape manually (e.g. colour = "tomato"), outside of aes().
The problem
If .shapefac or .colfac arguments are provided, the aesthetics get overridden by the specification of shape and colour, respectively. This is explained e.g. here.
What I've tried
One workaround would be to remove the shape and colour arguments, and allow them to be specified using ... in geom_point. This works, but needs some advanced R knowledge for a user of such a function.
The question
Does anybody know if there is
a way to change the default setting for the shape and colour arguments outside of aes() in geom_point?
a way to override the specification of the shape and colour arguments, if an aesthetic is used?
another way to reach the goal stated above, without using ...?
Any hints or explanations are much appreciated!
The following function and plots hopefully illustrate the problem.
define function
library(mlbench)
data("Ionosphere")
cplot <- function(X, v = 1:ncol(X), .shapefac = NULL, .colfac = NULL, shape = 21, colour = "black",
center = TRUE, scale = FALSE, x = 1, y = 2, plot = TRUE) {
library(ggplot2)
# some code processing X to Y
d.pca <- prcomp(X, center = center, scale. = scale)
Y <- data.frame(X, d.pca$x)
v <- round(100 * (d.pca$sdev^2 / sum(d.pca$sdev^2)), 2)
# plot PCA
p <- ggplot(Y, aes_string(x = paste0("PC",x), y = paste0("PC",y))) +
geom_point(aes_string(shape = .shapefac, colour = .colfac),
shape = shape, color = colour) +
labs(x = paste0("PC ", x, " (", v[x], "%)"),
y = paste0("PC ", x, " (", v[y], "%)")) +
theme_bw()
if (plot) print(p)
invisible(p)
}
setting colour and shape arguments outside aes()
This works as it should.
cplot(Ionosphere, v = 3:34, colour = "tomato", shape = 4)
setting shape inside aes() when shape outside aes() has a default of 21
The default shape = 21 outside aes() overrides the shape aesthetic.
cplot(Ionosphere, v = 3:34, .shapefac = "Class")
setting colour inside aes() when colour outside aes() has a default of "black"
The default colour = "black" outside aes() overrides the colour aesthetic.
cplot(Ionosphere, v = 3:34, .colfac = "Class")
failed trials to set default shape and colour to NULLor NA
# results in an empty plot (shape = NA)
cplot(Ionosphere, v = 3:34, .shapefac = "Class", shape = NA)
#> Warning: Removed 351 rows containing missing values (geom_point).
# results in an error
cplot(Ionosphere, v = 3:34, .shapefac = "Class", shape = NULL)
#> Error: Aesthetics must be either length 1 or the same as the data (351): shape
Created on 2021-09-20 by the reprex package (v2.0.1)
I saw some ideas for changing the default point shape here: https://stackoverflow.com/questions/14196804/how-to-change-default-aesthetics-in-ggplot
how should a mapping on "Class" work if you remove it from the data? -> Ionosphere[,-c(1,2,35)]
Sorry that was a typo, not sure why reprex still worked, probably because X was assigned. I fixed it in the question.
@aosmith I think this is what I was looking for, thanks!
One option to achieve your desired result may look like so:
If the aesthetics are provided set the color and/or shape params to NULL
Make use of modifyList to construct a list of arguments to be passed to geom_point which includes the mapping and the non-NULL parameters. Making use modifyList will drop any NULL.
Make use of do.call to call geom_point with the list of arguments.
Note: I slightly changed your function to select only numeric columns for the PCA.
library(mlbench)
library(ggplot2)
data(Ionosphere)
cplot <- function(X, .shapefac = NULL, .colfac = NULL, shape = 21, colour = "black",
center = TRUE, scale = FALSE, x = 1, y = 2, plot = TRUE) {
col_numeric <- unlist(lapply(X, is.numeric))
# some code processing X to Y
d.pca <- prcomp(X[, col_numeric], center = center, scale. = scale)
Y <- data.frame(X, d.pca$x)
v <- round(100 * (d.pca$sdev^2 / sum(d.pca$sdev^2)), 2)
colour <- if (is.null(.colfac)) colour
shape <- if (is.null(.shapefac)) shape
mapping <- aes_string(shape = .shapefac, colour = .colfac)
args <- modifyList(list(mapping = mapping), list(color = colour, shape = shape))
geom <- do.call("geom_point", args)
p <- ggplot(Y, aes_string(x = paste0("PC", x), y = paste0("PC", y))) +
geom +
labs(
x = paste0("PC ", x, " (", v[x], "%)"),
y = paste0("PC ", x, " (", v[y], "%)")
) +
theme_bw()
if (plot) print(p)
invisible(p)
}
cplot(Ionosphere, colour = "tomato", shape = 4)
cplot(Ionosphere, .shapefac = "Class")
cplot(Ionosphere, .colfac = "Class")
cplot(Ionosphere, .colfac = "Class", .shapefac = "Class")
cplot(Ionosphere, .shapefac = "Class", shape = NULL)
Wow @stefan, this is exactly what I was looking for! Interesting use of if, and I learnt about modifyList. This solution also seems better compared to using update_geom_defaults, because it truly overrides any specification of e.g. shape if .shapefac is given, also for the legend.
| common-pile/stackexchange_filtered |
Fueling strategy while running a marathon in warm weather
I'm going to be running in the London Marathon in two weeks. Initially my target time was to run sub 4 hours. Its my first marathon and my training had been going quite well until the last two weeks.
I've been doing a long run every Sunday. The longest I've done is 29 KM (18 miles) and my time was 2 hrs and 34 mins with an average pace of 5:19 per km (8:34 per mile). I also did a half marathon two weeks ago and my time was 1 hr and 45 mins.
Both my half marathon and 29k times indicate that I should be able run a sub 4 hour marathon (if not quicker according to some calculators).
My biggest run was meant to be last Sunday, 35k (22 miles). As I set off, I did feel like it was a litte bit tougher than normal but just thought it would be a rough patch so tried not to pay too much attention to it. At the 21k mark, I started struggling. It was like nothing I've ever experienced before on a long run, I couldn't run anywhere near my target pace, my effort levels felt quite high yet my km splits were >6 mins/km. At 25.6 km I gave up and ended my run. I realised afterwards, that I must've hit the notorious 'wall'. I didn't have a very good pre run breakfast. I had three High5 ISO Gels throughout the run (aim was to have one every 10k).
After the disastrous run last Sunday, I decided to attempt a 35k again today. This time I had a substantial breakfast around three hours before my run; 4 weetabixes and half a banana around an hour before I set out. Also sipped on water in the hours leading upto it. I knew I was well hydrated based on pee colour.
I set off with the aim of going at an easier pace than my previous long runs. Kept the effort level relatively low and I felt quite good after an opening rough 5k. Had gels every 10km and overall I felt a lot better at the 21K stage than last week.
However I started experiencing the same problems as last week at the 25k mark. I could feel the pace slipping away and it became physically and mentally very tough just to keep running regardless of the pace. I gave up at the 27k mark :(
The weather has picked up in London in the past week or so. These are the first long runs I'm doing in the sun and slightly warmer weather, they seem to have a massive impact on my performance. My half marathon PB and 29k were ran on cold, cloudy days.
After every long run, I evaluate my target marathon time based on how the long run felt and the pace I did it at. My initial target time was sub 4:30, this was based on before I did any training. Over the weeks its been mostly at sub 4, but after my half marathon I was entertaining sub 3:45. My last two runs have put to bed any of those target times and I think I'm back to my initial target time of sub 4:30.
Based on my situation, my questions are:
How can I deal with the effects of hot weather and minimise any impact on my performance during the marathon?
What fueling strategies would folks recommend? I'm toying with the idea of using Zipvit gels too as they have 51 grams of carbs per sachet.
There are many factors that cut your marathon short. Firstly, the heat dissipation is better in a shorter runner than in a tall runner (the area-volume ratio larger to transfer heat if shorter). Secondly, the warm environment requires extra effort from your body like running extra miles. The ideal solution is to get used to the warm environment weeks before the competition. Lastly, the worrying thing is the inexperience in warm weather that can result to lack of consistency. To run marathon in warm weather, you need to get used to such climate and distances.
Just two weeks until the warm marathon race
Extra heat must transferred somehow away because your body is not yet used to it. Either you need to cut your goals (less heat from muscles generated) or cool down your body other ways such as run-showers, cooling body in aid stations and more hydration. The risks contain overhydration and hyponatremia where you start to feel fatique and heavier body can result to more pain in joints such as knees.
Strategies to tackle the extra heat in warmer race environment
water yourself in aid stations
drink more during the race: extra weight requires more effort from your legs, your front thighs/shins may fail. Relax calves, shins and front thighs before the race: backwards walking/running etc, more here.
plan your hydration on aid stations such as more gels and watering pre 20km while more cold watering later
More about aid stations planning in https://sports.stackexchange.com/questions/13718/how-to-manage-hydration-in-aid-stations-during-marathon is covered in terms of the opposite hydration levels where dehydration versus overhydration analysed.
Long term
It seems that the distance is not your main problem but the consistency. The inconsistency is probably due to the lack of experience in warm runs. 2 weeks before race should be more intensive training and you have little time to do major changes. Just 1 week before the race it is important to build up the glycogen reserves and work particularly on the front thighs and knees -- particularly if your plan is to do major changes in hydration. Your body cannot adapt in a split second to more hydration and watering can also be an obstacle. In long term, overhydration can drain important trace minerals. In next run, train in warmer weather or simulate it with clothes.
| common-pile/stackexchange_filtered |
Kendo UI Dynamically Change Datasource String (XML)
I have a Kendo Grid that binds to an XML DataSource. How can I have the DataSource change, based off the selection of a drop down list. Example:
//Create DataSource
var gridDataSource = new kendo.data.DataSource({
transport: {
read: [DropDownListValue] + ".xml",
dataType: "xml"
}
});
gridDataSource.read();
function createGrid(){
var grid = $("#grid").kendoGrid({
dataSource: gridDataSource
}...
};
Where [DropDownListValue] is a drop down list on my form. In this example if [DropDownListValue] = 1, the datasource would be "1.xml". If [DropDownListValue] = 2, then datasource would be "2.xml".
I was able to achieve this by adding the following to the On Change event of my Drop Down list:
//Assign drop down value to variable
var dropDownListValue = $("#dropDown1").val();
//Concatenate drop down variable to file name
var dynamicUrl = dropDownListValue +".xml";
//Assign grid to variable
var grid = $("#grid").data("kendoGrid");
//Set url property of the grid data source
grid.dataSource.transport.options.read.url =dynamicUrl;
//Read data source to update
grid.dataSource.read();
RegDwight, thanks for the cleanup. If you agree this is correct, please mark as answered. I can attest I am using it now and it works great.
How to send the property also ?
| common-pile/stackexchange_filtered |
How can I convert including timezone date in swift?
I want to convert 2015-08-14T20:02:25-04:00 to 2015-08-14 16:02
I tried below, but it could't execute well(returned nil).
let d = "2015-08-14T20:02:25-04:00"
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ"
let date: NSDate? = formatter.dateFromString(d)
How can I convert this date format?
I'm no sure if NSDateFormatter has a direct way, but you can decompose the string (ie. split into date, time, TZ) and build a conforming string to put into NSDateFormatter.
Xcode 8 • Swift 3
You need to escape 'T' and use the appropriate timezone symbol. Note that it will depend if your date string represents a UTC (zero seconds from GMT) time timezone with Z "XXXXX" or without it +00:00 "xxxxx":
let dateString = "2015-08-14T20:02:25-04:00"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
if let date = formatter.date(from: dateString) {
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let string = formatter.string(from: date)
print(string)
}
If you need some reference you can use this:
@Vakas feel free to post a new question with your code and the steps necessary to reproduce the problem I will gladly take a look if you would like me to
@LeoDabus Let me try a bit, will post a question if not resolved. Thanks.
@Vakas I tested +05:00 and it gave me the time with 8 hours less which is the correct offset from where I am -03:00
@LeoDabus woking for me as well, I had some other issue in my date string.
You can use :
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZ"
Hope this help you !
You the best!))
| common-pile/stackexchange_filtered |
Turn off transparency for Windows 7 taskbar only
I don't like the semi-transparent nature of the Windows 7 taskbar. When a white window slides down there it makes the icons and, more importantly, the Workrave (http://www.workrave.org/) toolbar, hard to see.
Is there a way to disable transparency ONLY for the taskbar (I like it everywhere else).
Unfortunately as far as I know, it is only possible to do it for everything through Control Panel > Personalization > Window Color
I would be interested to see if anyone has a solution/reg hack or similar for just the taskbar though as I have the same problem as you sometimes when I drag a window under it (Explorer Windows).
Use a black wallpaper, or blacken the lower portion of your wallpaper using Paint. Alternatively, you can install the ZoneTick Clock, which disables taskbar transparency while it is running.
+1 for suggesting blackening the bottom of the desktop image
It's not the wallpaper that's the problem for me, it's when I drag a window with a white background partially below the taskbar. This seems to be something I do with great frequency, for some reason. Since windows are on top of the wallpaper, changing the wallpaper wouldn't help. ZoneTick clock is an interesting suggestion, though naturally I prefer a solution that's free.
As a last resort, you could try writing a quick program that uses the Desktop Window Manager API to do that. Here is a similar discussion: http://www.anuko.com/forum/viewtopic.php?f=2&t=761
| common-pile/stackexchange_filtered |
input 4 digit number after typing without pressing enter with python
I am trying to make an input for a four digit number, and exactly when I finish typing the number I want the number to input.
Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named "What topics can I ask about here?" and "What types of questions should I avoid asking?". And more importantly, please read the Stack Overflow question checklist. You might also want to learn about Minimal, Complete, and Verifiable Examples.
Are yo familiar with the input function?
@PatrickHaugh OP wants to take an input of length four without the user having to press enter.
@AhmetEmreKılınç how would an MCVE for this problem look like? There's not much you can try here without any knowledge.
Apply duplicate four times.
What should happen if they enter three digits and then a letter?
| common-pile/stackexchange_filtered |
Laravel 5.5 empty object
Good afternoon guys, I'm having an issue I don't know if you have the same trouble, I upgrade my Laravel project and now all routes like this
Route::get('detail/client/{client}', "controller@method")
are breaking everything because the object instanced in the controller comes empty...
public function detail(FileRequest $request, Client $client){
dd($client) // empty object
}
If someone can help me with this please. If I remove the Client model and make the dd then return the ID of the object i.e "594"
Is that client soft-deleted perhaps?
Nope I review that, this occurs with every client
You haven't written base Laravel version you are upgrading from, but I think it might have something in common with \Illuminate\Routing\Middleware\SubstituteBindings::class middleware.
Make sure you have it in middlwareGroups like this:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class, // <- this is the line you should have
],
'api' => [
'throttle:60,1',
'bindings',
],
];
in app/Http/Kernel.php file
and also make sure the routes you have problem are in web middleware group.
@LuisJosueUscanga Yes, but you wrote you upgrade your Laravel project so I thought that you are upgrading it from previous version like for example 5.0 or 5.1
Well I add the binding to my routes but then throws Call to a member function parameters() on null
Your answer was correct, thanks, I was having problems because I add other middlewares and add the api middleware with the middleware bindings to the end of that list of middlewares. I had to put it first of all the middlewares and clean de cache and then it works thank you
| common-pile/stackexchange_filtered |
Unable to make the chrome extension work in the background when the extension is closed
The setInterval script works when the popup is open. But when the extension is closed, the script doesn't run in the background. Here is the code:
Manifest.json:
"browser_action": {
"default_icon": "iho.png",
"default_popup": "index.html"
},
"permissions": [
"activeTab", "<all_urls>"
],
"background": {
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["bundle.js"]
}
]
hello.js
var MainApp = React.createClass({
submitForm: function (e){
event.preventDefault();
function myCallback(){
alert("hi there")
}
window.setInterval(myCallback, 8000);
},
render: function () {
return (
<div>
<button onClick={this.submitForm}> click me! </button>
</div>
)
}
})
background.js
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript(null, {file: "bundle.js"});
});
Please [edit] the question to be on-topic: include a complete [mcve] that duplicates the problem. Including a manifest.json, some of the background/content/popup scripts/HTML. Questions seeking debugging help ("why isn't this code working?") must include: ►the desired behavior, ►a specific problem or error and ►the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: "How to create a [mcve]", What topics can I ask about here?, and [ask].
Why are you showing hello.js when it is not referenced anywhere? Where are bundle.js, and index.html? What is your exact problem? You appear to be using React, but don't load it. Why are you injecting bundle.js as a manifest.json content_scripts and using chrome.tabs.executeScript() to also inject it.?
Toolbar popup environment is destroyed when closed. 2. browserAction.onClicked won't work when popup html file is specified. 3. Make sure to read the extensions overview, especially the architecture article.
| common-pile/stackexchange_filtered |
Unhandeled exception Type 'String' is not a subtype of type 'int' of 'index'
I am getting unhandled exception in my code and my app is not working.
This is the only one error which I can find in the logs:
ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter (30126): #0 AssistantMethods.obtainPlaceDirectionDetails (package:driverapp/Assistant/assistantMethods.dart:63:41)
E/flutter (30126): <asynchronous suspension>
E/flutter (30126): #1 _NewRideScreenState.getPlaceDirection (package:driverapp/AllScreens/newRideScreen.dart:189:19)
E/flutter (30126): <asynchronous suspension>
E/flutter (30126): #2 _NewRideScreenState.build.<anonymous closure> (package:driverapp/AllScreens/newRideScreen.dart:70:15)
E/flutter (30126): <asynchronous suspension>
E/flutter (30126):
This is my assistantMethod.dart file code:
static Future<DirectionDetails> obtainPlaceDirectionDetails(LatLng initialPosition, LatLng finalPosition)async
{
String directionUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=${initialPosition.latitude},${initialPosition.longitude}&destination=${finalPosition.latitude},${finalPosition.longitude}&key=$mapKey";
var res = await RequestAssistant.getRequest(directionUrl);
if(res == "failed")
{
return null;
}
DirectionDetails directionDetails = DirectionDetails();
#1 error points out at this line
directionDetails.encodedPoints = res["routes"][0]["overview_polyline"]["points"];
directionDetails.distanceText = res["routes"][0]["legs"][0]["distance"]["text"];
directionDetails.distanceValue = res["routes"][0]["legs"][0]["distance"]["value"];
directionDetails.durationText = res["routes"][0]["legs"][0]["duration"]["text"];
directionDetails.durationValue = res["routes"][0]["legs"][0]["duration"]["value"];
return directionDetails;
}
#2 error points out this line
var details = await AssistantMethods.obtainPlaceDirectionDetails(pickUpLatLng, dropOffLatLng);
#3 error points out this line
await getPlaceDirection(currentLatLng, pickUpLatLng);
Please help me do this right.
I think this might be causing your error:
directionDetails.encodedPoints = res["routes"][0]["overview_polyline"]["points"];.
Please post the res json to take a look at it.I think there would be an index before points.
It seems that you have a List and your putting a KEY instead of a int (index) on the list, check your api response.
I checked your code and it works. My steps
0) Fetch JSON in browser
To fetch data we are using URL (with points from Google examples):
https://maps.googleapis.com/maps/api/directions/json
?origin=Disneyland
&destination=Universal+Studios+Hollywood
&key=<YOUR_KEY_HERE>
The response has such structure:
1) Fetch response as String
I use http library.
Future<String> fetchData() async {
String url = "https://maps.googleapis.com/maps/api/directions/json"
"?origin=Disneyland"
"&destination=Universal+Studios+Hollywood"
"&key=<YOUR_KEY_HERE>";
var client = http.Client();
var response = await client.get(Uri.parse(url));
String body = response.body;
return body;
}
2) Parse received data
Received data are just String. Base on documentation we know that's JSON format. So let's decode that:
String body = await fetchData();
var res = json.decode(body);
3) Find necessary fields
When you have JSON you can iterate it and get necessary data, for example:
var distanceText = res["routes"][0]["legs"][0]["distance"]["text"];
var distanceValue = res["routes"][0]["legs"][0]["distance"]["value"];
var durationText = res["routes"][0]["legs"][0]["duration"]["text"];
var durationValue = res["routes"][0]["legs"][0]["duration"]["value"];
var encodedPoints = res["routes"][0]["overview_polyline"]["points"];
and it works :)
My idea how to make it better
1) Fetch JSON in Flutter
I use http library.
Fetch data and return response as String:
Future<String> fetchData() async {
String url = "https://maps.googleapis.com/maps/api/directions/json"
"?origin=Disneyland"
"&destination=Universal+Studios+Hollywood"
"&key=<YOUR_KEY_HERE>";
var response = await Requests.get(url);
String body = response.content();
return body;
}
2) Convert received data in to models (classes)
The easiest way is to use quicktype.io which:
produces nice types and JSON (de)serializers for many programming languages. It can infer types from JSON but also takes types from JSON Schema, TypeScript, and GraphQL.
what you have to do is to:
paste JSON on the left, and code appears on the right.
So you will receive classes, for example:
class DirectionDetails {
DirectionDetails({
this.geocodedWaypoints,
this.routes,
this.status,
});
final List<GeocodedWaypoint> geocodedWaypoints;
final List<Route> routes;
final String status;
factory DirectionDetails.fromJson(Map<String, dynamic> json) => DirectionDetails(
geocodedWaypoints: json["geocoded_waypoints"] == null
? null
: List<GeocodedWaypoint>.from(json["geocoded_waypoints"].map((x) => GeocodedWaypoint.fromJson(x))),
routes: json["routes"] == null ? null : List<Route>.from(json["routes"].map((x) => Route.fromJson(x))),
status: json["status"] == null ? null : json["status"],
);
Map<String, dynamic> toJson() => {
"geocoded_waypoints":
geocodedWaypoints == null ? null : List<dynamic>.from(geocodedWaypoints.map((x) => x.toJson())),
"routes": routes == null ? null : List<dynamic>.from(routes.map((x) => x.toJson())),
"status": status == null ? null : status,
};
}
You will also receive methods allowing you to convert directly to and from json string:
DirectionDetails directionDetailsFromJson(String str) => DirectionDetails.fromJson(json.decode(str));
String directionDetailsToJson(DirectionDetails data) => json.encode(data.toJson());
So in your case you have to use directionDetailsFromJson to receive Flutter data structure.
3) Find necessary fields
When you have whole data structure you can find all of the data which you need, so:
List<Widget> parseData(DirectionDetails directionDetails) {
PolylinePoints polylinePoints = PolylinePoints();
return directionDetails.routes.map((route) {
var points = route.overviewPolyline.points;
List<PointLatLng> decodedPoints = polylinePoints.decodePolyline(points);
var distanceText = route.legs.map((leg) => leg.distance.text).join();
var distanceValue = route.legs.map((leg) => leg.distance.value).join();
var durationText = route.legs.map((leg) => leg.duration.text).join();
var durationValue = route.legs.map((leg) => leg.duration.value).join();
var stringPoints = decodedPoints.join("\n");
return Text(
"distanceText: $distanceText\n\n"
"distanceValue: $distanceValue\n\n"
"durationText: $durationText\n\n"
"durationValue: $durationValue\n\n"
"points:\n$stringPoints",
);
}).toList();
}
To decode PolylinePoints I use flutter_polyline_points library.
4) Result
5) Whole code
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Widget> items = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ElevatedButton(
child: Text("Fetch Data"),
onPressed: download,
),
Expanded(
child: ListView.separated(
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) => items[index],
separatorBuilder: (BuildContext context, int index) => Container(
height: 1,
color: Colors.grey,
),
itemCount: items.length,
),
)
],
),
),
);
}
void download() async {
String body = await fetchData();
DirectionDetails directionDetails = directionDetailsFromJson(body);
var routes = parseData(directionDetails);
setState(() {
items = routes;
});
}
Future<String> fetchData() async {
String url = "https://maps.googleapis.com/maps/api/directions/json"
"?origin=Disneyland"
"&destination=Universal+Studios+Hollywood"
"&key=<YOUR_KEY_HERE>";
var client = http.Client();
var response = await client.get(Uri.parse(url));
String body = response.body;
return body;
}
List<Widget> parseData(DirectionDetails directionDetails) {
PolylinePoints polylinePoints = PolylinePoints();
return directionDetails.routes.map((route) {
var points = route.overviewPolyline.points;
List<PointLatLng> decodedPoints = polylinePoints.decodePolyline(points);
var distanceText = route.legs.map((leg) => leg.distance.text).join();
var distanceValue = route.legs.map((leg) => leg.distance.value).join();
var durationText = route.legs.map((leg) => leg.duration.text).join();
var durationValue = route.legs.map((leg) => leg.duration.value).join();
var stringPoints = decodedPoints.join("\n");
return Text(
"distanceText: $distanceText\n\n"
"distanceValue: $distanceValue\n\n"
"durationText: $durationText\n\n"
"durationValue: $durationValue\n\n"
"points:\n$stringPoints",
);
}).toList();
}
}
| common-pile/stackexchange_filtered |
Django - guidance needed
I am developing a web-site using Django/Python. I am quite new to this technology and I want to do the web-site in a right way.
So here is my problem:
Imagine, that there is a Product entity and product view to display the Product info.
I use (product_view in my views.py ).
There is also Message entity and the Product might have multiple of them.
In Product view page ( I use "product_view" action in my views.py ) I also query for the messages and display them.
Now, there should be a form to submit a new message ( in product view page ).
Question #1: what action name should form have ( Django way, I do understand I might assign whatever action I want )?
Option #1: it might be the same action "product_view". In product_view logic I might check for the HTTP method ( get or post ) and handle form submit or just get request. But it feels a bit controversial for me to submit a message to the "product_view" action.
Option #2: create an action named "product_view_message_save". ( I don't want to create just "message_save", because there might be multiple ways to submit a message ). So I handle the logic there and then I make a redirect to product_view. Now the fun part is: if the form is invalid, I try to put this form to the session, make the redirect to the "product_view", get the form there and display an error near the message field. However, the form in Django is not serializable. I can find a workaround, but it just doesn't feel right again.
What would you say?
Any help/advice would be highly appreciated!
Best Regards,
Maksim
By "action" do you mean a "view function"? Are the "messages" something similar to having "comments" to an article or a product description page?
Yes. Users will leave a message like a comments to an article
You could use either option.
Option #1: In the post method (if using Class-based-views, otherwise check for "post" as the request type), just instantiate the form with MessageForm(request.POST), and then check the form's is_valid() method. If the form is valid, save the Message object and redirect back to the same view using HttpResponseRedirect within the if form.is_valid(): code block.
If you're checking for the related Messages objects in your template, the newly created message should be there.
Option #2: Very similar to Option #1, except if the form is not valid, re-render the same template that is used for the product_view with the non-valid form instance included in the template context.
The question is not in the code level ( I know how to create a form from the post request, how to validate it etc ).
The question is more in "approach" level or in "structure" level. As always in the programming, there are multiple ways to do it. Multiple workarounds to do it. The question is: what is considered the best practice in Django?
Option #1? Option #2? Or something other. It's not about the code.
By the way, as I described for Option #2, I would like to make a redirect after form submit and form is not serializable ( I've already found for a workaround how to serialize a form ), but this doesn't seem to be a good solution.
I'm not sure there is a "right way" that's recommended by the Django project, but in my opinion, if you only have one form that is performing a post on the Product page, it's easy enough to just keep it within the same view.
| common-pile/stackexchange_filtered |
How should I get the original comment while processing the reply
I'm working on a comments section for my template. And I need to do something like this:
Comment:
-This was my original comment
And this is my reply to the original comment.
So I wanna cite the original comment inside the comment that was a reply to the original comment. I var_dumped through everything that get_the_comment(); returns and failed to find any reference to the initial comment whatsoever.
Can you please assist me with that? Cheers!
The comment/reply ID is a value actually sent by the form. You are able to retrieve it via $_GET:
// Default is "no reply" eq. 0
$id = 0;
// Handle replies
if ( isset( $_GET['replytocom'] ) )
{
$id = filter_var(
$_GET['replytocom'],
FILTER_VALIDATE_INT,
# or:
# FILTER_SANITIZE_NUMBER_INT
array(
'options' => array(
'min_range' => 1,
),
# @link http://www.php.net/manual/en/filter.filters.flags.php
# 'flags' => '',
)
);
if ( FALSE === $id )
break;
$id = absint( $_GET['replytocom'] )
}
Then you have access to the reply-$id.
Hi thanks for the reply! You mean I should put it in the reply comment's <textarea> the original comment? Is this your solution?
@LoomyBear I don't know how you exactly set up your comments and the comment reply task. The answer just shows from where you can retrieve the ID.
sorry my bad! I've just carefully searched through the comments DB fields once again and found comment_parent field, which contains the reply ID. Thanks for the input though!
@LoomyBear Then please add this as separate answer. You might also want to edit your question and show a bit more of your setup. Thanks.
Ok my bad!
I've looked through what get_comments(); returns and I found comment_parent field which contains the ID of the initial comment. So in order to add cite of the comment you wanna reply to you need to do the following:
<?php
$pid = get_the_id();
$comments = get_comments('post_id='.$pid);
foreach ( $comments as $comment ) {
$cpid = $comment->comment_parent; // Getting the ID of the parent comment
$comment_parent = get_comment( $cpid );
// Do comment rendering here
...
}
?>
Sorry for bothering everyone. I hope this would help somebody in the future.
Cheers!
| common-pile/stackexchange_filtered |
Using SOQL aggregate functions
I have a table in salesforce that stores the topic selected by a person and a person may select the same topic multiple times. At a high level this how the data is stored.
{"Person1, "Topic1", "Person1", "Topic1", "Person1", "Topic2", "Person2", "Topic3", "Person2", "Topic1", "Person2", "Topic3"}
I want to write a SOQL query that returns the person and the most frequently selected topic. For the above example the results will be like this:
{"Person1", "Topic1", "Person2", "Topic3"}
I tried to use aggregate queries using MAX and Count but was not successful. Can any one tell me if its even possible with SOQL. Write now the only work around I am using is to dump this data in a map and looping through it to generate the desired output.
You can write SOQL like this:
Select Person , Topic, count(Topic) CNT from TABLE group by Person , Topic order by Person , Topic, CNT DESC
This will return all topic counts selected by each person order by CNT
Then you can apply logic to fetch top row (which has max count) for each person , for each topic.
| common-pile/stackexchange_filtered |
How can I dock a text area inside a div
I have a textarea inside a div.
What property should I set so that the textarea is docked to all sides of the div? In other words, how can the text area fill the space inside the div?
I started writing JavaScript but there must be a simpler option.
As you can see by the answers below, the thing is that it depends :) What context is this in? In general I think width/height: 100% works, but as pointed out below, not always. If you want to be absolutely sure that it works in your context, show us some more code.
You could set the css Style of the textarea to
height:100%;
width:100%
Would fail if the div's height is set to auto.
Try to do it with css:
div { width:400px; height:160px; border:#f00 3px solid; padding: 10px; }
textarea { width:100%; height:100%; }
Code: http://jsfiddle.net/kf2dt/
using CSS you may set the margin and padding to the div Set to 0, then for the css of of the
textarea set the height and width too 100%;
div { margin:0;padding:0px; }
textarea {height:100%;width:100%;}
and add overflow:hidden; to the the textarea css too hide the scrollbars if needed.
Again, would fail if the div's parent's height is set to auto.
Exactly why this wasn't an example of using auto height. :)
Try:
div textarea { position: absolute; top: 0; bottom: 0; right: 0; left: 0; }
div { position: relative; }
But as a general rule of thumb, if an element is the only element inside of a div, it's often not needed!
Here's a working example. The width and height are set for comfort reasons, but they are not necessary.
This isn't working properly for me at all. http://jsfiddle.net/BvKVY/1/ Firefox 9.0.1
I haven't tried in Firefox, but what are you seeing there? I'm seeing it properly.
http://i.imgur.com/IZSr2.png Works in Webkit for me, fails in IE9 as well as Firefox.
| common-pile/stackexchange_filtered |
Fibonacci string array revised
Maybe I misunderstand my assignment last time.The actually problem description should be like the following:
I have an array: A B AB BAB ABBAB BABABBAB
The number of each term of the array is base on the Fibonacci number.
Put the n-th string and the n+1-th string together, then producing the n+2-th string:
BABABBAB = BAB + ABBAB
Then is the x-th (eg.10^16-th) letter of the n-th term which count from the last letter is A or B? Eg. the 6th letter was B, not only in the 6th term BABABBAB but also in the later terms ABBABBABABBAB
The 7th letter is A in the the 6th term BABABBAB and also in the later terms - ABBABBABABBAB
The most inspiring news is that someone has a Θ(1) solution.
if [x / g] * g >= x - 1 then it's B
else it's A.
g is the golden mean.
but he or she didn't explain why it works.
I just thought that: if x > f(n) and x < f(n+1), that means x is among the f(n+1) and it's the x - f(n-1) in the f(n-2) then just going on until to the 1st or 2nd term.But the complexity will be Θ(n). The solution I added was so simple and perfect to solve the problem, but I can't figure out.
possible duplicate of Fibonacci string array
You should update your original question with the new information, rather than starting a new question on the same topic.
@Paul R: It's a different problem from the previous one,though they have same assumptions.
Can you post a link to where you got that from? I don't think it works. [6 / g] * g = 4.8, which is not at least 5. So you would say it's A when in fact it's B.
@IVlad @Paul R @Brian Roach Thanks for your attention! It's all my fault to misunderstand much information.I found the original problem. http://projecteuler.net/index.php?section=problems&id=230
Have a look at the Wikipedia article on Fibonacci Word. A formula for the n'th digit is given there along with references.
+1: The problem gives the reverse of Fibonacci words. Can prove using induction...
| common-pile/stackexchange_filtered |
Code design for reusable drag&drop UI parts in android
I am new to android and writing an learning app for children in primary school. The app is for practicing simple calculations (add and subtract).
So far, I have finished the UI design and written a simple proof-of-concept implementation to demonstrate the basic usage of the app.
The design for one of the activities (addition of 123 and 456) would look like this:
|-----------------------------|
| |c| 1 |c| 2 |c| 3 |
| |
| 4 5 6 |
| -------------------- |
| | r1 | | r2 | | r3 | |
| |
| |
| 1 | 2 | 3 | 4 | 5 |
| 6 | 7 | 8 | 9 | 0 |
| cancel | check |
|-----------------------------|
The numbers (0-9) in the numblock are views that can be drag&dropped to the carry fields (|c|) or the result fields (|r1| etc). Values already dropped to the carry or result fields also can be moved (again with drag&drop) to another carry or result field.
There are going to be multiple practice modes, e.g.:
|-----------------------------|
| 1 + 9 = |r1|r2| |
| 2 + 8 = |r1|r2| |
| 3 + 7 = |r1|r2| |
| 4 + 6 = |r1|r2| |
| 5 + 5 = |r1|r2| |
| |
| |
| 1 | 2 | 3 | 4 | 5 |
| 6 | 7 | 8 | 9 | 0 |
| cancel | check |
|-----------------------------|
or:
|-----------------------------|
| 1 2 3 4 5 |
| | | | | | |
| |+| |+| | |
| | | | |
| |r1| |r2| | |
| | | | |
| \ \ / |
| \ |-| |
| \ | |
| \ |r3| |
| \ / |
| \ / |
| |+| |
| | |
| |r4| |
| |
| |
| 1 | 2 | 3 | 4 | 5 |
| 6 | 7 | 8 | 9 | 0 |
| cancel | check |
|-----------------------------|
For my current implementation, I have all the drag&drop stuff in one activity and the layout is one single .xml file.
I would like to reuse the code for the drag&drop functionality in some way to keep the code clean and not have the same functionality implemented in many different activities.
I have already read about fragments in android and thought about making one fragment for the numblock and one fragment for each area where the numbers would be dropped, but as far as I researched, drag&drop between fragments is not really the way to go here (drag and drop between two fragments, the proposed solution does not seem to be very elegant).
Right now, I am thinking about just creating all content but the numblock dynamically in onCreate() of a single activity depending on the required mode. I would like your opinion on this approach. Are there probable issues when going that way?
Is there another way to achieve the same functionality and keep the code maintainable?
Have you suggestions on how I could design my code as simple and maintainable as possible?
How would you design an app with the required functionality?
The general advice that leaving design decisions until you have to make them would certainly apply here. I am sure there are hundreds of ways in which you could organise code like this.
In the Activity (or could be a Fragment) you so far have the following functionality:
Dragging and dropping numbers
Calculating if the answer is correct
Setting up the problem
Doing the things all activities must do - e.g. having an onCreate()
Can you split those different functionalities out somehow?
Are there things that are good candidates for making there own classes?
Draggable numbers?
Non draggable numbers?
Mathematical symbols?
Places you drag from and to?
Rows that form a calculation (which can be nested on top of each other)?
How will these elements communicate with each other?
To calculate if the answer is correct?
So that an element knows where it is?
How are you going to create a new instance of the Activity?
What data will you pass to the Activity?
Do you want to call one of a set number of different types?
How will what type the Activity loads be determined?
I haven't even begun to answer your question and yet this answer is getting very long.
The most important question is what do you want from the design? I'm guessing the answer is to make it as easy as possible to add new types of problem to the app.
Things that might help you:
You can add views programatically to a layout. You don't need to specify things in an xml file. This could simply be used for generating new numbers when you drag from the bottom or more complexly to define the entire setups programmatically.
I imagine interfaces and listeners will be the best way for elements to communicate.
It may be good to take a look at some patterns: Template Method, Static Factory Method or even Strategy could be helpful here.
Remember that you can split functionality out into separate Java files easily from Activities and then call them as needed.
It feels quite game like. I think it is 50/50 as to whether it might be worth spending time looking into if a game engine could help you.
Keep it simple - stick to splitting out one thing at a time. Work on one class at a time. I wouldn't try to make some huge, complex, intricate design all at once.
Thanks for your time and extensive answer. It certainly gave me some ideas on how to proceed.
Regarding some of your points:
Yes, the point of the design is making it easy for anyone else to understand and enable them to easily add new modes to the app. In general, the app should also be consistent to use, so the concept of dragging&dropping numbers from the numblock into the result fields should be the same for all implemented modes.
I think I am going to have a closer look on listeners... I might find just what I was looking for there...
| common-pile/stackexchange_filtered |
legend() not displaying datasets properly
I'm attempting to display 2 major datasets namely "Type2" (red squares) and "Type1" (blue circles) in the legend. Nevertheless, since my plot involves subgroups of "Type1" and "Type2" (A,B are subgroups of each), there are 4 items appearing in the legend. Please take a look at how my plots looks like:
The issue is legend() tends to display 4 items : red square, red square, blue circle, blue cricle, while I need solely two of them i.e. red square to represent Type2 and blue circle for Type1.
Type2 Mean2 SD2
A 4.1 1.9
A 5.7 0.9
A 7.5 1.2
B 6.9 0.7
B 4.9 0.4
B 8.5 1
Type1 Mean1 SD1
A 8.1 1
A 7.7 0.9
A 8.5 1.1
B 5.9 0.4
B 7.9 0.7
B 9.5 1.2
Figure1 = plt.figure('Scatter Plot', figsize=(6,6), dpi=300)
Subplot1 = Figure1.add_subplot(1,1,1)
markers = ['s','s']
colors = ['r', 'r']
grouped = DataFrame.groupby('Type2')
for i,((g,d),m,c) in enumerate(zip(grouped,markers,colors)):
x = np.random.normal(loc=i,scale=0.2,size=(len(d['Mean2'],)))
Subplot1.errorbar(x, y= Mean2 , yerr= SD2 ,
fmt=m,
markersize=5, color=c,
capsize=3, markeredgewidth=0.5
)
XPos = list(range(len(grouped)))
Subplot1.set_xticks(XPos)
Subplot1.set_xticklabels([a for a in grouped.groups])
Subplot1.set_xlim(-0.5,1.5)
###############################################
###############################################
markers = ['o','o']
colors = ['b', 'b']
grouped = DataFrame.groupby('Type1')
for i,((g,d),m,c) in enumerate(zip(grouped,markers,colors)):
x = np.random.normal(loc=i,scale=0.2,size=(len(d['Mean1'],)))
Subplot1.errorbar(x, y= Mean1, yerr= SD1,
fmt=m,
markersize=5, color=c,
capsize=3, markeredgewidth=0.5
)
###############################################
###############################################
Subplot1.legend(['Type2','not needed!', 'Type1','not needed!'])
Any comments will be highly appreciated. Many thanks!
Your code is not reproducible as written. For instance d['Mean1'] is not known.
Matplotlib will only add items to the legend that have a label affixed to them. You can use a ternary operation on the label assignment of the errorbar to only give a label to the first iteration over each groubby object.
Example:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df1 = pd.DataFrame({'Type1': ['A', 'A', 'A', 'B', 'B', 'B'],
'y_mean1': [8.1, 7.7, 8.5, 5.9, 7.9, 9.5],
'y_SD1': [1.0, 0.9, 1.1, 0.4, 0.7, 1.2]})
df2 = pd.DataFrame({'Type2': ['A', 'A', 'A', 'B', 'B', 'B'],
'y_mean2': [4.1, 5.7, 7.5, 6.9, 4.9, 8.5],
'y_SD2': [1.9, 0.9, 1.2, 0.7, 0.4, 1.0]})
df1['x'] = np.random.rand(6)
df2['x'] = np.random.rand(6)
fix, ax = plt.subplots(1,1)
for i, (glab, g) in enumerate(df1.groupby('Type1')):
h1 = ax.errorbar(g.x,
g.y_mean1,
g.y_SD1,
fmt='o',
c='b',
capsize=3,
markeredgewidth=0.4,
elinewidth=0.4,
# label is only assigned on the first iteration
label='Type1' if not i else None)
for i, (glab, g) in enumerate(df2.groupby('Type2')):
h2 = ax.errorbar(g.x,
g.y_mean2,
g.y_SD2,
fmt='s',
c='r',
capsize=3,
markeredgewidth=0.4,
elinewidth=0.4,
# label is only assigned on the first iteration
label='Type2' if not i else None)
ax.legend()
Thanks. Your plot doesn't look like the original one in that it's got rid of the subgroups A and B. If you could please tweak the original code to account for the new code line you added, i.e. label='Type1' if not i else None. I went ahead and added this line of code yet it doesn;t seem to be working the proper way. Adding this line doesnt alter anything.
I can't tweak your original code as it contains references to objects that you don't have defined.
Could ya be further precise. What is undefined here? Your answer is not applicable to my case.
In x = np.random.normal(loc=i,scale=0.2,size=(len(d['Mean2'],))), the variable d is not defined. In Subplot1.errorbar(x, y= Mean1, yerr= SD1, ..., neither Mean1 nore SD1 are defined in the code you have given.
Mean1 and Mean2 are simply the values of y axis for each set of data (you may check out data on top of the code). Also d is defined for each dataset in this line for i,((g,d),m,c) in enumerate(zip(grouped,markers,colors)):
| common-pile/stackexchange_filtered |
Can I use 'Deferred' XEPs, like "XEP-0142: Workgroup Queues"?
I want to implement the functionality same as defined in the XEP-0142 (Users to contact a representative of an organization or workgroup without knowing the address of a particular member of that organization or workgroup).
But in XEP-0142 site says "Implementation of the protocol described herein is not recommended". What are the consequences if we use the same?
I find the https://stackoverflow.com/questions/16837281/chat-application-with-queues-xep0142 on satckoverflow but there i could not find any solution for that one.
Please suggest me if i can use that one with out any problem or please suggest me any other alternatives to implement that functionality.
The consequence depends on your requirements. If you have control over the functionality of both your client and server then you do not have any problem with implementing this feature. If you do not, it could mean that either the client or the server will not have this functionality implemented.
The advise just states that XMPP does not support this implementation anymore, meaning that software vendors who develop XMPP based solutions may or may not have implemented this feature as described.
Thanks for the response Kay Tsar.
"The advice … states … not support this implementation anymore, … may or may not have implemented this feature as described". That is not what the advise states, nor what 'Deferred' means..
Your link states the following: "Implementation of the protocol described herein is not recommended." I am not a native speaker, so I might have confused advise with recommendation.
Openfire has reliable implementation of this XEP named fastpath. See fastpath plugin of openfire (and Spark) for more information.
So you can reuse Spark client or write your own to achieve needed functionality.
Most people are confused or warned by the current text a 'Deferred' XEP accompanies, which reads
WARNING: Consideration of this document has been Deferred by the XMPP
Standards Foundation. Implementation of the protocol described herein
is not recommended.
this should have been changed a long time ago to1,2
WARNING: This document has been automatically Deferred after 12
months of inactivity in its previous Experimental state.
Implementation of the protocol described herein is not recommended for
production systems. However, exploratory implementations are
encouraged to resume the standards process.
Which more precisely describes the situation a 'Deferred' XEP is in: It just hasn't been updated in more then 12 months. If someone would step up, and continue working on the that, which is something everyone can do, then it could back on the standards track:
Note that if a XEP is Deferred, the XMPP Extensions Editor may at some
point re-assign it to Experimental status
from XEP-0001 § 8.1 Standard Track XEPs.
XEP-0001 describes the process in detail.
1: http://logs.xmpp.org/council/2013-07-24/#15:12:32
2: http://mail.jabber.org/pipermail/council/2013-August/003748.html
| common-pile/stackexchange_filtered |
Padding schemes reversal and space efficiency
My crypto course proposes the following padding schemes:
$\operatorname{pad}(m) = m \mathbin\| 0^i$
$\operatorname{pad}(m) = m \mathbin\| 10^i$
$\operatorname{pad}(m) = m \mathbin\| 0^i \mathbin\| E(\left|m\right|)_l$
$\operatorname{pad}(m) = E(\left|m\right|)_l \mathbin\| m \mathbin\| 0^i$
where $E(\left|m\right|)_l$ is the $l$-bit encoding of the length of $m$ and $l$ is the size of the block in the scheme. The question is:
How can one reverse each padding?
Which padding is more space efficient?
I'm at risk of overthinking these questions. Thus, I ask for your experience. To me, the first the more space efficient but not always applicable. It can only be reverted under certain assumptions. But these assumptions hold for 3 and 4 also, if I'm not mistaken. For 2, I don't see very well the advantage. It may help sometimes but others (say 1 has to be written in the next block) it may force to introduce another block. So, overcomplicating matters one could do an average analysis of cases.
What are, in your opinion, the correct answers to these questions?
hints: 1) m=0 2) search for padding in wiki 3) think again 4) see 3.
The more space efficient but cannot always be reverted, for instance if one inputs $m = 1$.
The second space efficient but can always be reverted, this appears in Wikipedia entry as bit padding.
and 4. They consume the same space (which is greater than 1. and 2.) but also, they're always reversable.
| common-pile/stackexchange_filtered |
Accuracy of a multimeter over 10 years period
Datasheets of multimeters contain accuracy specifications.
One parameter is usually accuracy over period of 1 year. I understand that it means multimeter can be off by the specified value.
For example Keithley 2000 for 100mV range:
1 year accuracy = 0.005% (of reading) + 0.0035% (of range)
or Siglent SDM2055 for 200mV range:
1 year accuracy = 0.015% (of reading) + 0.004% (of range)
But question is what accuracy I have to consider over period of 10 years?
Do I have to multiply "1 year accuracy" by 10? Or it is not nearly that easy (and not that bad)?
No hobbyist is going to do calibration of his equipment every year. It would be useful to know how does the accuracy shift in longer period of time.
The manufacturer does not want to specify accuracy for a 10 years period, the necessary tests will take too much time.
Please improve the question by stating WHY exactly this question is useful. I was about to point out SE's general policy of asking questions about issues which you're actually experiencing, when I found your comment on an answer below which shows why you consider it a practical and not-hypothetical question.
@Beanluc I have added the reason why did I ask that question.
"No hobbyist is going to do calibration of his equipment every year". If you've bought expensive equipment then follow the manual. Otherwise all you earn is bragging rights. You can't pay once and have something sorted out forever, nothing in life works this way.
Generally that figure is defined because you are supposed to calibrate your equipment annually.
If you don't.. all bets are off.
You can not extrapolate from one to the other, plus aging will not be linear.
I know it's generally recommended to calibrate every year. But that was not the question.
@Chupacabras But you cant tell more than a year... it could be anything.. that's the point
Well, the key is here: how does the non-linearity of aging look like?
@Chupacabras hard to say if the manufacturer does not publish that information, which they likely don't since they expect people to calibrate. You have to remember those numbers are also worst case drift, the 0.005% they quote could be for a 10 year old meter.... who knows. Worse. some meters may start out drifting one way then after a few years flatten out then later in life go the other way.
Doesn't a DMM use a dual slope technique? an integrator converts an unknown voltage:reference voltage ratio to a ratio of time periods. This avoids errors in comparator offset, capacitor tolerances, integrator non-linearity - at the cost of slow conversions and the input can't vary during the reading time. You're really asking about the quality of the voltage reference and how it ages.
@Chupacabras It's not recommended to calibrate, it's required. Otherwise, the manufacturer takes no responsibility for the accuracy whatsoever. In programming we call it "undefined behavior". The very point of "undefined behavior" is that it cannot be defined nor predicted.
Do I have to multiply "1 year accuracy" by 10?
Well if you could use it without a calibration being needed it's not strictly the case of multiplying by ten because it's like compound interest that a bank might charge.
So if it drifts +1% per year, over ten years you get \$(1.01)^{10} - 1\$ = 10.46%.
Doesn't sound too bad and for tighter tolerances you can certainly approximate to multiplying by ten.
But you do need regular calibrations for this type of equipment, else what is the point of using it?
Well, hobbyist is not going to calibrate every year. Possibly never. That is the point of my question. Your calculation means you expect that aging is linear.
My answer only explains that the theoretical method is compounding rather than multiplying.
The simple legal answer is they owe you this accuracy for a year. It the meter fails this within a year you have a warranty claim. After a year (absent another specification) you are on your own. The extreme engineering approach would be for the manufacturer to require drift specs from every vendor and do an error analysis that supports the claim. You can guess as well as I whether they have done that. After a year they have not made a promise. Maybe there is a drift proportional to time^2 or a higher power so things go to pot shortly after one year. In an extreme theory even frequent calibration will not solve this problem.
Practically, shorting the leads together will detect offset errors. It won't help with gain errors. We might measure 1.456 volts on one point and 1.358 on another. Sometimes what we care about is that the first is higher than the second. In practice any time I got that from a meter I would count on the ordering of them, but I wouldn't count on the difference being 0.098 volts. Usually the first is the important fact, not the second. Relative values are much easier than absolute. If you need absolute, you need to be calibrating often and doing careful error analysis. Otherwise you need to develop the skills to understand what you know and what you don't. In practice a 10 year old meter is very useful, but you can't justify it from the specs.
Assume you bought the meter 10 years ago, or calibrated it 10 years ago, then you get a year of measurements within spec, or the meter is broken.
After 1 year and 1 day? The Manufacturer makes no claim. If you want to claim a spec and can support it, go ahead. But it's on you.
IF you measure the same thing with the same meter for 10 years, without re-calibrating, and then re-calibrate and measure again, then you've got a one-point study of long term drift. Don't forget to include the long term drift of whatever you're measuring. You could look at the data in the uncalibrated interval and draw conclusions about it. But that's your calibration, in the interval, not the manufacturer's calibration.
Re-calibrate the meter after 10 years, measurements will be within spec. for one year, again. Drift over the 10 year period isn't an issue. If you measure with a calibrated meter 10 years ago and measure with a calibrated meter, today, each measurement will be within spec and its LIKELY any difference in the measurements is less than the maximum allowed, in opposite directions. But the maximum allowed, in opposite direction, is the worst possible case.
IF you use a meter that was calibrated once, for 10 years, without re-calibrating, measuring various values, then you've got 9 years of data from an uncalibrated meter. It may be better than random numbers. To know how much better, you need to measure references to establish accuracy now, or re-calibrate and repeat prior measurements to characterize repeatability, allowing for source drift. Either way, accuracy in the uncalibrated interval on your shoulders.
The specifications quoted are really good. If you expect to realize that performance, you have to maintain calibration. If you want a hobbyist quick check, short the two inputs together. That better be 0.0000 volts, 0.0000 amps and 0.0000 ohms. Beyond that, you need a voltage reference, a current reference and a resistance reference. A low drift resistor is not an unreasonable thing for a lab, but why not just get the meter calibrated, or learn to calibrate it yourself, at that point? Before you start shopping for voltage and current standards that are 2-10 times better than the meter spec. They aren't cheap, and they have calibration requirements themselves!
Many (I would assume most or all) multimeters would display the probe resistance if you short the probes together, though, so a 0.0000 ohm reading isn't to be expected.
My experience is that they read 0.00, 0.000 or 0.0000, although the OP mentions instruments much nicer than I typically use. So I have to question "most or all". "Probe resistance" is real, but small, as is the microvolt EMF from dissimilar metals. But the $10 multimeter I keep in my desk drawer reads 00.0 on it's 200mV range, 000 on the 2V range, 0.00 on the 20V range, etc. I encourage you to test your assumption on actual hardware and report your results.
I was referring to resistance, not voltage. My multimeter shows 0.13-0.14 ohms unless you use the relative/null function, depending on how you hold the probe tips.
Well, I took my own good advice and discovered I was overgeneralizing too. My desk-drawer meter shows about 1.0 Ohm, and it bounces around a lot depending on how hard one presses the probe tips together. My $35 all singing and dancing meter is more stable and shows lower resistance, but not nothing.
| common-pile/stackexchange_filtered |
Finding a MST using a set of weights and building a tree using another set
I'm working with minimum spanning tre (MST) and I'm new using boost. My problem is that I want to generate a MST using one weight vector, and after that, reconstruct the tree using another vector.
Maybe I could explain better with a code:
using namespace boost;
typedef adjacency_list < vecS, vecS, undirectedS, property<vertex_distance_t, int>, property < edge_weight_t, int > > Graph;
typedef graph_traits < Graph >::edge_descriptor Edge;
typedef graph_traits < Graph >::vertex_descriptor Vertex;
typedef std::pair<int, int> E;
const int num_nodes = 5;
E edges[] = { E(0, 2), E(1, 3), E(1, 4), E(2, 1), E(2, 3),
E(3, 4), E(4, 0) };
int weights[] = { 1, 1, 2, 7, 3, 1, 1 };
int weights2[] = { -1, 1, -2, 7, 3, -1, -1 };
Graph g(edges, edges + sizeof(edges) / sizeof(E), weights, num_nodes);
property_map<Graph, edge_weight_t>::type weightmap = get(edge_weight, g);
std::vector < graph_traits < Graph >::vertex_descriptor > parentMap(num_vertices(g));
property_map<Graph, vertex_distance_t>::type distancemap = get(vertex_distance, g);
property_map<Graph, vertex_index_t>::type indexmap;
prim_minimum_spanning_tree (g, *vertices(g).first, &parentMap[0], distancemap, weightmap, indexmap, default_dijkstra_visitor());
for (std::size_t i = 0; i != parentMap.size(); ++i)
if (parentMap[i] != i)
std::cout << "parent[" << i << "] = " << parentMap[i] << std::endl;
else
std::cout << "parent[" << i << "] = no parent" << std::endl;
std::cout<<"Weights"<<std::endl;
for (std::size_t i = 0; i != parentMap.size(); ++i)
std::cout<<"weight["<<i<<"]: "<< distancemap(i) <<std::endl;
return EXIT_SUCCESS;
In the code above, I can generate the MST, and using the parentMap and the distanceMap I can have the weight of each edge of the tree.
But consider I want to use the vector weights to generate the MST, and use weights2 to get the edges values between the vertices, how could I do that?
| common-pile/stackexchange_filtered |
Semi-conjugacies between interval and circle maps
There are examples of self-maps of the circle which are semi-conjugate to self-maps of a compact interval. A famous one is the covering map $z\mapsto z^2$ of the unit circle which is semi-conjugate to the tent map, and also to the Chebyshev polynomial $[-1,1]\circlearrowleft:x\mapsto 2x^2-1$ via $z\mapsto x:=\frac{1}{2}\left(z+\frac{1}{z}\right)$. On the other hand, there is no semi-conjugacy between an irrational rotation and a continuous self-map of a compact interval because unlike the former, the latter must have a fixed point. So I ask the following: Is a continuous self-map of a circle possessing a fixed point always semi-conjugate to a continuous self-map of an interval? By definition, a semi-conjugacy needs to be surjective, continuous and respecting the dynamics. Here, I allow it to be in either direction but I want its fibers to be finite though.
In general, the answer is no. The reason why $z^2$ and Chebyshev polynomial have this property is that they are even. But $z^3$ already does not have this property.
@AlexandreEremenko The covering $z\mapsto z^3$ is also semi-conjugate to an interval map: $z\mapsto x:=\frac{1}{2}\left(z+\frac{1}{z}\right)$ still works as a semi-conjugacy from the circle map onto the Chebyshev polynomial $x\mapsto 4x^3-3x$.
this is a semiconjugation in another direction. There is no semicongugation FROM the segment TO the circle. Semiconjugation is not an equivalence relation, as the name suggests. But it is easy to find an example which has no semiconjugation either way.
@AlexandreEremenko I have mentioned in my question that I allow semi-conjugacies in both directions.
| common-pile/stackexchange_filtered |
Declaring the field of a class without prefixing it with the class
private static final Color DEFAULT_PEN_COLOR = BLACK;
private static final Color DEFAULT_CLEAR_COLOR = WHITE;
This is a part of my code thats is having an error that says that the symbols BLACK and WHITE cannot be identified, even when I put import java.awt.Color. What do I need to do?
Use Color.BLACK and Color.WHITE instead.
Color.BLACK and Color.WHITE
You have to use static imports if you don't want to prefix the Color class :
import static java.awt.Color.*;
or else you have to prefix the fields with Color:
Color.BLACK
Color.WHITE
I believe you need to import either both colors explicitly or use wildcard on your import import static java.awt.Color.BLACK or import static java.awt.Color.*
@Samuel Indeed thank you.It is not required only when the import specifies a variable and Color is indeed not a variable.
| common-pile/stackexchange_filtered |
How can I capture iSight frames with Python in Snow Leopard?
I have the following PyObjC script:
from Foundation import NSObject
import QTKit
error = None
capture_session = QTKit.QTCaptureSession.alloc().init()
print 'capture_session', capture_session
device = QTKit.QTCaptureDevice.defaultInputDeviceWithMediaType_(QTKit.QTMediaTypeVideo)
print 'device', device, type(device)
success = device.open_(error)
print 'device open success', success, error
if not success:
raise Exception(error)
capture_device_input = QTKit.QTCaptureDeviceInput.alloc().initWithDevice_(device)
print 'capture_device_input', capture_device_input, capture_device_input.device()
success = capture_session.addInput_error_(capture_device_input, error)
print 'session add input success', success, error
if not success:
raise Exception(error)
capture_decompressed_video_output = QTKit.QTCaptureDecompressedVideoOutput.alloc().init()
print 'capture_decompressed_video_output', capture_decompressed_video_output
class Delegate(NSObject):
def captureOutput_didOutputVideoFrame_withSampleBuffer_fromConnection_(self, captureOutput, videoFrame, sampleBuffer, connection):
print videoFrame, sampleBuffer, connection
delegate = Delegate.alloc().init()
print 'delegate', delegate
capture_decompressed_video_output.setDelegate_(delegate)
print 'output delegate:', capture_decompressed_video_output.delegate()
success = capture_session.addOutput_error_(capture_decompressed_video_output, error)
print 'capture session add output success', success, error
if not success:
raise Exception(error)
print 'about to run session', capture_session, 'with inputs', capture_session.inputs(), 'and outputs', capture_session.outputs()
capture_session.startRunning()
print 'capture session is running?', capture_session.isRunning()
import time
time.sleep(10)
The program reports no errors, but iSight's green light is never activated and the delegate's frame capture callback is never called. Here's the output I get:
$ python prueba.py
capture_session <QTCaptureSession: 0x1006c16f0>
device Built-in iSight <objective-c class QTCaptureDALDevice at 0x7fff70366aa8>
device open success (True, None) None
capture_device_input <QTCaptureDeviceInput: 0x1002ae010> Built-in iSight
session add input success (True, None) None
capture_decompressed_video_output <QTCaptureDecompressedVideoOutput: 0x104239f10>
delegate <Delegate: 0x10423af50>
output delegate: <Delegate: 0x10423af50>
capture session add output success (True, None) None
about to run session <QTCaptureSession: 0x1006c16f0> with inputs (
"<QTCaptureDeviceInput: 0x1002ae010>"
) and outputs (
"<QTCaptureDecompressedVideoOutput: 0x104239f10>"
)
capture session is running? True
PS: Please don't answer I should try PySight, I have but it won't work because Xcode can't compile CocoaSequenceGrabber in 64bit.
Your problem here is that you don't have an event loop. If you want to do this as a standalone script, you'll have to figure out how to create one. The PyObjC XCode templates automatically set that up for you with:
from PyObjCTools import AppHelper
AppHelper.runEventLoop()
Trying to insert that at the top of your script, however, shows that something inside AppHelper (probably NSApplicationMain) expects a plist file to extract the main class from. You can get that by creating a setup.py file and using py2app, something like this example from a PyObjc talk:
from distutils.core import setup
import py2app
plist = dict(
NSPrincipalClass='SillyBalls',
)
setup(
plugin=['SillyBalls.py'],
data_files=['English.lproj'],
options=dict(py2app=dict(
extension='.saver',
plist=plist,
)),
)
@Dan: Thanks for the pointer! It's my first experience with Mac OS X programming and I was absolutely clueless. I got it to work invoking AppHelper.runConsoleEventLoop() instead at the end of the script, no need for Plist. Now my problem is that it takes over the main thread and never returns. I was hoping to wrap it nicely in a module in a non-intrusive way.
You could spawn off a thread and handle it within the thread, probably. QT is not threadsafe, but in this context all it means is you have to do all of your QT stuff in one thread, which is not necessarily the main thread. You might also look into timers, but I think you probably still need a main loop for that.
Apparently, it has to be the main thread. If I do Thread(target=AppHelper.runConsoleEventLoop).start() instead, I get a bunch of errors and nothing works:
2009-10-20 12:58:32.075 Python[2054:4903] *** __NSAutoreleaseNoPool(): Object 0x1018065b0 of class NSCFString autoreleased with no pool in place - just leaking 2009-10-20 12:58:32.078 Python[2054:4903] *** __NSAutoreleaseNoPool(): Object 0x101821130 of class NSCFString autoreleased with no pool in place - just leaking 2009-10-20 12:58:32.078 Python[2054:4903] *** __NSAutoreleaseNoPool(): Object 0x101828df0 of class NSCFString autorelease
You should give a try to motmot's camiface library from Andrew Straw. It also works with firewire cameras, but it works also with the isight, which is what you are looking for.
From the tutorial:
import motmot.cam_iface.cam_iface_ctypes as cam_iface
import numpy as np
mode_num = 0
device_num = 0
num_buffers = 32
cam = cam_iface.Camera(device_num,num_buffers,mode_num)
cam.start_camera()
frame = np.asarray(cam.grab_next_frame_blocking())
print 'grabbed frame with shape %s'%(frame.shape,)
you can see some simple examples on http://www.incm.cnrs-mrs.fr/LaurentPerrinet/SimpleCellDemo
is there any way to directly record to a file through this library?
motmot and camiface are great but I wanted a low-dependency solution, specially to directly record video. So created this: https://github.com/dashesy/pyavfcam using AVFoundation for direct video and image capturing and recording to file.
| common-pile/stackexchange_filtered |
Sort table in Angular component
I have two Angular components, one is the whole page which loads another component which is just a table.
The table is loaded through
<app-detections-table [dataSource]="dataSource"></app-detections-table>
in detections.component.html.
In detections-table.component.html I've added
<table
mat-table
[dataSource]="dataSource"
#sort
matSort="sort"
>
and <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th> to each of the column headers.
In detections-table.component.ts I added
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
Now, I get the sorting arrows on the table, but nothing happens when I click them.
If I remove passing in the dataSource from detections.component.html to the table component and just use a JSON objec in the table component then it works as expected, so I assume that sorting in detections-table.component.ts is "too late", which is why I tried adding this.dataSource.sort = this.sort to the end of ngOnInit() in detections.component.ts, but that also didn't do anything.
Anybody got a tip? Thanks!
I've had a similar problem with mat-table and i solved it by using a setter on the @Input and load the table properties in a separate function.
tableData = new MatTableDataSource([]);
@Input() set dataSource(value: any[]) {
if(value) {
this.loadTable(value);
}
}
And for the loadTable you could do something like this:
loadTable(data: any[]) {
this.tableData = new MatTableDataSource(data);
this.tableData.sort = this.sort;
}
In this example the "tableData" variable becomes the datasource that you use for the table so this:
<table
mat-table
[dataSource]="dataSource"
#sort
matSort="sort"
>
Would become this:
<table
mat-table
[dataSource]="tableData"
#sort
matSort="sort"
>
Hopefully this solves your issue!
| common-pile/stackexchange_filtered |
How would you play this hand?
No Limit Hold'em
7 players at the table, I am SB with around 10 BB in my stack
Average stack is around 15-20 BB
One person in middle position calls the BB, everyone else folds
Back to me - I have AQ offsuit, and raise to 2.5 BB. I have been either raising to 2-3 BB or folding pre-flop for most of the game so far.
BB is a new player at the table and seems fairly loose overall
He goes all in with about 15 BB - I follow and go all in. Player in middle position folds.
BB has JQ offsuit. He catches a J on the turn and wins the hand with the pair of Jacks.
Thinking about this hand now, I think I should have probably gone all in immediately instead of raising to 2.5 BB, the BB probably thinking I was trying to steal. Would he have called my all in with JQ offsuit?
How would you have played this hand?
Is this a tournament or a cash game situation?
It is a tournament
In case you go all in, he might fold and you wont get money out of that hand. With just 1 player behind and the limper an AQ ist most probably the best hand. You didn't do a mistake here. I mean, a good player will understand that if you already put 25% of your stack in, there is no way that you will fold anyway. So a 2,5bb raise looks super strong already
Sometimes, you're just going to get 3-outered.
In this situation, the pot is already approaching 25% of your stack (more if antes are in play), so I'd have been inclined to simply shove the AQo.
The line you chose probably would work better with a balanced range consisting of your stronger hands (say QQ+, AKs) and a corresponding set of the weakest hands drawn from the fringes of your raising range for balance.
Now, in the later stages of a tournament, there are ICM considerations which might affect your reasoning; e.g., the UTG player is a microstack about to be blinded all in on the next hand, and the MP is some uber-LAG who has just limped for the very first time ever. But, in general, I tend to lean to the more aggressive line -- put your opponents to the test.
I wouldn't waste too much time wondering about what might have happened had you followed a different line. You made a reasonable choice for the game situation that you faced -- after that, variance happens. Focus on making the best decisions you can, and the rest will take care of itself in the long run.
I think the your raise was too small. Under 10BB you should better go all in, then there would be a chance that BB folds. If you played tight and go all in, the guy will probably put your on a premium hand or pocket and fold. But your small raise didn't show strength, it looked like you wanted to see the flop. The BB-guy made a good move pushing all in, as the middle player just limped (not strong) and you raised too little: 2,5 BBs were already in pot, so you just made it more attractive by putting 2 more blinds in the pot.
It was of course bad luck that you lost with a better hand, but this happens way too often in poker :)
| common-pile/stackexchange_filtered |
What tool can I use to transcode my videos to Webm?
What tools can I use to transcode my videos to Webm?
Have you looked at the official site for the WebM project?
http://www.webmproject.org/
| common-pile/stackexchange_filtered |
Unable to extract fields form log line containing a mix of JSON and non-JSON data using grok in Logstash
I am running a couple of Spring Boot applications in Docker containers. Since I don't want to log to files, I am instead logging to the console and then using logspout to forward the logs to Logstash. I am using logstash-logback-encoder to log all logs from the application in JSON format.
Apart from these, there are also some logs (console outputs) which are made by the docker container before starting the Spring Boot application. These are not in JSON format.
To both of these, Logspout appends metadata (container name, container id, etc) before sending to Logstash. Below are my example logs in both formats.
Direct from container (no JSON)
<14>1 2016-12-01T12:58:20Z 903c18d47759 com-test-myapp 31635
- - Setting active profile to test
Application logs (in JSON format)
<14>1 2016-12-01T13:08:13Z 903c18d47759 com-test-myapp 31635
- - {"@timestamp":"2016-12-01T13:08:13.651+00:00","@version":1,"message":"Some
log message goes
here","logger_name":"com.test.myapp.MyClass","thread_name":"http-nio-8080-exec-1","level":"DEBUG","level_value":10000,"HOSTNAME":"903c18d47759"}
Below is my Logstash grok configuration.
input {
tcp {
port => 5000
type => "logspout-syslog-tcp"
}
}
filter {
if [type] == "logspout-syslog-tcp" {
grok {
match => {
"message" => [
"<%{NUMBER:syslogPriority}>1 %{TIMESTAMP_ISO8601:eventTimestamp} %{BASE16NUM:containerId} %{DATA:containerName} %{NUMBER:containerPort} - - %{DATA:jsonLog}",
"<%{NUMBER:syslogPriority}>1 %{TIMESTAMP_ISO8601:eventTimestamp} %{BASE16NUM:containerId} %{DATA:containerName} %{NUMBER:containerPort} - - %{DATA:regularLog}"
]
}
}
json {
source => "jsonLog"
target => "parsedJson"
remove_field=>["jsonLog"]
}
mutate {
add_field => {
"level" => "%{[parsedJson][level]}"
"thread" => "%{[parsedJson][thread_name]}"
"logger" => "%{[parsedJson][logger_name]}"
"message" => ["%{[parsedJson][message]}"]
}
}
}
}
output {
elasticsearch { hosts => ["localhost:9200"] }
stdout { codec => rubydebug }
}
Based on this, I was hoping to have each field in JSON available as a filter in Elasticsearch/Kibana. But I am not able to get the value of those fields. It shows up in Kibana as below:
I am not sure what I am missing here. How should I go about extracting the fields from JSON? Also, is the grok filter correct for handling both JSON and non-JSON logs?
Thanks,
Anoop
The problem is with the %{DATA:jsonLog} part. The DATA pattern, .*?, is not greedy (see here), so it won't grab anything and won't create the jsonLog field. You'll need to use the GREEDYDATA pattern instead.
See http://grokconstructor.appspot.com/do/match#result to test your patterns.
Thanks @baudsp for the response. That was indeed the issue.
I am now able to parse the fields within the JSON. But, the same pattern matches for both JSON and non-JSON type. Next step is for me to figure out how to distinguish them. Thanks for your help.
@Anoop Glad I could help.
Managed to get it fixed. I used the a single grok match which creates a single field. Then I use the same field to parse the JSON.. Below are the relevant pieces of configuration.
`grok {
match => {
"message" => [
"<%{NUMBER:syslogPriority}>1 %{TIMESTAMP_ISO8601:eventTimestamp} %{BASE16NUM:containerId} %{DATA:containerName} %{NUMBER:containerPort} - - %{GREEDYDATA:log}",
]
}
}
json {
source => "log"
target => "parsedJson"
}
if [parsedJson] {
// Put code to parse fields from JSON
}
`
| common-pile/stackexchange_filtered |
Learning about Power Spectral Density
I am sorry to ask a basic question. I am new in signal processing and want to know about the difference between PSD and fft.
I have a audio signal. Which I convert into PSD by using pwelch in matlab. But, when I plot this signal, I want to see the frequency (hz) in x axis and energy (db) in y axis.
But, it doesn't show like this way.
Can anybody explain me the relationship between PSD and FFT and also please let me know, how to plot these two things.
Thanks
To put things simply (for the first pass), the FFT is an algorithm that implements the Discrete Fourier Transform (DFT). The DFT takes N points of the input signal and performs a fourier transform. Power spectrum of the signal is got after you plot the square of the magnitude of the FFT output.
So, the DFT takes N points as input and spits out N points as the output. If you think of the signal as a frame of N samples, the DFT finds statistics using only one frame (N points).
However, the pwelch method is an average statistic over multiple frames. The signal can be a very long signal of length (say L) where its length is many times greater than N. The pwelch method starts off by calculating the DFT of the first N samples, then moves ahead to look at the next N samples and so on until all the "frames" have been looked at. So, what you are left with is the DFTs of every frame of sample size N of the signal of length N. Say, N is 256 points and the L is 44100 points.
Therefore, pwelch takes L points (L > N) and spits out N points for each "frame" of length N of a signal of length L.
There are more details involving windowing and whether you want consecutive frames to have some samples that overlap with each other and so on.
I hope this helps as a first pass explanation.
| common-pile/stackexchange_filtered |
How to get bitbucket webhook payload data in AWS Codebuild
Bitbucket sends a payload in the webhook . AWS Codebuild allows to use some of the data passed within the payload but not all of them.
I am interested in the pull request ID and the pull request state (Open/Merged/Decline).
After looking at the documentation I did not find a way to identify which pull request triggered the AWS codebuild pipeline. If at least I got the pull request ID, I could use it to make an API call to Bitbucket to get the data I want. Does anyone know how to identify the pull request that started the AWS Codebuild pipeline?
| common-pile/stackexchange_filtered |
React Tailwindcss dropdown doesn't open. Click on the dropdown button but dropdown dont open
I'm tryinng to use react tailwind css navbar. Everything is all right but dropdown is not working. I clicked on the icon but never open dropdown. I can't found the problem. Please help me out to finding whats the wrong in my code. I'm using typescript in my project.Please Tell me Whats going on in my code.
Menu Code
<Menu as="div" className="relative ml-3">
<div>
<Menu.Button className="flex rounded-full bg-gray-800 text-sm focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-gray-800">
<span className="sr-only">Open user menu</span>
<img
className="h-8 w-8 rounded-full"
src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80"
alt=""
/>
</Menu.Button>
</div>
<Transition
as={Fragment}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<Menu.Items className="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
<Menu.Item>
{({ active }) => (
<a
href="#"
className={classNames(
active ? "bg-gray-100" : "",
"block px-4 py-2 text-sm text-gray-700"
)}
>
Your Profile
</a>
)}
</Menu.Item>
</Menu.Items>
</Transition>
</Menu>
My Package.json
{
"name": "e-shop",
"version": "0.1.0",
"private": true,
"dependencies": {
"@headlessui/react": "^0.0.0-dev.0ce63d8",
"@heroicons/react": "^2.0.16",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^13.0.0",
"@testing-library/user-event": "^13.2.1",
"@types/jest": "^27.0.1",
"@types/node": "^16.7.13",
"@types/react": "^18.0.0",
"@types/react-dom": "^18.0.0",
"@types/react-router-dom": "^5.3.3",
"flowbite": "^1.6.3",
"flowbite-react": "^0.3.8",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.8.1",
"react-scripts": "5.0.1",
"typescript": "^4.4.2",
"web-vitals": "^2.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"tailwindcss": "^3.2.7"
}
}
tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"node_modules/flowbite-react/**/*.{js,jsx,ts,tsx}",
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [require("flowbite/plugin")],
include: ["src/**/*.ts*"],
};
https://codesandbox.io/s/headless-ui-forked-vmy8qd?file=/src/App.js
Strange its working here
but in my computer it is not work
| common-pile/stackexchange_filtered |
swift 2: Sprite tilting effect
Looking for a method to tilt a sprite upwards on the right side when tapping the screen (like in flappy bird) Like a start of a rotation that returns to the place it were. I will use this as an effect of going faster then the sprite normally does.
I'll add the code I got so far below:
var player = SKSpriteNode()
override func didMoveToView(view: SKView) {
let playerTexture = SKTexture(imageNamed: "player")
player = SKSpriteNode(texture: playerTexture)
player.position = CGPoint(x: 200, y: 80)
player.physicsBody = SKPhysicsBody(texture: playerTexture, size: playerTexture.size())
player.physicsBody!.affectedByGravity = true
self.addChild(player)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
What do you mean by "Like a start of a rotation that returns to the place it were."?
I mean it begins lifting updwards on the right side. The rotation was a bad explanation
Maybe an SKAction that adjusts the zRotation of the sprite?
| common-pile/stackexchange_filtered |
.net 3.5 modify DataSet query at runtime
I'm sure something like this has been asked before, but I can't seem to find exactly what I need. Say I added a DataSet component to my VS 2010 .NET 3.5 project - it's executing and filling up alright and is very easy to use.
But what if i wanted to make small modifications to its query at runtime (basing on various user input)?
I know i could do this with Parameters, but what if the modifications to the query have more structural character, - like omitting parameters etc.?
In the generated code i see that it exposes CommandCollection property, but it's protected, therefore I can't use it from outside of the dataset - unless :) i make a dummy class that inherits from the generated adapter object and publicly exposes CommandCollection property by force (that's just what I did) - but isn't it a bit awkward?
Do you know of a better technique?
(i am then creating a new OracleCommand basing on my modified query and then assigning it to my adapter's SelectCommand property)
so since nobody answered, I post the workaround I used here (inherited class). Foreword: when you drag a DataSet class from VS 2010 toolbox to your Form (e.g. MainForm) in Design view, three things are generated :
a DataSet (contains table & data instances)
a DataAdapter (describes how to fill the above dataset)
a BindingSource (binds the above DataSet to controls on Form)
The definition of the above generated classes, along with the required queries etc. is ultimately stored in an XSD file, and during each build the code for these classes is generated from the XSD.
// MyTableAdapter is a VS2010 AUTOGENERATED class
// (generated during DataSet wizard)
// thankfully, MyTableAdapter exposes protected CommandCollection attribute
class MyAdapter : MyTableAdapter
{
public System.Data.OracleClient.OracleCommand[] Commands
{
get { return CommandCollection; }
}
}
class MainForm : Form
{
private void btnQuery_Click(object sender, EventArgs e)
{
// create new OracleCommand to substitute the SelectCommand in autogenerated adapter
using (OracleCommand cmd = new OracleCommand())
{
MyAdapter m = new MyAdapter(); // dummy instance used just to retrieve saved query
if (m.Commands.Length > 0)
{
cmd.Connection = mainDbConnection;
cmd.CommandText = m.Commands[0].CommandText.Replace('someText', 'someOtherText'); // do whatever changes to the query
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(...); // optionally, if needed
//myTableAdapter is a Designer generated instance of MyTableAdapter
//but I can substitute its SelectCommand with something else
myTableAdapter.Adapter.SelectCommand = cmd;
myTableAdapter.Adapter.Fill(this.myDataSet.MyTable);
}
}
}
}
| common-pile/stackexchange_filtered |
Linux how to convert time format to epoch time?
I have the following time format: 2019-03-08T17:35:44Z
How can I convert that, using nothing but Linux commands, to epoch time?
Use:
date -d "2019-03-08T17:35:44Z" +%s
1552066544
To get the current epoch time:
date +%s
1552085639
Please abstain from answering obvious duplicate questions. Thanks.
| common-pile/stackexchange_filtered |
Does replacing statements by expressions using the C++ comma operator could allow more compiler optimizations?
The C++ comma operator is used to chain individual expressions, yielding the value of the last executed expression as the result.
For example the skeleton code (6 statements, 6 expressions):
step1;
step2;
if (condition)
step3;
return step4;
else
return step5;
May be rewritten to: (1 statement, 6 expressions)
return step1,
step2,
condition?
step3, step4 :
step5;
I noticed that it is not possible to perform step-by-step debugging of such code, as the expression chain seems to be executed as a whole. Does it means that the compiler is able to perform special optimizations which are not possible with the traditional statement approach (specially if the steps are const or inline)?
Note: I'm not talking about the coding style merit of that way of expressing sequence of expressions! Just about the possible optimisations allowed by replacing statements by expressions.
Why not check the generated assembler code and post it here?
I have checked the generated assembler code (VS2005), and it is the same (Debug & Release), with one minor exception though: the number of registers used is greater with the comma version.
I would be curious to test this on GCC.
Most compilers will break your code down into "basic blocks", which are stretches of code with no jumps/branches in or out. Optimisations will be performed on a graph of these blocks: that graph captures all the control flow in the function. The basic blocks are equivalent in your two versions of the code, so I doubt that you'd get different optimisations. That the basic blocks are the same isn't entirely obvious: it relies on the fact that the control flow between the steps is the same in both cases, and so are the sequence points. The most plausible difference is that you might find in the second case there is only one block including a "return", and in the first case there are two. The blocks are still equivalent, since the optimiser can replace two blocks that "do the same thing" with one block that is jumped to from two different places. That's a very common optimisation.
It's possible, of course, that a particular compiler doesn't ignore or eliminate the differences between your two functions when optimising. But there's really no way of saying whether any differences would make the result faster or slower, without examining what that compiler is doing. In short there's no difference between the possible optimisations, but it doesn't necessarily follow that there's no difference between the actual optimisations.
The reason you can't single-step your second version of the code is just down to how the debugger works, not the compiler. Single-step usually means, "run to the next statement", so if you break your code into multiple statements, you can more easily debug each one. Otherwise, if your debugger has an assembly view, then in the second case you could switch to that and single-step the assembly, allowing you to see how it progresses. Or if any of your steps involve function calls, then you may be able to "do the hokey-cokey", by repeatedly doing "step in, step out" of the functions, and separate them that way.
Using the comma operator neither promotes nor hinders optimization in any circumstances I'm aware of, because the C++ standard guarantee is only that evaluation will be in left-to-right order, not that statement execution necessarily will be. (This is the same guarantee you get with statement line order.)
What it is likely to do, though, is turn your code into a confusing mess, since many programmers are unaware that the comma-as-operator even exists, and are apt to confuse it with commas used as parameter separators. (Want to really make your code unreadable? Call a function like my_func((++i, y), x).)
The "best" use of the comma operator I've seen is to work with multiple variables in the iteration statement of a for loop:
for (int i = 0, j = 0;
i < 10 && j < 12;
i += j, ++j) // each time through the loop we're tinkering with BOTH i and j
{
}
Very unlikely IMHO. The thing get's compiled down to assembler/machine code, then further low-level optimizations are done, so it probably turns out to the same thing.
OTOH, if the comma operator is overloaded, the game changes completely. But I'm sure you know that. ;)
The obligatory list:
Don't worry about rewriting almost equivalent code to gain performance
If you have a perf-problem, profile to see what the problem is
If you can't get it faster by algorithmic ops, look at the disassembly and see that the compiler does what you intended
If not, ask here and post source and disassembly for both versions. :)
| common-pile/stackexchange_filtered |
How to easily keep track of similar looking wires
So my irrigation system has 4 cables which each contain 6 bundled wires. To make things worse, the 6 bundled wires are the same color between the four cables (red, green, blue, yellow, white, black) and all have the same sheathing color. I'm going to be replacing and relocating the controller, but in the interim due to the way the wiring is routed, I will need to disconnect and re route all wires, so it will be very difficult to keep which one is which straight.
I could individually label each one, but this sounds like a massive pain -- and possibly not reliable because no matter how I attach the labels, it's highly probable at least one would slip off the wire as it is being pulled through interstitial space in the walls.
I could just "test" each wire when it's done. I know in each bundle the colored wires go to sprinkler heads while the white is the common wire, but this sounds like a pain in the butt.
Does anyone have a good way to keep track of these wires?
Very resilient labelling: Some offcuts of thin heatshrink tubing, shrunk on tight. In different color, width or number. If whatever you are pulling the cables through can rip that off, it is also a threat to your wiring insulation.
If you can designate each bundle 1, 2, 3 and 4, and record the connection of each color per bundle, then all you really need to do is mark each bundle, right? If it's light colored sheathing, giving the end of each one a corresponding number of rings with a permanent marker should survive a trip through walls, conduit, etc. If not light colored, you could snip a corresponding number of small notches into the end of each sheathing.
Label each bundle when you disconnect them. Then pull them through the conduit one at a time; if you lose a label, you can replace it right then, while the other three wires are known quantities.
For the individual colored wires, you might try a "telco" crimp connector. These are made for indoor telephone wire, likely similar to the low-voltage, low-current wiring in your control bundles. Each crimp can be used to attach a short loop of wire that runs through a tag of some sort (even buttons, if you have a button jar you almost certainly have 24 distinct buttons to use as tags). Even better, they don't require special tools to attach; just put the wires in the holes and squeeze the crimp with plain pliers. You can clip and restrip the wires when you're done needing the labels, of course.
Good things, I would add giving the bundles of wires a colour coding with a bit of coloured string in addition to the other marker/s. You can often feed the coloured string through the bundel of wires, but if not, tie it around the bundels in different spots.
You could take a picture of the current state of the attached wires. That would let you record which color of which wire goes to which connector. (I can't fully visualize your setup or issue, so this might not work for your situation. But for the situation I am picturing, it works great!)
Why do you need at all to label the bundles? It is very easy to differentiate them after stretching all the wires.
At one end of the cables, short circuit the red and a given color from the same bundle. On each of the other ends test which color is short circuited with the red wire, and you'll know exactly which cable that is. (You state that you have 4 cables, and with short circuiting the red wire you could recognize 5 cables. By carefully selecting which color to short circuit you could extend this system to match a lot of cables)
Know you can properly label the cable for future use or historical reference.
| common-pile/stackexchange_filtered |
Service methods not working in android
I just created a service as shown below :
package com.example.timepass;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class alarm extends Service{
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Entered in service", Toast.LENGTH_SHORT).show();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
return 1;
// Log.i("YourService", "Yes this works.");
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Changed", Toast.LENGTH_SHORT).show();
return null;
}
}
Now when I startservice from mainactivity by the following command:
Intent myIntent = new Intent("com.example.timepass.ALARM");
MainActivity.this.startService(myIntent);
By doing this there is no error, but no TOAST of Service class are dipslayed
My manifest is :
<service class=".alarm" android:name=".alarm" android:enabled="true">
<intent-filter>
<action android:value="com.example.timepass.ALARM"
android:name=".alarm" />
</intent-filter>
</service>
Please guide me!!!
check your service is running or not from application manager
@prosper ofcourse it would not be running as it does not display any toast!!
Probably you don't have the service in your manifest, or it does not have an that matches your action. Examining LogCat should turn up some warnings that may help.
More likely, you should start the service via:
startService(new Intent(this, alarm.class));
your manifest is ok, start your service by this way startService(new Intent(this, alarm.class));
| common-pile/stackexchange_filtered |
Problems with Publish Web giving blank page
I have written my first asp.net website and I'm ready to deploy. I've followed this tutorial to the letter in order to test first and all seems to proceed without any hitches or errors. However, the webpage gives a blank page with nothing rendered, only
<html><head><style type="text/css"></style></head><body></body></html>
All the files seem to have deployed correctly and I can see them in C:\inetpub\wwwroot\Test Webpage and if I attempt to run using inetmgr I get the same.
Can anyone advise what the problem(s) might be? Below are some screenshots of IIS if it helps but will post up more info if needed.
What is your startup page? I believe it defaults to default.aspx. Have you put anything in that page? You can change your start page by right-clicking it in the solution explorer and selecting Set as Start Page.
My startup page is home.aspx and I have already set it as start page. Web Config also has... defaultUrl="home.aspx". I just re-tried and same result?
Check this one http://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-using-aspnet-35-and-aspnet-45
You might also look here: http://stackoverflow.com/questions/1164494/server-returns-blank-pages-with-asp-net-3-5-on-iis6
It's not exactly the same, but may have a similar cause.
Also, is your publish profile setup to overwrite existing files, or delete all files when you publish? If the former, try the latter.
And one more, if you're using authentication.
| common-pile/stackexchange_filtered |
All possible electromagnetic Lorentz invariants that can be built into the electromagnetic Lagrangian?
Given the electromagnetic Lagrangian density
$$
\mathcal{L}~=~-\frac{1}{4}F_{\mu\nu}F^{\mu\nu}~=~\frac{1}{2}(E^2-B^2)
$$
is a Lorentz invariant, how many other electromagnetic invariants exists that can be incorporated into the electromagnetic Lagrangian?
One can show that all local, gauge and Lorentz invariant can be constructed from only two quantities $F_{\mu\nu}F^{\mu\nu}$ and $\tilde F_{\mu\nu}F^{\mu\nu}$
What is the meaning of the symbol "~" over "F"?
$\tilde F_{\mu\nu}=\epsilon_{\mu\nu\sigma\lambda}F^{\sigma\lambda}$ and $\tilde F_{\mu\nu}F^{\mu\nu}\propto E^2-B^2$.
Oh its the dual tensor.
Related: http://physics.stackexchange.com/q/87817/2451 and links therein.
As mentioned in the comments, to find all possible terms we normally only consider local, gauge invariant, Lorentz invariant interactions. There are in fact an infinite number of these. This is easiest understood using the Lagrangian. The gauge invariant field stength tensor is given by
\begin{equation}
F _{ \mu \nu } = \partial _\mu A _\nu - \partial _\nu A _\mu
\end{equation}
The only other tensors with Lorentz indices are
\begin{equation}
\epsilon _{ \alpha \beta \gamma ... } \quad , \quad g _{ \mu \nu }
\end{equation}
To lowest order in $ F $ the only non-zero invariants are:
\begin{equation}
F _{ \mu \nu } F ^{ \mu \nu} \quad , \quad \epsilon _{ \alpha \beta \gamma \delta } F ^{ \gamma \delta } F ^{ \alpha \beta }
\end{equation}
If we restrict ourselves to terms with mass dimension of $4$ or lower these are the only options (these terms are called renormalizable terms). However, one can also write down other invariants which have higher mass dimensions. One such example is the mass dimension six term,
\begin{equation}
\partial ^\mu F _{ \mu \nu } \partial ^\alpha F _\alpha ^{ \,\, \nu }
\end{equation}
Such terms are small at low energies and are often ignored. In general there are an infinite number of allowed (non-renormalizable) terms in the Lagrangian. Though it may not be trivial, such terms could be written in terms of the electric and magnetic fields to find the different combinations of $\bf E$ and $\bf B$ that form Lorentz invariants.
Can one include the Lorentz gauge term into the Lagrangian?
A Lorentz gauge term, $\partial_\mu A^\mu$ is not gauge invariant. If you want to fix the gauge such that this term is zero then you can add it in. But at that point there is no use to including the term as this term is zero.
| common-pile/stackexchange_filtered |
routes not directing in laravel application
I am surprised this is not working but maybe I am missing something...I am trying to access from the main page (index.php) either the login page or the signup page. I created both routes to be handled. When I click on the link, it goes to another page such as /website/login and shows not found. Here is the routes.php code:
Route::get('/', 'MainController@index');
Route::get('login', array('as' => 'login', 'uses' => 'MembersController@loadLoginView'));
Route::get('signup', array('as' => 'signup', 'uses' => 'MembersController@loadRegisterView'));
MembersController code:
<?php
class MembersController extends BaseController {
public function loadRegisterView()
{
return View::make('members.register');
}
public function loadLoginView()
{
return View::make('members.login');
}
}
and inside views I have a folder called members and inside it I got login.blade.php and register.blade.php.
Thanks for the help in advance
View signup.blade.php should be named register.blade.php. Otherwise you'll be trying to render a non-existent view.
Sorry that was actually a typo in the question. It is called register.blade.php. Thanks for noticing
Do you have an .htaccess? if you go to http://www.example.com/index.php/login does it work?
@DamienPirsy yup that worked! How can I remove the index.php from the url though?
To remove the index.php you could use the .htaccess provided on the Laravel website:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Be sure you're running on an Apache server with Mod_rewrite active. I'm not expert on other servers, so I can't suggest you alternative. On Laravel's website there's this snippet for Nginx:
location / {
try_files $uri $uri/ /index.php?$query_string;
}
Have no idea on IIS server, though.
Otherwise, you'll need to keep the 'index.php' in the url, like http://www.example.com/index.php/login
I am using MAMP...any change you know how to make sure mod_rewrite is active?
| common-pile/stackexchange_filtered |
How can I segregate the application jar and dependencies?
I've a spring-boot application with maven, the final jar is of 96MB+ and I want to reduce that jar size by excluding dependencies jars from final jar and keeping them in one remote location and redirecting the dependencies location from final jar. By removing spring-boot-maven-plugin from pom.xml, I've generated the jar which of size 3MB+ but that is not able to run, giving error no main manifest attribute, in target\abc.jar. I understood that it's not executable. Please guide me how can I have the dependencies in a remote location and redirect it from application jar and how can I make the jar executable?
I tried segregating application jar and dependencies.
I'm expecting a separate executable application jar and dependencies.
Think about the dependencies you have defined and check if they are really needed... removing spring-boot-maven-plugin will not help nor is spring-boot-maven-plugin part of the final jar ... Check every dependency you have defined in your pom file if you really need it or not...that will result in reducing the jar size..
Don't it will be more trouble then it is worth as you will be reinventing the wheel. If you really want use something like the Spring Boot Thin Launcher instead of hacking away yourself.
The real point is this: I tried segregating application jar and dependencies. I'm expecting a separate executable application jar and dependencies. (Which I hand't read carefully enought) that can be achieved by spring thing launcher (written by @M.Deinum) but that will of course not reduce the overall size... The layers in Spring Boot maven plugin can give already some steps into this (https://docs.spring.io/spring-boot/docs/current/maven-plugin/reference/htmlsingle/#packaging.layers)
Why wouldn't it reduce the overall size? It will only create a jar with the application classes and upon startup will download them (or if you are using a machine that already has the .m2/repository directory use them from there by default.
| common-pile/stackexchange_filtered |
How to create a basic custom QGraphicsEffect in Qt?
I have been trying to create a basic QGraphicsEffect to change the colors of the widget, but first I tried to make an effect that does nothing like so:
class QGraphicsSepiaEffect(QtWidgets.QGraphicsEffect):
def draw(painter):
pixmap = sourcePixmap()
painter.drawPixmap(pixmap.rect(), pixmap)
I am using PySide2. Though I checked all over the internet but couldn't find any sample, neither a template nor a real custom effect.
How can I write a basic effect to alter the colors of my widget?
As your question is basically how to create a custom effect then based on an example offered by the Qt community I have translated it to PySide2:
import random
import sys
from PySide2 import QtCore, QtGui, QtWidgets
# or
# from PyQt5 import QtCore, QtGui, QtWidgets
class HighlightEffect(QtWidgets.QGraphicsEffect):
def __init__(self, offset=1.5, parent=None):
super(HighlightEffect, self).__init__(parent)
self._color = QtGui.QColor(255, 255, 0, 128)
self._offset = offset * QtCore.QPointF(1, 1)
@property
def offset(self):
return self._offset
@property
def color(self):
return self._color
@color.setter
def color(self, color):
self._color = color
def boundingRectFor(self, sourceRect):
return sourceRect.adjusted(
-self.offset.x(), -self.offset.y(), self.offset.x(), self.offset.y()
)
def draw(self, painter):
offset = QtCore.QPoint()
try:
pixmap = self.sourcePixmap(QtCore.Qt.LogicalCoordinates, offset)
except TypeError:
pixmap, offset = self.sourcePixmap(QtCore.Qt.LogicalCoordinates)
bound = self.boundingRectFor(QtCore.QRectF(pixmap.rect()))
painter.save()
painter.setPen(QtCore.Qt.NoPen)
painter.setBrush(self.color)
p = QtCore.QPointF(offset.x() - self.offset.x(), offset.y() - self.offset.y())
bound.moveTopLeft(p)
painter.drawRoundedRect(bound, 5, 5, QtCore.Qt.RelativeSize)
painter.drawPixmap(offset, pixmap)
painter.restore()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
lay = QtWidgets.QVBoxLayout(w)
for _ in range(3):
o = QtWidgets.QLabel()
o.setStyleSheet(
"""background-color : {}""".format(
QtGui.QColor(*random.sample(range(255), 3)).name()
)
)
effect = HighlightEffect(parent=o)
o.setGraphicsEffect(effect)
lay.addWidget(o)
w.show()
w.resize(640, 480)
sys.exit(app.exec_())
This doesn't compile, super takes 1 argument, 0 give, should be super(HighlightEffect, self)
@JoanVenge What version of python do you use? I assume that if the OP does not indicate it then use the latest version of Python, that is python3 but it seems that you use python2.
I am using 2.7. Then please specify the version in your answer for future readers.
@JoanVenge MHO would be better for the OP to specify its version :-) so that those who try to respond know what limitations the answer must have.
@JoanVenge Anyway I have already updated it to be compatible with python2 too
Sorry, please give an example for PyQt5
@S.Nick change PySide2 to PyQt5 in my example
pixmap = self.sourcePixmap(QtCore.Qt.LogicalCoordinates, offset) - ... argument 2 has unexpected type 'QPoint'
@S.Nick Thanks for the observation, there seems to be an incompatibility in the sourcePixmap method between PySide2 and PyQt5 but I already corrected it, try it and tell me if it works for you or not. :-)
@eyllanesc what do you mean now I want something specific? I didn't change the question here. If you mean the other question, there is a reason I asked them as separate questions because they are separate questions.
@JoanVenge Okay, so I have confused the concepts since we were talking in 2 post. To avoid this confusion, what is wrong with my answer in this question according to your opinion or what is missing?
| common-pile/stackexchange_filtered |
Updating a table with PHP and MYSQL
<?php require("inc_connect.php"); ?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td align="left" valign="top">
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name">
<br />
ID:
<label for="select"></label>
<select name="id">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while($output = mysql_fetch_array($run)){
echo "<option value=\"{$output['id']}\">{$output['id']}</option>";}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td width="300" align="left" valign="top"><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
The above is the index page ...
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}'";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{mysql_error();}
?>
And this is the page that processes the form.
The problem is that the record won't update if i set the id={$_GET['id']}
and if I remove that part it updates all the rows.
So updating according to id ...
Thanks in Advance
FarrisFahad
This is not the answer to your question, but you should read up on SQL Injection, especially if you are going to connect to MySQL as the root user (don't do that).
Try changing your form action to
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
Also, doing an echo of $query might help debug your problem.
Actually, you already have a reference to "id" in your form so update your form action to just "ex_update.php". Then change your php code to $id = (int) $_POST['id'];
First, just be aware of SQL Injection - your code is wide open to it. See http://bobby-tables.com/
PHP Code
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}' WHERE id = {$id}";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{
# In production, don't show raw errors to users - log them to a file and
# present the user with a generic "There was a problem with the database"
# error. Or people can start sniffing for vulnerabilities in your site.
echo mysql_error();
}
?>
Page
<?php
require("inc_connect.php");
?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td><form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name"><br />
<label for="select">ID:</label>
<select name="id" id="select">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while( $r = mysql_fetch_array($run) ){
# I always use short, single character, variables when in loops.
# Saves alot of characters and potential confusion.
echo " <option value='{$r['id']}'>{$r['id']}</option>\n";
}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
I just checked, and there is no problem with the query when I UPDATE without WHERE id={$id}. but I would like to update it according to the id,
OK, three things then. 1) Can you share the full SQL statement (with WHERE...) here? 2) Does the id field exist in the table? 3) What does the mysql_error() display?
As you want to update that record which is selected from your dropdown. Moreover u have set your form method to POST. So you should try following:
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">
| common-pile/stackexchange_filtered |
How to prove that angular velocity is not a derivative of angular displacement?
The angular velocity $\omega$ of a two-dimensional solid body is given by $$\omega = \hat{z} \cdot \frac{\vec{r} \times \vec{v}}{r^2},$$ where $\vec{r}$ and $\vec{v}$ are the position and the velocity of an arbitrary point of the body relative to the center of mass, and $\hat{z}$ is the unit vector perpendicular to the body. I can write this as $$\omega dt = \hat{z} \cdot \frac{\vec{r} \times d \vec{r}}{r^2}.$$ I want to show that there does not exist such a function $\varphi(\vec{r}(t))$ so that $d \varphi = \omega dt$. Is there an easy way to see this? Perhaps using the fact that $$\hat{z} \cdot \frac{\vec{r} \times d \vec{r}}{r^2} = d \left(\hat{z} \cdot \frac{\vec{r} \times \vec{r}}{r^2}\right) - (\hat{z} \cdot (\vec{r} \times \vec{r})) d \left(\frac{1}{r^2}\right) - \hat{z} \cdot \frac{d\vec{r} \times \vec{r}}{r^2} = 0-0+\hat{z} \cdot \frac{\vec{r} \times d \vec{r}}{r^2}?$$
Integrating $\omega$ along a closed loop around the origin gives something nonzero. So $\omega$ can't be exact.
Note your question is asking about angular position, not angular displacement. You can, in fact, define angular displacement along a curve as $\theta(t) = \int_0^t \omega(s) , \mathrm{d} s$, and then you do have $\omega(t) = \theta'(t)$.
Let the body lie in the $xy$-plane. Consider the unit circle $c$ in the $xy$-plane parametrized by $\vec{r}(t) = (\cos t, \sin t, 0)$, $0 \le t \le 2\pi$. Then $\vec{v}(t) = (-\sin t, \cos t, 0)$, and so $\vec{z} \cdot (\vec{r} \times \vec{v}) = \hat{z} \cdot (0,0,1) = 1$. Since $r^2 = 1$, $$\int_c \omega\, dt = \int_c \hat{z}\cdot (\vec{r} \times \vec{v})\, dt = \int_0^{2\pi} 1\, dt = 2\pi \neq 0.$$ Therefore $\omega\, dt$ is is not exact.
So, basically, the problem is the multivaluedness of the angle variable?
What do you mean?
@LBO: That's right.
| common-pile/stackexchange_filtered |
Unhashable type in python
I am trying to call functions of a C based .dll from python, by creating wrappers.I face a scenario where i need to create a callback in python for a function in that .C dll. In C, The callback function is of type
typedef void (*Log_Callback_t)(void * pDataParams, uint8_t bOption, Log_Entry* pLogEntries, uint16_t wEntryCount);
src.py
# I am adding excerpts of the .py file. Pls indicate if it's incomplete or unclear
class Log_Entry(Structure):
_pack_ = 1
_fields_ = [('bLogType',c_ubyte),
('wDataLen',c_uint16)
]
logArray = (Log_Entry)()
def LogCallBack(pDataParams,bOption,pLogEntries,wEntryCount):
GlobalVars.log.info("In LogCallBack")
# Creating function ptr type
callback_type = CFUNCTYPE(None,c_void_p,c_ubyte,pointer(LogEntry),c_uint16)
# Creating function ptr of LogCallBack
callback_ptr = callback_type(LogCallBack)
# Passing the created function ptr to python wrapper
status1 = LogInit (callback_ptr,32)
While running this, i face the below issue with pointer(Log_Entry) i suppose. Can someone pls point me where am i going wrong
callback_type = CFUNCTYPE(None,c_void_p,c_ubyte,pointer(LogEntry),c_uint16)
File "C:\python\lib\ctypes\__init__.py", line 99, in CFUNCTYPE
return _c_functype_cache[(restype, argtypes, flags)]
TypeError: unhashable type
Exception TypeError: unhashable type
I referred to already posted questions related to unhashable type, but i did not find related to it, hence posting here. BTW, i tried with byref as well.
Since LogEntry is a type, I think you might need to use POINTER(LogEntry).
pointer(LogEntry) is an instance of a pointer to an instance of a variable called LogEntry that isn't defined.
POINTER(type) is the type of a pointer to the specified type. Types are needed by .argtypes, so POINTER(Log_Entry) is needed.
Working example:
test.c
#include <stdint.h>
#define API __declspec(dllexport)
#pragma pack(push,1)
typedef struct Log_Entry {
uint8_t bLogType;
uint16_t wDataLen;
} Log_Entry;
#pragma pack(pop)
typedef void (*Log_Callback_t)(void * pDataParams, uint8_t bOption,
Log_Entry* pLogEntries, uint16_t wEntryCount);
API int LogInit(Log_Callback_t cb, uint8_t num) {
Log_Entry entry[2];
entry[0].bLogType = 1;
entry[0].wDataLen = 2;
entry[1].bLogType = 3;
entry[1].wDataLen = 4;
cb(NULL, num, entry, 2);
return 6;
}
test.py
from ctypes import *
class Log_Entry(Structure):
_pack_ = 1
_fields_ = [('bLogType',c_ubyte),
('wDataLen',c_uint16)]
def __repr__(self):
return f'Log_Entry(bLogType={self.bLogType}, wDataLen={self.wDataLen})'
CALLBACK = CFUNCTYPE(None, c_void_p, c_ubyte, POINTER(Log_Entry), c_uint8)
dll = CDLL('./test')
LogInit = dll.LogInit
LogInit.argtypes = CALLBACK, c_uint16
LogInit.restype = c_int
@CALLBACK
def LogCallBack(pDataParams, bOption, pLogEntries, wEntryCount):
print(f'{pDataParams=} {bOption=} {wEntryCount=}')
for i in range(wEntryCount):
print(f'LogEntry[{i}]={pLogEntries[i]}')
status1 = LogInit(LogCallBack, 32)
Output:
pDataParams=None bOption=32 wEntryCount=2
LogEntry[0]=Log_Entry(bLogType=1, wDataLen=2)
LogEntry[1]=Log_Entry(bLogType=3, wDataLen=4)
| common-pile/stackexchange_filtered |
correct logical URI for fs.defaultFS and dfs.nameservices?
i followd apache documentation for setting up Hadoop HA Namenode
in core-site.xml i have the following
<property>
<name>fs.defaultFS</name>
<value>hdfs://apache-hadoop-namenode:8020</value>
</property>
in hdfs-site.xml
<property>
<name>dfs.nameservices</name>
<value>apache-hadoop-namenode</value>
</property>
should value of both be the same? if so should I need to mention the port 8020 as shown above or not?
dfs.nameservices can be a comma-separated list of NameServices. NameServices do not include protocols or ports.
If you have no NameServices, then hdfs://apache-hadoop-namenode:8020 would refer to a DNS name, not a NameService
This page covers federation and configuration of nameservices. https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs-rbf/HDFSRouterFederation.html
| common-pile/stackexchange_filtered |
Does TWRequest work for the twitter streaming api?
I am trying to make a basic iphone app that shows nearby tweets. I was using the TWRequest object to accomplish this with the twitter search api. Unfortunately, I would actually like to mark the tweets on a map using their GPS coordinates and the search api doesn't seem to return the actual location that a tweet was made with any better accuracy than the city name.
As such, I think I need to switch to the streaming api. I am wondering if it is possible to continue using the TWRequest object in this case or if I need to actually switch over to using NSURLConnection? Thanks in advance!
Avtar
Yes, you can use a TWRequest object. Create your TWRequest object using the appropriate URL and parameters from the Twitter API doco, and set the TWRequest.account property to the ACAccount object for the Twitter account.
You can then use the signedURLRequest method of TWRequest to get an NSURLRequest which can be used to create an asynchronous NSURLConnection using connectionWithRequest:delegate:.
Once this is done, the delegate's connection:didReceiveData: method will be called whenever data is received from Twitter. Note that each NSData object received may contain more than one JSON object. You will need to split these up (separated by "\r\n") before converting each one from JSON using NSJSONSerialization.
It took me a bit of time to get this up and running, So I thought I aught to post my code for others. In my case I was trying to get tweets close to a certain location, so you will see that I used a locations parameter and a location struct I had in scope. You can add whatever params you want to the params dictionary.
Also note that this is bare bones, and you will want to do things such as notify the user that an account was not found and allow the user to select the twitter account they would like to use if multiple accounts exist.
Happy Streaming!
//First, we need to obtain the account instance for the user's Twitter account
ACAccountStore *store = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request permission from the user to access the available Twitter accounts
[store requestAccessToAccountsWithType:twitterAccountType
withCompletionHandler:^(BOOL granted, NSError *error) {
if (!granted) {
// The user rejected your request
NSLog(@"User rejected access to the account.");
}
else {
// Grab the available accounts
NSArray *twitterAccounts = [store accountsWithAccountType:twitterAccountType];
if ([twitterAccounts count] > 0) {
// Use the first account for simplicity
ACAccount *account = [twitterAccounts objectAtIndex:0];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:@"1" forKey:@"include_entities"];
[params setObject:location forKey:@"locations"];
[params setObject:@"true" forKey:@"stall_warnings"];
//set any other criteria to track
//params setObject:@"words, to, track" forKey@"track"];
// The endpoint that we wish to call
NSURL *url = [NSURL URLWithString:@"https://stream.twitter.com/1.1/statuses/filter.json"];
// Build the request with our parameter
TWRequest *request = [[TWRequest alloc] initWithURL:url
parameters:params
requestMethod:TWRequestMethodPOST];
// Attach the account object to this request
[request setAccount:account];
NSURLRequest *signedReq = request.signedURLRequest;
// make the connection, ensuring that it is made on the main runloop
self.twitterConnection = [[NSURLConnection alloc] initWithRequest:signedReq delegate:self startImmediately: NO];
[self.twitterConnection scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
[self.twitterConnection start];
} // if ([twitterAccounts count] > 0)
} // if (granted)
}];
Be careful when posting copy and paste boilerplate/verbatim answers to multiple questions, these tend to be flagged as "spammy" by the community. If you're doing this then it usually means the questions are duplicates so flag them as such instead:http://stackoverflow.com/a/12485390/419
| common-pile/stackexchange_filtered |
Set Iam Policy using Resource Manager Python V3 GCP API doesn't have a policy field?
I am trying to add service accounts to a certain role in a project in GCP. In order to do so, I get the IAM policy and then add the accounts desired, but am unable to get set_iam_policy to work correctly. I add the projects_to_add to the member list for the role I want to add service accounts to, but the GCP Docs are confusing and I'm not able to add the roles_dict I updated to set_iam_policy. Does anyone know how I should do this?
client = resourcemanager_v3.ProjectsClient(credentials=credentials)
req = iam_policy_pb2.GetIamPolicyRequest(
resource="projects/mse-sandbox-registry-anushka"
)
response = client.get_iam_policy(request=req)
roles_dict = MessageToDict(response)
projects_to_add = []
projects_to_remove = []
for proj in proj_numbers:
account = (
"serviceAccount:service-"
+ proj
+<EMAIL_ADDRESS> )
if proj not in storage_obj_viewer_list:
projects_to_add.append(account)
for dict in roles_dict["bindings"]:
if (
dict["role"] == "roles/storage.objectViewer"
): # add the projects into the dictionary
members_list = dict["members"]
members_list.append(projects_to_add)
dict["members"] = members_list
req = iam_policy_pb2.SetIamPolicyRequest(
resource="mse-sandbox-registry-anushka", Policy=roles_dict
)
response = client.set_iam_policy(
request=req,
)```
I tried various forms, including passing in resource="projects/<my-project-name>", policy=roles_dict, but nothing seems to work.
| common-pile/stackexchange_filtered |
What does SoC stand for?
… and no, I do not mean System-on-a-Chip.
I stumbled upon this question which was using the acronym in the context of graphics, and found myself wondering about its meaning. Neither the question nor the answer further explained the acronym, and a search on google only got me "system-on-a-chip", which I was already familiar with, and "security operations center", which I was less familiar with.
What does SoC stand for in the context of game development (and/or software engineering)?
It stands for Separation of Concerns, i.e. designing a software so that each section has a specific purpose.
As you guessed, it's a general software engineer priciple and it is not specific to game design/programming.
This is often done (and not limited to) to reduce the coupling between sections, resulting in better reusability, code clarity and (sometimes) teamwork.
Additional benefits: test-ability and composition
It's not necessarily a software thing though, it's often a network engineering thing too. Things like not having your MMORPG on the same server as your billing system and registration page for example, that's SoC too.
| common-pile/stackexchange_filtered |
Get variables from php file to bash sh script
Im building a shell script to automate some process on my work.
I need to pull some variables from a php they are created like this:
return [
'db' => [
'table_prefix' => '',
'connection' => [
'default' => [
'host' => 'localhost',
'dbname' => 'dbname',
'username' => 'root',
'password' => '',
'model' => 'mysql4',
'engine' => 'innodb',
'initStatements' => 'SET NAMES utf8;',
'active' => '1'
]
]
],
So, my plan was to pull the php file this way:
#!/bin/bash
# php file to get variables from
FILE_NAME="etc/env.php"
echo "Starting Migration..."
DATABASE=$(cat $FILE_NAME | grep "^\'dbname' =>" | cut -d "=" -f 2-)
DATABASE_HOST=$(cat $FILE_NAME | grep "^\host=" | cut -d "=" -f 2-)
DATABASE_PASS=$(cat $FILE_NAME | grep "^\password=" | cut -d "=" -f 2-)
DATABASE_USER=$(cat $FILE_NAME | grep "^\$username=" | cut -d "=" -f 2-)
echo "Value from PHP file"
echo "Database name ${DATABASE}"
echo "Database host ${DATABASE_HOST}"
echo "Database pass ${DATABASE_PASS}"
echo "Database user ${DATABASE_USER}"
But im not getting the variables , its just empty...any ideas?
Is FILE_NAME supposed to be "etc/env.php" or "/etc/env.php"? Do any of the subexpressions work? What does cat $FILE_NAME | grep "^\'dbname' =>" | cut -d "=" -f 2- do on its own? Why cat $FILE_NAME | grep expression? grep expression $FILE_NAME is better. There's http://porkmail.org/era/unix/award.html
Yes, this command DATABASE=$(cat $FILE_NAME | grep "dbname" | cut -d "=" -f 2-) seems to be working, but im getting some characters i dont need, im getting with that call: > 'dbname', , so i just need to get dbname
You could grep expression $FILE_NAME | cut "-d'" -f4, that is use "'" as the delimiter.
Using GNU grep if available, you can do this
grep -Po "(?<='dbname' => ).*(?=,)" file
In your script:
DATABASE=$(grep -Po "(?<='dbname' => ).*(?=,)" $FILE_NAME)
DATABASE_HOST=$(grep -Po "(?<='host' => ).*(?=,)" $FILE_NAME)
DATABASE_PASS=$(grep -Po "(?<='password' => ).*(?=,)" $FILE_NAME)
DATABASE_USER=$(grep -Po "(?<='username' => ).*(?=,)" $FILE_NAME)
With the -P option you activate Perl-like regular expressions.
With the -o option you get only the captured string, not the whole line.
Basically this happens:
(?<=<string starts with>)<capture this string>(?=<string ends with>)
This is close, im getting etc/env.php:'localhost' , i need get only localhost.
Sorry I edited the answer, there was an error: file $FILE_NAME is just $FILE_NAME
Thank you, its working, just getting: Database host 'localhost' can we remove the ' and just get Database host localhost ? can you explain what are you doing?
I edited the answer, hopefully it's clear. To remove the single quotes you just need "(?<='dbname' => ').*(?=',)". Do you want me to add that to the answer?
Thank you so much, this is the final result:
DATABASE=$(grep -Po "(?<='dbname' => ').(?=',)" $FILE_NAME)
DATABASE_HOST=$(grep -Po "(?<='host' => ').(?=',)" $FILE_NAME)
DATABASE_PASS=$(grep -Po "(?<='password' => ').(?=',)" $FILE_NAME)
DATABASE_USER=$(grep -Po "(?<='username' => ').(?=',)" $FILE_NAME)
Pure magic ! Just what I need +1 !
My variable is saved in the file as - $db_host = "blabla.rds.amazonaws.com"; So, I used this systex and it worked for me - DB_HOST=$(grep -Po '(?<='db_host' = ").*(?=";)' $FILE_NAME)
Typically for each feature a shell script needs that isn't within the scope of shell scripting, it calls some other program that will "do one thing well" (Unix philosophy) so why not call the program that does what you want to do? You may not have realized that you can run PHP directly from the command line (or shell script in this case) using the PHP -r argument. Here is how to do it with your example (Assuming the input file starts with <?php and ends with ; ?> instead of ,), by using the require statement to use the return of the php file as an array (which it is in your case):
DATABASE=$(php -r 'echo (require("input.php"))["db"]["connection"]["default"]["dbname"];')
DATABASE_HOST=$(php -r 'echo (require("input.php"))["db"]["connection"]["default"]["host"];')
DATABASE_PASS=$(php -r 'echo (require("input.php"))["db"]["connection"]["default"]["password"];')
DATABASE_USER=$(php -r 'echo (require("input.php"))["db"]["connection"]["default"]["username"];')
If the PHP file doesn't have a return within the global scope, follow the require statement with ; then do a separate echo statement (The -r argument can accept multiple lines if each ends with semicolon. See my answer at https://unix.stackexchange.com/a/747009/343286).
| common-pile/stackexchange_filtered |
How to POST data from js to php scripts other than controllers in laravel
I'm trying to post some data from my js to a php script which is not a controller using ajax but I can't get it to work. I put the script in app/Classes Here is what I've done so far.My Javascript:
$.ajax({
url:'apps/Classes/TheScript.php',
method: 'POST',
dataType: 'json',
data: {data: 'some data'}
});
TheScript.php
namespace App\Classes;
class TheScript{
public function get() {
return $_POST['data'];
}
}
I tried to use it in my controller like this:
use App\Classes\TheScript;
class MyController extends Controller {
function home(){
$script= new TheScript();
$data = $script->get();
return view('home',['data' => $data]);
}
}
When I run this, I get the error Undefined index: data in the TheScript.php get() function. My question is, is there a way to refer to another script that isn't a controller from my ajax url? How can I achieve this? Thank you
in wich file MyController class is saved?
It is saved in the app\Http\Controllers directory
What does var_dump(file_get_contents('php://input')) say ?
It says string(0) ""
I did that and still got the same error
You could wire your request directly to your php script attached as closure to a Laravel route like this:
js:
$.ajax({
url: 'apps/classes/thescript',
method: 'POST',
dataType: 'json',
data: {data: 'some data'}
});
routes.php
Route::post('apps/classes/thescript', function()
{
$data = Input::get('data');
$script = new TheScript;
$script->data = $data;
$script->save();
return view('home',['data' => $data]);
});
If I declear TheScript as an instance, how will I get the "$data" valuable? Do I have to return this variable?
You could instantiate your class and add $data received by ajax call as its property. See my edited answer.
(Assuming you are using apache and public/ is you DocumentRoot)
If you want to access files outside the DocumentRoot, you should use Alias.
<VirtualHost *:80>
#...
DocumentRoot "YOUR_PATH_/public"
Alias /app YOUR_PATH_/app
#...
</VirtualHost *:80>
Now you can access the app/Classes/TheScript.php
Change TheScript.php to return some data.
<?php
$data = $_POST['data'];
echo json_encode($data);
Change the ajax request url to: '/app/Classes/TheScript.php'
| common-pile/stackexchange_filtered |
Create a fragment many times with different data and add to back stack
I create one fragment with many items because the number of items is not known I want when clicked in every item that same fragment recreate it(like child fragment) and add to back stack With information about each specific item
and when back pressed pop in back stack.
(A fragment is often created with new information and added to the back stack and pop)
Any one can help me?
Are these screens always stacked on top of eachother (i.e. A1->A2->A3) or can there be different screens inbetween (i.e. A1->A2->B->A3)?
Welcome to StackOverflow @rezayi. It seems you are looking for others to solve your problem.
Please take the tour and add some detail to your post as to what you have tried so far that isn't working (https://stackoverflow.com/help/how-to-ask).
There is likely a bunch of answers here on StackOverflow that will help you implement a solution to your required design.
| common-pile/stackexchange_filtered |
How do I include an activeX library in my C++ project?
I would like to add a third party library to my C++ project.
The library is ActiveX and I have to admit, that I have no experience with that. I tried to google the solution but could not find one that fits for me.
I'm using Visual Studio and my project is not MFC.
From the third party library I have a dll-file, a tlb-file and an idl-file, but no header file. I tried to include the tlb-file but when compiling I got a lot of errors from the kind of missing typedef for default-int and character is not allowed. (just by writing #include "xyz.tlb")
Is the tlb file incompatible with my project? Is there another way to include the activeX class I need?
https://msdn.microsoft.com/en-us/library/8etzzkb6.aspx
One could easily write an entire college course about doing what you're talking about. The simple answer is that you need to use #import not #include, but there is a lot more you'll have to deal with to properly utilize an activex library.
| common-pile/stackexchange_filtered |
Trying to understand pointers and threads
I am fairly new to C and trying to understand threads and pointers. As far as i know, this line creates a thread
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
The fourth arg is taking the argument for the pointer function (void *)t, and this is a pointer to the address of variable t which is a long type? And the pointer function takes the argument of void pointer to a variable, which is (void *)t.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 20
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0;t<NUM_THREADS;t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
After that, I changed the pointer function and the pthread_create to this:
{
long taskid;
sleep(1);
taskid = *(long *)threadid;
printf("Hello from thread %ld\n", taskid);
pthread_exit(NULL);
}
rc = pthread_create(&threads[t], NULL, PrintHello, (void *) &t);
So now the void pointer is still pointing to the address of variable t?
And *(long *)threadid is de-referencing the variable t?
And it outputs the final value of t in all threads.
I'm not sure if I understand it correctly, if I misunderstood somewhere I appreciate any advice. My question is for the (void *)t and (void *) &t, they are both pointers to the address of variable t, and I read pointers can only be point to addresses but not values, so why is the (void *)t outputting the incrementing values of t? taskid = *(long *)threadid; And if I just do taskid = threadid it prints out the address of t, what does *(long *) do? The * outside the brackets is de-referencing?
Putting a type in brackets before something is casting that value into that data type. So in your examples (void *) t converts the value of t from a long to a void *. This is done because the pthread_create is expecting a pointer.
Putting a & in front of something gets the address of it. So &t gets the address of t. It's then being cast to void * as described above, although it isn't really needed as any pointer will be automatically cast to void * if required.
So in the first version of your code you're passing the actual value of t into your thread by casting it to make it look like it is a pointer and then casting it back again inside the thread to get the long value.
The second version is passing a pointer to t in, so each thread will print out the value of t at the time the reach this line:
taskid = *(long *)threadid;
taskid = *(long *)threadid; so on this line i am casting it back to long, but since it's a pointer to t, i have to use * outside the brackets to get the value, and casting (long *) because it is a pointer? Otherwise it wouldn't work if i just cast (long) because t is a pointer?
Not quite. You're casting it to long * and then dereferencing that. You can't dereference void * pointers.
Got it, thank you very much for the explanation, i understand it better now :)
To get an address of a variable you have to use &.
(void*)t does not get the address of t. It takes the value of t, and treats that value as a void* value instead. So you have a pointer to memory address 0, 1, 2, ... up to NUM_THREADS-1.
You can't use these pointers because they don't point to valid addresses. But you can treat them as numbers again by using (long)threadid.
The only reason you need to make the type void* is because that's what pthreads uses as the parameter to the thread function. If you used void *PrintHello(long threadid) then you would get an error when calling pthread_create, which would say that the function had the wrong type.
So in the second example, i have to cast (long *)threadid because i'm passing in the pointer to t, in other words the address of t?
@aalang Yes. I hope you also understand why it prints the final value in all threads.
I kinda get why, but is it because i called sleep(1), and by the time it finishes sleep, the t value is already the final value, and so it only starts assigning taskid to the threadid?
Yes, that is the reason. (I'm not sure what "it only starts assigning taskid to the threadid" means but the rest of what you said is correct)
I mean after it sleeps, then only executes the rest of the code from taskid = threadid, which by then is already final value
| common-pile/stackexchange_filtered |
How to find unique values by group in datatable Frame
I have created a datatable frame as follows,
DT_EX = dt.Frame({'cid':[1,2,1,2,3,2,4,2,4,5],
'cust_life_cycle':['Lead','Active','Lead','Active','Inactive','Lead','Active','Lead','Inactive','Lead']})
Here I have three unique customer life cycles and each of these counts are found as
DT_EX[:, count(), by(f.cust_life_cycle)]
Along with it, I have five customer IDs and these counts are as
DT_EX[:, count(), by(f.cid)]
Now I would like to see how many of unique customer ID's existed per each of customer life cycle,
DT_EX[:, {'unique_cids':dt.unique(f.cid)}, by(f.cust_life_cycle)]
It should display as Lead customer has got 3 unique customer ID's such as (1,2,5), Active user has got 2 unique customer ID's (2,4) so on forth.
I couldn't get it as expected, Could you please let me know how to get it fixed?.
FYI: I have tried to reproduce the same on R data.table frame, its working.
DT_EX[, uniqueN(cid), by=cust_life_cycle]
There is now a nunique implementation :
DT_EX[:, f.cid.nunique(), 'cust_life_cycle']
| cust_life_cycle cid
| str32 int64
-- + --------------- -----
0 | Active 2
1 | Inactive 2
2 | Lead 3
[3 rows x 2 columns]
The dt.unique function does not apply by groups (yet). So, one way to achieve what you need would be to first group by the lifecycle + customerID, and then in the second step re-group by lifecycle only:
>>> DT_EX[:, count(), by(f.cust_life_cycle, f.cid)]\
... [:, {"unique_cids": count()}, by(f.cust_life_cycle)]
| cust_life_cycle unique_cids
-- + --------------- -----------
0 | Active 2
1 | Inactive 2
2 | Lead 3
[3 rows x 2 columns]
@pasha
I have also created a custom function for my practice as below,
def pydt_unique_per_group(DT,by_col,uni_col):
DT_dict = DT[:,(f[by_col],f[uni_col])].to_dict()
pairs = list(zip(DT_dict[by_col], DT_dict[uni_col]))
unique_per_col_dict = {k : list(map(itemgetter(1), v)) for k,v in groupby(sorted(pairs, key=itemgetter(0)), key=itemgetter(0))}
unique_per_col_count = {drink:len(set(ingr)) for drink,ingr in unique_per_col_dict.items()}
unique_per_col_count_sort = {k:v for k,v in sorted(unique_per_col_count.items(),key=lambda x:x[1],reverse=True)}
by_group_summary_dict = {by_col:[],'count':[]}
for k, v in unique_per_col_count_sort.items():
by_group_summary_dict[by_col].append(k)
by_group_summary_dict['count'].append(v)
return dt.Frame(by_group_summary_dict)
output:
In [8]: pydt_unique_per_group(DT_EX,'cust_life_cycle','cid')
Out[8]:
| cust_life_cycle count
-- + --------------- -----
0 | Lead 3
1 | Active 2
2 | Inactive 2
[3 rows x 2 columns]
| common-pile/stackexchange_filtered |
How to get direction of rotation from linear velocity of pendulum?
I have a class called Pendulum which has getters and setters allowing it to calculate its angle of rotation if given some inputs like: initial angle, current time (which is used to calculate dt), etc.
I am using THREE.js
One of these getter methods is called get angularVelocity() and this one has a logic error. I can't figure out what this error is so I can fix it.
The getter is defined:
get angularVelocity() {
// we have v and radius => w = v/r
// positive w means cw, negative means acw rotation
const linearSpeed = linearVelocity.length();
const wMagnitude = linearSpeed / pendulumLength;
const axis = new THREE.Vector3(0, 0, 1);
const w = new THREE.Vector3();
w.crossVectors(axis, v);
w.setLength(wMagnitude);
const dotProduct = w.dot(axis);
const isClockwise = dotProduct < 0;
return isClockwise ? wMagnitude : -wMagnitude;
}
The problem is that the pendulum rotates clockwise no matter the direction of the linear velocity. Why is this and how can I fix my logic so that the pendulum rotates in a direction as if a force is applied to the end of the pendulum along the velocity vector?
Ie the direction of rotation calculated here does not follow the direction of linear velocity.
I have added my full code below in case the error is actually elsewhere:
class PendulumScene {
#scene;
#camera;
#renderer;
#pendulum;
#pendulumData;
#parent;
#g;
#clock;
constructor(pendulumLengths, startingAngles) {
this.#scene = new THREE.Scene();
this.#camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
this.#camera.position.z = 2;
this.#camera.lookAt(0,0,0);
this.#renderer = new THREE.WebGLRenderer();
this.#renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild(this.#renderer.domElement);
this.#g = new THREE.Vector3(0,-1,0); // acceleration due to gravity
this.#clock = new THREE.Clock();
this.populateScene(pendulumLengths, startingAngles);
this.animate();
}
populateScene(pendulumLengths, startingAngles) {
const len = pendulumLengths[0]; // todo - make it loop thru all lengths to make it a double/tripple etc pendulum
const angle = startingAngles[0];
const material = new THREE.MeshBasicMaterial({color: 0x33bb33});
this.#pendulum = new THREE.Mesh(
new THREE.BoxGeometry(.25, len, .25),
material
);
this.#parent = new THREE.Object3D();
this.#parent.add(this.#pendulum);
this.#parent.position.set(0, len, 0);
this.#pendulum.position.set(0, -len/2, 0);
this.#parent.rotation.z = angle;
this.#scene.add(this.#parent);
const pendulumVelocity = new THREE.Vector3(0,0,0);
this.#pendulumData = new Pendulum(len, angle, this.#g, this.#clock);
}
animate() {
requestAnimationFrame(() => {
this.animate();
});
this.#renderer.render(this.#scene, this.#camera);
const rotation = this.calcPendulumRotation();
// todo - this.#parent.rotation.set(...rotation);
}
calcPendulumRotation() {
const newTheta = this.#pendulumData.theta;
this.#parent.rotation.z = newTheta;
if(this.velocityArrow) {
this.#scene.remove(this.velocityArrow);
this.#scene.remove(this.accelerationArrow);
}
const v = this.#pendulumData.getVelocityArrow();
const a = this.#pendulumData.getAccelerationArrow();
const origin = new THREE.Vector3(0,-1,1);
const length = new THREE.Vector3(0,1,0);
origin.add(length);
const vLen = v.clone().length();
v.normalize();
this.velocityArrow = new THREE.ArrowHelper(v, origin, vLen, 0xff0000);
const aLen = a.clone().length();
a.normalize();
this.accelerationArrow = new THREE.ArrowHelper(a, origin, aLen, 0x008800);
this.#scene.add(this.velocityArrow, this.accelerationArrow);
}
}
class Pendulum {
#oldVelocity; // the velocity at a very small time, dt, earlier
#oldAngularVelocity;
#oldAcceleration;
#radiusVector;
#length;
#g;
#gSize;
#clock;
#currentDt;
#oldTheta;
#dampingFactor;
#axis;
constructor(length, initialTheta, g, clock) {
this.#radiusVector = new THREE.Vector3(length,0,0);
this.#length = length;
this.#g = g;
this.#gSize = Math.abs(g.y);
this.#clock = clock;
this.#currentDt = undefined;
this.#oldVelocity = new THREE.Vector3(0,0,0);
this.#oldAcceleration = new THREE.Vector3(0,0,0);
this.#oldAngularVelocity = 0;
this.#oldTheta = initialTheta;
/*if(this.#initialTheta > Math.PI) {
console.log(this.#initialTheta*(360/2));
this.#initialTheta = -2*Math.PI + this.#initialTheta;
console.log(this.#initialTheta*(360/2));
}*/
this.#dampingFactor = 1;
this.#axis = new THREE.Vector3(0,0,1);
}
get deltaTime() {
return this.#clock.getDelta(); // always around ~0.002: this.#clock.getDelta();
}
get t() {
return this.#clock.getElapsedTime();
}
get acceleration() {
/*let dir = -1;
if(this.#oldTheta < 0) {
dir = 1;
}*/
const mag = this.#gSize * Math.sin(this.#oldTheta);
const direcAngle = this.#oldTheta + /*dir**/Math.PI/2;
const a = new THREE.Vector3(0, mag, 0).applyAxisAngle(this.#axis, direcAngle);
a.multiplyScalar(this.#dampingFactor);
this.#oldAcceleration = a;
return a;
}
get velocity() { // linear velocity
this.#currentDt = this.deltaTime;
const averageAcceleration = this.#oldAcceleration.clone().add(this.acceleration.clone());
averageAcceleration.divideScalar(2);
const dv = averageAcceleration.multiplyScalar(this.#currentDt);
const v = this.#oldVelocity.clone().add(dv);
this.#oldVelocity = v;
return v;
}
get angularVelocity() {
// we have v and radius => w = v/r
// positive w means anticlockwise, negative means clockwise
/*
let dir = 1;
if(velocity.y < 0) { // todo problem here - decide which way w is
dir = -1;
}
const w = dir*velocity.length() / this.#length;
// this.#oldAngularVelocity = w;
return w;*/
const v = this.velocity.clone();
const wMagnitude = v.length() / this.#length;
const axis = new THREE.Vector3(0, 0, 1);
const w = new THREE.Vector3();
w.crossVectors(axis, v);
w.setLength(wMagnitude);
const dotProduct = w.dot(axis);
const isClockwise = dotProduct < 0;
return isClockwise ? wMagnitude : -wMagnitude;
}
get integratedAngularVelocity() {
// integrated angular velocity means the change in theta over dt
// where dt is stored in this.#currentDt
/*const oldAngularVelocity = this.#oldAngularVelocity; // at time 0
const newAngularVelocity = this.angularVelocity; // at time dt
// integrate approximately (trapezium rule, since dt doesnt tend to 0 especially on slow computers)
const averageAngularVelocity = (oldAngularVelocity+newAngularVelocity)/2;
const deltaTheta = averageAngularVelocity * this.#currentDt;
return deltaTheta;*/
// calcualte area of thin slice of w over t graph, call it dTheta
const dTheta = this.angularVelocity * this.#currentDt;
return dTheta;
}
get theta() {
// we have theta0 and w
// => integrate w and add on to theta0 to get new theta
// because the integration getter returns the area of a small slice of the graph of w over t, not the entire area
const newTheta = this.integratedAngularVelocity + this.#oldTheta;
this.#oldTheta = newTheta;
return newTheta;
}
getVelocityArrow() {
return this.#oldVelocity;
}
getAccelerationArrow() {
return this.#oldAcceleration;
}
}
const pendulumScene = new PendulumScene(
[1], // pendulum lengths
[Math.PI/4], // starting angles
);
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100vw;
height: 100vh;
overflow: hidden;
background: black;
}
canvas {
width: 50vw;
outline: 1px solid #00ff00;
height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.1/three.min.js"></script>
In the snippet above:
the green and red arrows show the acceleration and velocity vectors.
the function which instantiates Pendulum calls the pendulum's theta getter (each frame) to rotate it by the angle theta in the three js scene. The theta getter calls all the other getters one by one.
In your function, through w.crossVectors(axis, v), you set the direction of w perpendicular to the z axis, so the w's z component is always zero, therefore dotProduct is always zero (which is revealed by debugging) and isClockwise always false. I suppose you wanted to compute the direction of the w vector as that of (r x v) and not (k x v) (k the z axis versor).
| common-pile/stackexchange_filtered |
How to create a squiggle arrow with some text on it in TikZ?
I need to define a new command to create a squiggle arrow with some text on it. Something similar to what \xrightarrow command produces but with wiggly arrows as in \rightsquigarrow. The length of the arrow should automatically be adjusted to fit the text above it and I do not know how to handle this part in TikZ. Any ideas would be much appreciated.
You can put your node and decorate a regular arrow going from (nodename.south west) to (nodename.south east) with a little extra adjustment (Check the manual page 49) but why do you need TikZ for this? Is there any disadvantage of the ones you mentioned?
@percusse: I guess there is no \xrightsquigarrow.
@Caramdir Aha, that explains it :)
Related: Squiggly arrows in tikz
this arrow is in unicode at U+27FF, so it should be in the stix and xits fonts. the reference i have available gives it the name \longrightsquigarrow although x would seem more "traditional" than long under the circumstances.
As percusse mentions in his comment, you can use a node and a decorated arrow; something like this:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations.pathmorphing,shapes}
\newcounter{sarrow}
\newcommand\xrsquigarrow[1]{%
\stepcounter{sarrow}%
\begin{tikzpicture}[decoration=snake]
\node (\thesarrow) {\strut#1};
\draw[->,decorate] (\thesarrow.south west) -- (\thesarrow.south east);
\end{tikzpicture}%
}
\begin{document}
\xrsquigarrow{text}\quad\xrsquigarrow{longer text}
\end{document}
The following code contains a new version of \xrsquigarrow using the zigzag decoration and \mathrel to be used in math-mode; it shows a comparison between \xrightarrow, \rightsquigarrow and \xrsquigarrow (some fine-tuning is still required, but I leave that to you):
\documentclass{article}
\usepackage{amsmath,amssymb}
\usepackage{tikz}
\usetikzlibrary{calc,decorations.pathmorphing,shapes}
\newcounter{sarrow}
\newcommand\xrsquigarrow[1]{%
\stepcounter{sarrow}%
\mathrel{\begin{tikzpicture}[baseline= {( $ (current bounding box.south) + (0,-0.5ex) $ )}]
\node[inner sep=.5ex] (\thesarrow) {$\scriptstyle #1$};
\path[draw,<-,decorate,
decoration={zigzag,amplitude=0.7pt,segment length=1.2mm,pre=lineto,pre length=4pt}]
(\thesarrow.south east) -- (\thesarrow.south west);
\end{tikzpicture}}%
}
\begin{document}
\[
A\xrightarrow{f} B\quad A\rightsquigarrow B\quad A\xrsquigarrow{f}B\quad A\xrsquigarrow{(f\circ g)\circ h}B
\]
\end{document}
This definition does not cover the case in which the arrow is to be used in super/sub-scripts.
Thanks, Gonzalo! This is very similar to what I had in mind. The only difference is the shape of the arrow that does not exactly look like \rightsquigarrow. This is important since I want to use the command in math mode and thus, it has to have a clean look. For example, $s \xsquigarrow{OR} t$ means a special operation between $s$ and $t$. The way you have defined the command does not produce a neat output in this setting. I am under impression that the wiggle type must have something to do with the "segment amplitude" and "segment length" of the arrow. Do you have any idea for fixing this?
@Ali in this case, use the zigzag decoration and appropriate values for amplitude and segment length; I'll give an example in some minutes.
I customized your command as follows:
\newcounter{sarrow} \newcommand\xrsquigarrow[1]{% \stepcounter{sarrow}% \begin{tikzpicture} \node[scale=0.5] (\thesarrow) {\mathstrut#1}; \draw[->,snake=zigzag,segment amplitude=.3mm,segment length=1.3mm,line after snake=.9mm] (\thesarrow.south west) -- (\thesarrow.south east); \end{tikzpicture}% }
This almost produces the right output in math mode, e.g., $s \xrsquigarrow{OR} t$. I am just wondering how I can add some free space between the math symbols and the arrow? Thanks again.
@Ali please see my updated answer.
Why is the counter needed for the node name? I seem to be able to replace the node name with a fixed value and everything still works.
| common-pile/stackexchange_filtered |
simple pattern matching in python
I am trying to write a basic interpreter in python.
So, I am at that point where I am trying to declare whether a string entered in command prompt is a method or variable type.
So not trying any fancy stuff..
s="12345" #variable
s ="foo()" method
s = "foo(1234)" method
What is a robust way to do this (for example.. robust for whitespaces ... throw error if syntax is not proper)
My code is pretty straightforward
s = s.strip()
params= s[s.find("(") + 1:s.find(")")] # find the params..
The above command works in case two and case three but for case 1.. it gives weird results..
What do you expect params to be for '12345'?
@Volatility: yes.. or nothing in case of 1st and 2nd case
@Volatility: basically.. these are the three cases which i am thinking to handle right now.. but i am having a lot of if elif statements..
A robust way is to write an actual parser, using something like ANTLR or pyparsing or whatever comes up under "python parser library".
@millimoose: oh .. didnt knew these.. thanks
the reason why you get the funny result in the first case is because your statement
in case of s = 123456
s[s.find("(") + 1:s.find(")")]
produces s[-1 + 1 : -1 ]
s[0 : -1 ] so you always miss the last character
Instead of parsing the string directly, you should first break it up into tokens, i.e. strings, bracket, numbers, operators, etc. Then, parse the sequence of tokens.
For the scenarios you are asked for i think this could do the trick
have a go
s[ 1+s.find("(") if s.find("(") > 0 else None : -1 if s.find(")") > 0 else None]
edit:
making a bit neater as suggested by Paul:
s[ 1+s.find("(") if '(' in s else None : -1 if ')' in s else None]
I think this would be clearer if it weren't crammed on to one line.
I think this would also be clearer if you used the more up-to-date idiom of if '(' in s instead of if s.find('(') > 0.
| common-pile/stackexchange_filtered |
How do I show $ 100^{n} $dominates $ n^{2.5} $
So i'm a little shaky on limits and I want to show
I could take the limit of$ \frac{x^{2.5}}{100^{x}} $
but it would get very messy with L'Hopitals rule is their
an easier way to show that this goes to 0 without having to do
a bunch of algebra?
You can show $100^n > n^{5/2}$ for every $n\ge 1$ by induction.
The ratio between successive terms is $100$ for $100^n$ and only $(1+\frac 1n)^{5/2}$ for $n^{5/2}$ so once the inequality holds it can never stop holding.
Remember that
$$\displaystyle\sum_{n} a_{n}< \infty \Rightarrow \lim\limits_{n\rightarrow \infty}a_{n}=0 $$
Observe that $\displaystyle\sum_{n} a_{n}< \infty$, since
$$\displaystyle \lim\limits_{n\rightarrow \infty}\frac{a_{n+1}}{a_{n}}=\lim\limits_{n\rightarrow \infty}\frac{1}{100}(1+\frac{1}{n})^{2.5}<1. $$
Upon taking logarithms from both sides you have $$ 2n> 2.5 \log n$$ or $$\frac {\log n}{n}<0.8$$ Note that $$\lim_{n\to \infty }\frac {\log n}{n} =0$$
Thus the statement is true.
| common-pile/stackexchange_filtered |
itunes JSON request in iOS returns an XML object
I want to access information from iTunes within an iOS app.
I am doing the regular http request (sending the parameters both as POST or directly in the URL)
The URL works, because if I use the browser, I get the expected result (in JSON format).
{
"resultCount":0,
"results": []
}
But within iOS, the JSONObjectWithData returns a null object.
After inspecting the data object, I found that the object returned is an XML object (that does not contain the required info, but instead a bunch of XML keys/values]
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/search"]];
NSError *directError;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&directError];
if (!directError) {
NSLog(@"%@", jsonDict);
} else {
NSLog(@"JSON Error: %@", directError.localizedDescription);
}
I looked into any possible POST parameter to force the response to be JSON, but didn't find anything.
Attached is a sample of the info contained in the data object (after XML parsing):
menus
key title
key Music
string url
key https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewGenre?id=34
string items
key title
key Free on iTunes
string url
Regards... enrique
Can you show what URL are you checking?
Itunes API returns json as you can see here:
https://itunes.apple.com/search?term=jack+johnson
The test URL is https://itunes.apple.com/search?term=pink-floyd
I used http://itunes.apple.com/search in the question, to highlight the short JSON response {
"resultCount":0,
"results": []
}. I tried http and https
I'm checking it and it works with that URL. If you want to check the data you have gotten, for example:
jsonDict[@"results"][0][@"trackName"]
I would guess that you're not explicitly asking for JSON, and many sites will return XML if you don't ask for JSON. (I forget exactly how you "ask" for JSON, though.)
UPDATE: I would also encourage you to not use the NSData dataWithURL method for fetching the contents since it triggers the request in synchronous manner. If you are requesting a lot of data then this will freeze the UI thread. For fetching you should almost always use asynchronous operations.
I am using the following code and it returns the JSON response which is later converted into the json object as shown below:
-(void) setup
{
NSString *iTunesURL = @"https://itunes.apple.com/search?term=pink-floyd";
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:iTunesURL] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"SUCCESS");
}] resume];
}
Hi @azamsharp... I did as you suggest (Launch the NSURLSession with dataTaskWithURL, but for some strange reason, the returned data object (that can be inspected) is not JSON but XML formatted... When I pass the NSData object through the NSJSONSerialization class, the returning object is nil. If I run it through the NSXMLParser, it gets a long list of keys, as shown in the attachment to the original question. I am puzzled here. Any help will be appreciated... A sample protect with the issue is posted here
Perhaps this will cause the response to be in JSON instead of XML:
NSUrlSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.HTTPAdditionalHeaders = @{ @"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" };
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
[[session dataTaskWithURL:[NSURL URLWithString:@"http://itunes.apple.com/search"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
}] resume];
That's using the default headers from Chrome. You could also try this:
sessionConfig.HTTPAdditionalHeaders = @{ @"Accept" : @"text/json" };
And if that doesn't work:
sessionConfig.HTTPAdditionalHeaders = @{ @"Accept" : @"text/json, application/json" };
I was also experiencing this issue and while the data being returned looks like XML, after analyzing the HTTP traffic, Apple is returning a redirect url that attempts to open iTunes on the device. By changing the user agent of NSMutableURLRequest, I was able to have JSON returned.
let session = NSURLSession.sharedSession();
let request = NSMutableURLRequest(URL:NSURL(string:"https://itunes.apple.com/search?term=wwg&country=us&media=software")!);
request.HTTPMethod = "GET";
//Be seen as the Mac OS
request.addValue("Paw/2.3.3 (Macintosh; OS X/10.11.4) GCDHTTPRequest", forHTTPHeaderField: "User-Agent")
//OR if you want to be seen as Chrome
//request.addValue("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36", forHTTPHeaderField: "User-Agent")
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
self.delegate?.didFinishSearching(data, response: response, error: error);
}
task.resume();
| common-pile/stackexchange_filtered |
TDirectory.Delete seems to be asynchronous
I have observed that calling DirectoryExists(x) immediately after calling TDirectory.Delete(x) returns true IF the folder to be deleted has few files in it AND the folder is open (in Total Commander).
In other words:
begin
TDirectory.Delete('x', true); <-- 'Delete' exited but the folder is still not fully deleted
if SysUtils.DirectoryExists('x')... <-- This returns true
end;
Is this a normal behavior?
The "solution" is this:
begin
TDirectory.Delete('x', true);
Sleep(1000); //wait for Delete to finish
if SysUtils.DirectoryExists('x')...
end;
Question: How do I know when the Delete is ready (how do I eliminate sleep)?
Note: Total Commander does not block the deletion of the folder (I guess) since the folder is deleted anyway (after a while).
Why would you do a call to DirectoryExists right after TDirectory.Delete anyway?
@R.Beiboer Maybe to check whether the directory has been deleted, since TDirectory.Delete lacks a result value.
@R.Beiboer: Defensive coding, to try and check that the directory is gone before doing something inconsistent with its existence, amongst other reasons.
I AM checking for folder existence! And DirectoryExists returns true, since the deletion is not complete.
@NAZCA: Yes, I understood that, I was just baffled by the "Why would you ..." comment.
If your intention is to empty a folder, you could call TDirectory.GetDirectories and call TDirectory.Delete for each directory. And then do a call to TDirectory.GetFiles and delete them all. That saves you the creation of a directory that already existed. and now you do not need the call to DirectoryExists anymore. Yes, it is more code for you to type, but it does what you need.
@R.Beiboer - Thanks. YOU ARE RIGHT. But that is not what I have asked. What I am trying to determine here is if this is a normal behavior and how trusted can this procedure be. Plus, is not that simple. When using GetFiles you need to do all kind of checks (set permissions do the files can be deleted, etc) and you need also to handle multi platform scenario.
What are you going to do? Do you want a program that works, or do you want to argue against the way MS designed the system. Just do what @R.Beiboer says.
Perhaps the Remarks section on the msdn page about RemoveDirectory gives us a clue? (https://msdn.microsoft.com/en-us/library/windows/desktop/aa365488(v=vs.85).aspx) The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed. This indicates that the call may return before the directory has actually been deleted.
@R.Beiboer - Thanks. That sheds some light into the issue. It also confirms that Delete is asynchronous (something not mentioned in Embarcadero's manual). This means that ALL code that uses Delete should use a Delay to prevent this kind of problems? PS: I will accept your answer if you post it.
@DavidHeffernan-Nope. I don't want to argue about why Windows was designed like that (at the time when I started this question I was not aware it is an OS-related thing). By discussing this here we might learn what other similar issue may arise from using Delete(). IT IS an interesting fact to learn that Delete is asynchronous. Right?
Take a look the msdn page about RemoveDirectory: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365488(v=vs.85).aspx
The Remarks section says:
The RemoveDirectory function marks a directory for deletion on close. Therefore, the directory is not removed until the last handle to the directory is closed.
So probably another process also has a handle to the directory (virus scanner?).
If you need to empty the directory, then empty it instead of deleting it and recreating it afterwards. In the end you always pay for a dirty hack ;)
Example of where deletion/recreate of folder could happen: Total Commander has a function that allows you to put IO operations in a queue. So, you could delete a folder, then recreate it (copy another older with same name in the place of the deleted folder). Probably there are also other scenarios in which you depend on a folder of being deleted.
| common-pile/stackexchange_filtered |
How to schedule task in flutter android
I am developing an app which requires scheduling a contract with three fields: time, date, and location. This contract is created with a specific time, date, and location input and is saved in a Firestore database. Once a user accepts the contract, it's activated.
The app needs to validate if the involved parties are present at the specified location at the correct date and time. In essence, the app will cross-verify the user's current location, time, and date with the contract details. If these match, a notification indicating "You Won" will be sent. Conversely, if the requirements are not met, a notification stating "You Lost" will be delivered. This verification will only occur once when the conditions are met.
I am seeking advice on the most suitable approach to accomplish this task in Flutter.
| common-pile/stackexchange_filtered |
Constructing objects based on enum
I have a class that builds objects based on an enum value. So several properties of these objects are based on some enum value, a type.
Option 1:
typedef NS_ENUM (NSUInteger, ViewType) {
VTHouse,
VTCar,
VTChair,
...
};
I have several methods that determine properties of the object based on the type.
- (NSURL*)urlForViewType:(ViewType)type {
NSURL *url = nil;
switch (type) {
case VTHouse: {
url = [NSURL URLWithString:@"House url"];
break;
}
case VTCar: {
url = [NSURL URLWithString:@"Car url"];
break;
}
case VTChair: {
url = [NSURL URLWithString:@"Chair url"];
break;
}
...
}
return url;
}
- (NSURL*)isSelectableViewType:(ViewType)type {
BOOL selectable = NO;
switch (type) {
case VTHouse: {
selectable = YES;
break;
}
case VTCar: {
selectable = YES;
break;
}
default: {
break;
}
}
return selectable;
}
- (NSURL*)colorForViewType:(ViewType)type {
UIColor *color = nil;
switch (type) {
case VTHouse: {
color = [UIColor redColor];
break;
}
case VTCar: {
color = [UIColor blueColor];
break;
}
case VTChair: {
color = [UIColor lightGrayColor];
break;
}
...
}
return color;
}
// And so on...
Then I have a method that the user of this class would call.
- (SpecialView*)specialViewForType:(ViewType)type {
NSURL *url = [self urlForViewType:type];
BOOL selectable = [self isSelectableViewType:type];
UIColor *color = [self colorForViewType:type];
...
return [SpecialView specialViewURL:url selectable:selectable color:color ...];
}
This all works very well but it gives me an uneasy feeling. Something just doesn't feel right. Perhaps it's all of the switches. I feel like there is a cleaner way to do this.
Another option that gets rid of most of the switches is something like;
Option 2:
- (SpecialView*)specialViewForType:(ViewType)type {
SpecialView *view = nil;
switch (type) {
case VTHouse: {
view = [self specialViewHouse];
break;
}
case VTCar: {
view = [self specialViewCar];
break;
}
case VTChair: {
view = [self specialViewChair];
break;
}
...
}
return view;
}
Where each of these methods already knows what properties to set for each type. But I prefer option 1.
So my question is; Does anyone have any suggestions on how to improve this kind of code?
You could replace switch case with dictionary and do simpler lookup. Certain switch case rules that produce the same result can be grouped too. Also if you have common protocol for views, you can implement color/selectable logic within each of subclasses to avoid switch-case.
Switches are subclasses from the last millenium. The easiest way to do this, is to have (private?) subclasses. Create the instance from that subclass.
@implementation BaseClass
+ (instancetype)newBaseClassForType:(ViewType)viewType
{
// Do a look-up to a array or a one-time switch to get the subclass
Class appropiateSubclass = …;
return [appropiateSubclass new];
}
Then, the subclasses can override the methods, i. e.:
@implementation HouswSubClass
- (BOOL)isSelectable { return YES; } // BTW: The return type was wrong
More important: Why do you have an enum?
I like and dislike the subclass idea. I have about 15 different types and possibly more in the future. So having a subclass just to have certain predetermined properties seems like it may be overkill, although well organized. I use an enum to simplify the interface for the view controller. So all it has to know is what type of view it wants. What would be better than an enum here?
Store the class, instead of a home made type. Keep in mind, that classes are objects in Objective-C. However, there is nothing wrong in having 15 subclasses. Likely they are private.
| common-pile/stackexchange_filtered |
How to print exception message in C++ with catch(...) {..}
This is the sample code
int main()
{
string S;
getline(cin, S);
try {
int val = stoi(S);
} catch(...) {
// cout << //exception message ; I want to print the exception message.
}
return 0;
}
Is it possible to print an exception message in this case ?. The message will show what kind of exception was thrown. I am trying this because , stoi() can throw multiple exceptions and I want to catch all of them and print the type of exception that was thrown, instead of using a separate catch block for each exception type.
All C++ library exceptions inherit from std::exception.
So the simplest thing to do is to catch a reference to it:
catch (const std::exception &e)
{
std::cout << "Caught " << e.what(); << std::endl;
}
This will catch all exceptions thrown by stoi.
I tried this. It seems that when exception is thrown the only output is stoi
input string: $#%$sto;'
output: Caught Exception: stoi . This will do fine. But I guess it can't be more specific unless I use the exact exception type in catch
what()'s message is implementation-defined and depends on the compiler. If all you need is a custom message for one or two specific exceptions it's possible to use dynamic_cast to check for them.
You simply cannot.
Catching with catch(...) has two properties.
It can capture anything thrown.
You don't have access to whatever has been caught.
Which means you cannot use .what() on the object caught, because you have no access to it.
If you have a warrant that std::exception will be thrown, then you could simply capture std::exception const&
catch(std::exception const& e){
std::cout<<"Exception: "<<e.what()<<std::endl;
}
| common-pile/stackexchange_filtered |
Regex Matching First URL with word
What I need:
I have a string like this:
Bike’s: http://website.net/bikeurl Toys: http://website.net/rc-cars
Calendar: http://website.net/schedule
I want to match the word I specify and the first URL after it. So if i specify the word as "Bike" i should get:
Bike’s: http://website.net/bikeurl
Or if possible only the url of the Bike word:
http://website.net/bikeurl
Or if I specify Toys I should get:
Toys: http://website.net/rc-cars
or if possible
http://website.net/rc-cars
What I am using:
I am using this regex:
(Bike)(.*)((https?|ftp):/?/?)(?:(.*?)(?::(.*?)|)@)?([^:/\s]+)(:([^/]*))?(((?:/\w+)*)/)([-\w.]+[^#?\s]*)?(\?([^#]*))?(#(.*))?
Result:
It is matching:
Bike’s: http://website.net/bikeurl Toys: http://website.net/rc-cars
I only want:
Bike’s: http://website.net/bikeurl
I am not a regex expert, I tried using {n} {n,} but it either didn't match anything or matches the same
I am using .NET C# so I am testing here http://regexhero.net/tester/
If you are sure the second word (the url) is always an URL, it would certainly make matching a lot easier, because you wouldn't have to verify the URL's format.
The regex I added works well only if each pair is on a different line.
@SwenKooij no I am not sure..
Here is another approach:
Bike(.*?):\s\S*
and here is an example how to get the corresponding URL-candidate only:
var inputString = "Bike’s: http://website.net/bikeurl Toys: http://website.net/rc-cars Calendar: http://website.net/schedule";
var word = "Bike";
var url = new Regex( word + @"(.*?):\s(?<URL>\S*)" )
.Match( inputString )
.Result( "${URL}" );
I need to make sure it is a URL because it is not always a URL
You could do the verification afterwards. First try to match the basic pattern and then verify that the matches are valid. A valid URL can't contain a space anyway.
I added example URL extraction logic. If you want to check the URL with RegEx then replace \S* part with pattern that matches your detailed URL requirements.
Alternatively you may use some .NET URL validator to validate URL-candidate value. RegEx for URL might be very tricky and error-prone...
I need to make sure it's a url because sometimes it may be Bike Shop: http://website.com and I need to select the website.com URL
If I understood your problem correctly. You need a generic regex that will select a url based on a word. Here is one that would select the url with bike in it:
(.(?<!\s))*\/\/((?!\s).)*bike((?!\s).)*
If you replace bike with any other word. It would select the respective URL's.
EDIT 1:
Based on your edit, here is one that would select based on the word preceding the URL:
(TOKEN((?!\s).)*\s+)((?!\s).)*
It would select the word + the URL eg.
(Bike((?!\s).)*\s+)((?!\s).)* would select Bike’s: http://website.net/bikeurl
(Toy((?!\s).)*\s+)((?!\s).)* would select Toys: http://website.net/rc-cars
(Calendar((?!\s).)*\s+)((?!\s).)* would select Calendar: http://website.net/schedule
If you want to make sure the string contains a URL, you can use this instead:
(TOKEN((?!\s).)*\s+)((?!\s).)*\/\/((?!\s).)*
It will make sure that the 2nd part of the string ie. the one that is supposed to contain a URL has a // in between.
Okay thanks a lot, how can I only select the URL ? Also sometimes the case might be: Bikes for Men: http://website.com and the code didn't work.
You need to have some definition of a URL right? Make it a part of the pattern. If website.com is a URL than abc.xyz or a.qqqq is not right! That is something you have to work out.
If you really need to make sure it's an url look at this:
Validate urls with Regex
Regex to check a valid Url
Here's another solution. I would separate the Bike's, Toys and Calendar in a dictionary and put the url as a value then when needed call it.
Dictionary<string, string> myDic = new Dictionary<string, string>()
{
{ "Bike’s:", "http://website.net/bikeurl" },
{ "Toys:", "http://website.net/rc-cars" },
{ "Calendar:", "http://website.net/schedule" }
};
foreach (KeyValuePair<string, string> item in myDic)
{
if (item.Key.Equals("Bike's"))
{
//do something
}
}
Hope one of my ideas helps you.
| common-pile/stackexchange_filtered |
Copy Text from Quicklook
In previous versions of OS X a plist addition to com.apple.finder (outlined here for instance) could be used to enable select and copy in quicklook previews.
This (hidden) feature doesn't appear to work anymore in Mavericks. Any workarounds? Or is the setting merely named differently?
Running
defaults write -g QLEnableTextSelection -bool true
and relaunching applications works for me. defaults write com.apple.finder QLEnableTextSelection -bool true only applies to Finder but defaults write -g QLEnableTextSelection -bool true applies to all applications.
If it doesn't work, see what Quick Look generator handles plain text files:
$ qlmanage -m|grep public.plain-text
public.plain-text -> /System/Library/QuickLook/Text.qlgenerator (555.0)
If it is not Text.qlgenerator, try to delete it and run qlmanage -r.
Deleting the third party generator and running qlmanage -r worked. Thanks.
Doesn't work for me with qlmanage -p on 10.8.5.
@Dominique Did you run defaults write -g QLEnableTextSelection -bool true? defaults write com.apple.Finder QLEnableTextSelection -bool true only applies to Finder and not to qlmanage.
Yes I did. I think this trick works when you use QuickLook from the Finder, but not when you call qlmanage -p from the command line.
Please notice that the activation of the "Text-Selection-In-Quicklook"-Feature could lead to the bug described in this question:
QuickLook blanks when displaying some images
| common-pile/stackexchange_filtered |
jquery pattern for multiple continuous ajax request
I have a for each loop with an array, for each element in the array I need to retrieve data from the server so I will make an ajax request per element and store the result in another array, I need to know when the last element in the array has been processed so I can display the data, is there a pattern or how could I do this without over complicating things which I think is what I'm doing
var array = ['a', 'b', 'c'],
arrayLength = array.length,
completed = 0;
Then, in the callbacks of your XHR,
if (completed == arrayLength) {
// All of them have finished.
}
completed++;
Alternatively, you state that you are adding the things to a new array. Assuming that when finished the arrays will be of equal length, you can change the check in the callback to (startArray.length == newArray.length).
Also, keep in mind if you are making XHR (assuming asynchronous) in a loop, they will all be trying to request at roughly the same time (I think), which may be an issue with performance. Consider writing a function which is called again on each individual request's callback, so the XHRs are made one at a time. Increment a counter so you can subscript the next array element in each call.
A continuation passing library that has a "parallel" mode will abstract this nicely. I'm using JooseX-CPS, also see its tutorial.
For each on success you hit, count up the successful results and then trigger an event.
For example:
var successfulReturns= 0;
$.ajax({
url:"",
success: function() {
successfulReturns++;
$(document).trigger("myapp.loadedComplete");
}
});
and then listen for your event
$(document).bind("myapp.loadedComplete", function() { } );
This lets you test the completion somewhere outside of the loop.
| common-pile/stackexchange_filtered |
How to get the ticker-id of the main symbol that is currently selected, in a multi-security chart
I have a watchlist-type chart, that is loading the tickers of a a fixed watchlist (top-10) via specific security calls. While processing the data for each security, I want to I get the name of currently select main-symbol of the chart.
Tried the syminfo.ticker function. It always refers to the symbol of the current security, and not the symbol selected in the main chart.
What do you mean by "symbol selected in the main chart"?
@vitruvius, I was referring to the the symbol which is currently selected as the chart's symbol. While for example, the chart shows the candles for XRP/USDT on the 15m time-frame, I call the security function top get BTC/USDT on a higher timeframe, in order to calculate some correlation-indicator.
After some deeper research, I am closing this question, by clarifying that in general, I found no problem in getting the tickerid of the main-chart's symbol, except of the case which I describe here: https://stackoverflow.com/questions/76278246/cannot-access-the-syminfo-tickerid-when-calling-request-security-with-dynamic
| common-pile/stackexchange_filtered |
Conditional statement to pull out last names from a list
I have a list of full names (titled "FullNames") and I am trying to pull out the last names. The problem is that some of the full names include middle names (e.g., some of the items in the list are "Craig Nelson" while others are "Craig T. Nelson") which stops me from using a simple list comprehension statement such as:
LastNames = ([x.split()[1] for x in FullNames])
Instead, I am trying to loop through the list with this code:
LastNames = []
for item in FullNames:
if '.' in FullNames:
LastNames.appened(item[2])
else:
LastNames.append(item[1])
print(LastNames)
However, I am just getting a bunch of letters back:
['u', 'a', 'e', 'i', 'o', 'a', 't', 'h', 'r', 'e', 'e', 'r', 'e', 'h', 'a', 'i', 't', 'a', 'r', 'a', 'i', 'e', 'o', 'e', 'e', 'a', 'r', 'o', 'a', 'y', 'i', 'e', 'e', 'o', 'o', 'e', 'e', 'a', 'i', 'i', 'e', 'm', 'a', 'a', 'a', 'n', 'e', 'a', 'r']
Is there a simple way around this?
use
LastNames = ([x.split()[-1] for x in FullNames])
also you should write if '.' in item: instead of if '.' in FullNames:
since last name is always at the end of the name, so you need to get the last element after split for the last name, so [x.split()[-1] for x in FullNames] will give you last name
Thanks! One follow up if it's alright, sometimes there are items within the list such as "Craig T. Nelson, MBA" .... is there a way to quickly modify to pull the last name out of something like that, or would that require manual repair?
This approach doesn't support double barrelled last names at all - i.e "Craig revel horwood"
def get_last(name):
return name.split(' ')[-1].split('.')[-1]
full_names = ["Craig T. Nelson", "Craig Nelson"]
output = list(map(get_last, full_names))
print(output)
#['Nelson', 'Nelson']
Thanks! One follow up if it's alright, sometimes there are items within the list such as "Craig T. Nelson, MBA" .... is there a way to quickly modify to pull the last name out of something like that, or would that require manual repair?
@am.96 Yes, one option is to use name.split(',')[0] first and then do the rest
thank you @aminrd! this fixed everything.
| common-pile/stackexchange_filtered |
Error sending form fields through jquery ajax
I am having a problem sending the dataString to the server. Aparently it is not pulling the values correctly from the form. Below is my jquery and my php.
$(document).ready(function() {
$("#submitForm").live('click', function() {
updateUserInfo();
});
var birthdate = $("#birthdate");
var sex = $("#sex");
var interestedIn = $("#interestedIn");
var relationshipStatus = $("#relationshipStatus");
var knownLanguages = $("#knownLanguages");
var religiousViews = $("#religiousViews");
var politicalViews = $("#politicalViews");
var aboutMe = $("#aboutMe");
var mobilePhone = $("#mobilePhone");
var neighborhood = $("#neighborhood");
var website = $("#website");
var email = $("#email");
var dataString = birthdate + sex + interestedIn + relationshipStatus + knownLanguages + politicalViews + aboutMe + mobilePhone + neighborhood + website + email;
function updateUserInfo() {
jQuery.ajax({
type: "POST",
dataType: "JSON",
url: "<?=base_url()?>index.php/regUserDash/updateUserInfo",
data: dataString,
json: {userInfoUpdated: true},
success: function(data) {
if(data.userInfoUpdated == true) {
alert("hello");
}
}
});
}
});
My PHP:
public function updateUserInfo() {
$userid = $this->session->userdata('userid');
$birthdate = $this->input->post("birthdate");
$sex = $this->input->post("sex");
$interestedIn = $this->input->post("interestedIn");
$relationshipStatus = $this->input->post("relationshipStatus");
$languages = $this->input->post("languages");
$religiousViews = $this->input->post("religiousViews");
$politicalViews = $this->input->post("politicalViews");
$aboutMe = $this->input->post("aboutMe");
$mobilePhone = $this->input->post("mobilePhone");
$neighborhood = $this->input->post("neighborhood");
$websites = $this->input->post("websites");
$email = $this->input->post("email");
$this->db->query("INSERT IGNORE INTO user_info (birthdate, sex, interestedIn, relationshipStatus, Languages, religiousViews, politicalViews, aboutMe, mobilePhone, neighborhood, websites, email, userid)
VALUES('{$birthdate}', '{$sex}', {$relationshipStatus}', '{$languages}, {$religiousViews}', '{$politicalViews}', {$aboutMe}', '{$mobilePhone}' {$neighborhood}', '{$websites}', {$email}', '{$userid}')");
echo json_encode(array('userInfoUpdated' => true));
}
Use .val() to get the value of the element.
And change your dataString to:
var dataString = {'birthdate' : birthdate, 'sex' : sex, 'interestedIn' : interestedIn, 'relationshipStatus' : relationshipStatus, 'knownLanguages' : knownLanguages, 'politicalViews' : politicalViews, 'aboutMe' : aboutMe, 'mobilePhone' : mobilePhone, 'neighborhood' : neighborhood, 'website' : website, 'email' : email};
From api.jquery.com:
Sorry for the late reply, but it is still not working. Here is my error: http://i50.tinypic.com/2bp750.png. If you notice it isn't even passing through json.
Everything is running correctly. This is odd. here is my PHP if that might help any: http://pastebin.com/R7tjfkDx.
@MichaelGrigsby check Network tab in Chrome and look for the request which JQuery sends. Is it there? If yes, look through request headers and find Form data. What is there?
Only the default values from the select boxes are being passed
@MichaelGrigsby Got it, select boxes, thats what causing the problem. E.g. $('#sex') is a select box, and to obtain selected value you should use :selected. var sex = $('#sex :selected').val()
let us continue this discussion in chat
Okay. Thanks man. Give me a little while. I'm not sitting in front of my computer at this moment.
The code $("#birthdate"); will return an element with id #birthdate but not it's value. use val function to get the value in it. like var birthdate = $("#birthdate").val();
| common-pile/stackexchange_filtered |
VisualStudio Code is completly black when started
When i started VSCode it is completely black and you can't see anything. But when i enter something and exit the program it asks if you want to save the changes. And the words I entered were saved! Everything is working but the screen is just completely black.
Does anyone have any idea how to solve it?
It looks like it's a GPU issue that can be fixed by running VS Code from command line and passing in the disable-gpu flag:
code --disable-gpu
Context: https://code.visualstudio.com/Docs/supporting/faq#_vs-code-main-window-is-blank
After using this disable gpu flag it still shows the blank screen, what to do?
| common-pile/stackexchange_filtered |
How to update the style of all the items which are iterated using *ngFor in Angular
How do I apply style to all the items in the list which are iterated using *ngFor when clicked on a button which is outside the list.
<button (click)="markAllAsChecked();">Mark All as Checked</button>
<ion-list>
<div *ngFor="let item of items">
<ion-item (click)="this.item.checked = !this.item.checked;">
<div class="item" [ngStyle]="{background: item.checked ? 'green': 'red'}">
{{item.name}}
</div>
</ion-item>
</div>
</ion-list>
I wanted all the items background color to be turned to green when clicked on Mark All as Checked button.
I created a working example using Stackblitz. Could anyone please help?
Your need to iterate on each item and make checked to true.
markAllAsChecked(){
this.items.forEach(item => item.checked = true);
}
and if you want to toggle background colour on same button then,
markAllAsChecked(){
this.items.forEach(item => item.checked = !item.checked);
}
here is the working link.
Thank you! I used .map instead of forEach for performance reasons. Here's what I did
this.items.map(item => item.checked = true);
use [ngClass] instead of [ngStyle]
<div class="item redBackgroundClass" [ngStyle]="{'greenBackgroundClass': item.checked}">
here keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed
| common-pile/stackexchange_filtered |
How do I extract subpath neatly accounting for root and no root folders on java
I have a Path object and a String object, the Path object represents part of the starting path represented by the filename
e.g for the filename /Music/Beatles/Help.mp3 the Path object may be
/
/Music
/Music/Beatles
this simple method returns the part of the path minus the basefolder
public String getPathRemainder(Path path, String filename)
{
if(baseFolder.getNameCount()==0)
{
return song.getFilename().substring(baseFolder.toString().length());
}
else
{
return song.getFilename().substring(baseFolder.toString().length()+File.separator.length());
}
i.e
Music/Beatles/Help.mp3
Beatles/Help.mp3
Help.mp3
but although simple its rather messy as I have to account for the fact that if the base folder is a root folder it ends with '/' (on unix) but not none root paths.
Im sure there is a neater approach, but I cant see it.
Using java.nio available since Java 7:
Path file = Paths.get("/Music/Beatles/Help.mp3");
Path dir1 = Paths.get("/");
Path dir2 = Paths.get("/Music");
Path dir3 = Paths.get("/Music/Beatles");
System.out.println(dir1.relativize(file));
System.out.println(dir2.relativize(file));
System.out.println(dir3.relativize(file));
You get:
Music/Beatles/Help.mp3
Beatles/Help.mp3
Help.mp3
| common-pile/stackexchange_filtered |
Apply table() function to same column name in multiple dataframes - r
I'm trying to apply the table() function to the same column in several data frames. I'm sure there is a more efficient way than just typing each line of code and changing out the data frame.. This is what I've been doing.. (data frames are abram, arlington, blanche, carson, diamond; column name is Admin_Supp)
table(abram$Admin_Supp)
table(arlington$Admin_Supp)
table(blanche$Admin_Supp)
table(carson$Admin_Supp)
table(diamond$Admin_Supp)
I tried to play with lapply() but I couldn't figure it out. Any help would be greatly appreciated ~ thanks!
Place the extracted columns from the datasets in a list and apply table by looping over the list with lapply
lapply(list(abram$Admin_Supp, arlington$Admin_Supp, blanche$Admin_Supp,
carson$Admin_Supp, diamond$Admin_Supp), table)
Or place the datasets in the list, extract the column by looping and apply table
lapply(list(abram, arlington, blanche, carson, diamond), function(x)
table(x$Admin_Supp))
If we are interested only in data.frame objects created in the global env, we could also loop over the environment and extract the column only if it is data.frame
Filter(length, eapply(environment(), \(x)
if(is.data.frame(x)) table(x$Admin_Supp)))
Thank you so much! Do you know if there is a way for me to extract the same column from all the datasets without having to type it out after each data frame name? (i.e. I would like to just indicate which column once... not sure it possible) thanks again ~
@CatherineTiczon You could place those dataset in the list, extract by looping (as in the update)
| common-pile/stackexchange_filtered |
In Symfony2 where do I put e.g. TCPDF?
I'm on Symfony 2.0 and understood that third-party libraries go in /vendor. I have two third party classes I'm using, one is TCPDF and another is a Paypal class. Neither have formal Symfony2 Bundles.
So I followed the instructions here which namespaces them and makes them usable inside /vendor:
Add third party libraries to Symfony 2
This works and I can access them from my Controllers. However I'm rethinking if that's the right thing. Whenever I do..
php bin/vendors install --reinstall
..those custom classes disappear because they don't have a Git repo in 'deps'. This has caused real problems e.g. when trying to deploy on e.g. PagodaBox. I get the strong instinct that this code while 'third-party' belongs closer to the code of my app.
If that's true, should it:
Sit next to my Controllers in src/MyCompany/MyBundle/Controller/tcpdf.php
Be with my other custom-written services in src/MyCompany/MyBundle/DependencyInjection/tcpdf.php
Go in its own directory under my bundle: src/MyCompany/MyBundle/TCPDF/tcpdf.php
If I move these two classes from /vendor to one of the above, would I access it from a Controller with a 'use' statement, or would I need to define it in 'services.yml'?
I hope this isn't so much a matter of discussion or opinion but some guidance I've missed or best practise I'm unaware of that a more experienced Symfony2 dev would know.
Would it be sensible to switch to Composer even before Symfony 2.1 is ready?
Thanks for reading.
Maybe you should consider using open source bundles such as this TCPDF bundle: https://github.com/ioalessio/IoTcpdfBundle and this payments bundle: https://github.com/schmittjoh/JMSPaymentPaypalBundle
IoTcpdf seems mainly a Tcpdf bridge to output Twig templates as PDFs: not something I need. It doesn't include Tcpdf within itself, it says put Tcpdf manually in your vendor dir, which is what I'm trying to avoid. Matt's suggestion is more directly relevant. I looked at JMSPayment today and while I'd love to use it someday, it has a lot of dependencies and the documentation doesn't provide details on how to use it as a straightforward interface to the Paypal API.
If you're using deps to manage vendor libraries then you should add the git repo's for those libraries there.
For TCPDF you can use:
[TCPDF]
git=git://tcpdf.git.sourceforge.net/gitroot/tcpdf/tcpdf
target=/tcpdf
If you have other libraries that aren't in a public repo then you may want to commit them to your own repo.
The same would hold true for Composer. Just the syntax for adding non-packagist repo's is different.
Matt: thanks for the answer.
How did you get that Git repo for TCPDF. Did you construct the URL yourself from http://sourceforge.net/apps/trac/sourceforge/wiki/Git ? Is it going to be better to use that than https://github.com/tcpdf/tcpdf ? The other library (Paypal, closed-source for which I bought a license) I've made edits on, so I think I'll include in my own source tree as a service (in DependencyInjection) unless you think otherwise.
The SourceForge one is where the project is developed. The GitHub one is just a mirror. Either would be fine to use.
Just to complete Matt's answer, once you've included TCPDF in your deps and updated vendors, the next step is: IN app/autoload.php ADD 'TCPDF' => DIR.'/../vendor/tcpdf', TO $loader->registerPrefixes(array()); You can then use it in a Controller or Service e.g. $pdf = new \TCPDF();
..which worked for me on local but not when using Capifony with symlinked directories on the live server. For what solved that, see here: http://stackoverflow.com/questions/9253477/autoload-classes-with-zend-based-naming-convention-or-no-convention-at-all-with/10901809#10901809
| common-pile/stackexchange_filtered |
I am sending attachment mail with send grid in codeigniter
I am sending attachment mail with send grid in codeigniter . Mail send successfully But attachment file could not show after download . my code:-
public function test() {
$attach = base_url()."/uploads/a.png";
<EMAIL_ADDRESS><EMAIL_ADDRESS>'sss sub', 'ss msg',$attach, 'dss.png');
}
Send grid API
function SendMail($from, $email, $subject, $message, $attach = '', $filename = '')
{
$url = 'https://api.sendgrid.com/';
$user = 'XXXXXX';
$pass = 'XXXXXX';
if ($attach <> '' && $filename <> '') {
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => $email,
'fromname' => $from,
'from' => $from,
'subject' => $subject,
'html' => $message,
'files[' . $filename . ']' => new \CurlFile($attach),
'files[' . $filename . ']' => '@' . $attach,
);
} else {
$params = array(
'api_user' => $user,
'api_key' => $pass,
'to' => $email,
'fromname' => $from,
'from' => $from,
'subject' => $subject,
'html' => $message);
}
$request = $url . 'api/mail.send.json';
$session = curl_init($request);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $params);
curl_setopt($session, CURLOPT_HEADER, false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
//curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// obtain response
$response = curl_exec($session);
curl_close($session);
return true;
}
You need attach file differently, passing more parameters into Curlfile constructor like
new CurlFile('filename.png', 'image/png', 'filename.png')
Check these links a and b
| common-pile/stackexchange_filtered |
How can I remedy this problem? Please see the terminal log below
I am trying to do apt autoremove, apt --fix-broken install, apt upgrade or apt install -f and running into these kind of errors. It looks like a vicious cycle I cannot come out of. Please help a complete linux n00b.
Output of sudo apt-get update
Get:1 file:/var/cuda-repo-ubuntu2204-11-7-local InRelease [1,575 B]
Get:1 file:/var/cuda-repo-ubuntu2204-11-7-local InRelease [1,575 B]
Get:2 http://security.ubuntu.com/ubuntu jammy-security InRelease [110 kB]
Hit:3 http://archive.ubuntu.com/ubuntu jammy InRelease
Hit:4 http://archive.ubuntu.com/ubuntu jammy-updates InRelease
Hit:5 http://archive.ubuntu.com/ubuntu jammy-backports InRelease
Fetched 110 kB in 1s (202 kB/s)
Reading package lists... Done
Output of sudo apt-get upgrade:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
cuda-drivers-515 : Depends: nvidia-compute-utils-515 (>= 515.43.04) but it is not installed
Depends: nvidia-utils-515 (>= 515.43.04) but it is not installed
nvidia-driver-515 : Depends: nvidia-compute-utils-515 (= 515.43.04-0ubuntu1) but it is not installed
Depends: nvidia-utils-515 (= 515.43.04-0ubuntu1) but it is not installed
Recommends: libnvidia-compute-515:i386 (= 515.43.04-0ubuntu1)
Recommends: libnvidia-decode-515:i386 (= 515.43.04-0ubuntu1)
Recommends: libnvidia-encode-515:i386 (= 515.43.04-0ubuntu1)
Recommends: libnvidia-fbc1-515:i386 (= 515.43.04-0ubuntu1)
Recommends: libnvidia-gl-515:i386 (= 515.43.04-0ubuntu1)
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).
Output of apt --fix-broken install
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
javascript-common libaccinj64-11.5 libbabeltrace1 libboost-regex1.74.0 libcub-dev libcublas11 libcublaslt11 libcudart11.0 libcufft10 libcufftw10 libcupti-dev libcupti-doc libcupti11.5 libcurand10
libcusolver11 libcusolvermg11 libcusparse11 libdebuginfod-common libdebuginfod1 libdouble-conversion3 libdw1 libegl-dev libgl-dev libgl1-mesa-dev libgles-dev libgles1 libglvnd-core-dev libglvnd-dev
libglx-dev libipt2 libjs-jquery libjs-sphinxdoc libjs-underscore libnppc11 libnppial11 libnppicc11 libnppidei11 libnppif11 libnppig11 libnppim11 libnppist11 libnppisu11 libnppitc11 libnpps11 libnvblas11
libnvjpeg11 libnvrtc-builtins11.5 libnvrtc11.2 libnvtoolsext1 libnvvm4 libopengl-dev libpcre2-16-0 libpthread-stubs0-dev libpython3.10 libqt5core5a libqt5dbus5 libqt5network5 libsource-highlight-common
libsource-highlight4v5 libtbb-dev libtbb12 libtbbmalloc2 libthrust-dev libvdpau-dev libx11-dev libxau-dev libxcb-xkb1 libxcb1-dev libxdmcp-dev libxkbcommon-x11-0 node-html5shiv nsight-compute
nsight-compute-target nvidia-cuda-gdb nvidia-cuda-toolkit-doc nvidia-opencl-dev ocl-icd-opencl-dev opencl-c-headers opencl-clhpp-headers openjdk-8-jre qttranslations5-l10n x11proto-dev xorg-sgml-doctools
xtrans-dev
Use 'apt autoremove' to remove them.
The following additional packages will be installed:
nvidia-compute-utils-515 nvidia-utils-515
The following NEW packages will be installed:
nvidia-compute-utils-515 nvidia-utils-515
0 upgraded, 2 newly installed, 0 to remove and 6 not upgraded.
7 not fully installed or removed.
Need to get 0 B/608 kB of archives.
After this operation, 1,966 kB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 file:/var/cuda-repo-ubuntu2204-11-7-local nvidia-compute-utils-515 515.43.04-0ubuntu1 [271 kB]
Get:2 file:/var/cuda-repo-ubuntu2204-11-7-local nvidia-utils-515 515.43.04-0ubuntu1 [337 kB]
debconf: delaying package configuration, since apt-utils is not installed
(Reading database ... 105126 files and directories currently installed.)
Preparing to unpack .../nvidia-compute-utils-515_515.43.04-0ubuntu1_amd64.deb ...
Unpacking nvidia-compute-utils-515 (515.43.04-0ubuntu1) ...
dpkg: error processing archive /var/cuda-repo-ubuntu2204-11-7-local/./nvidia-compute-utils-515_515.43.04-0ubuntu1_amd64.deb (--unpack):
unable to make backup link of './usr/bin/nvidia-cuda-mps-control' before installing new version: Invalid cross-device link
dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)
Preparing to unpack .../nvidia-utils-515_515.43.04-0ubuntu1_amd64.deb ...
Unpacking nvidia-utils-515 (515.43.04-0ubuntu1) ...
dpkg: error processing archive /var/cuda-repo-ubuntu2204-11-7-local/./nvidia-utils-515_515.43.04-0ubuntu1_amd64.deb (--unpack):
unable to make backup link of './usr/bin/nvidia-debugdump' before installing new version: Invalid cross-device link
dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)
Errors were encountered while processing:
/var/cuda-repo-ubuntu2204-11-7-local/./nvidia-compute-utils-515_515.43.04-0ubuntu1_amd64.deb
/var/cuda-repo-ubuntu2204-11-7-local/./nvidia-utils-515_515.43.04-0ubuntu1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)
Output of sudo dpkg --configure -a
dpkg: dependency problems prevent configuration of cuda-drivers-515:
cuda-drivers-515 depends on nvidia-compute-utils-515 (>= 515.43.04); however:
Package nvidia-compute-utils-515 is not installed.
cuda-drivers-515 depends on nvidia-utils-515 (>= 515.43.04); however:
Package nvidia-utils-515 is not installed.
dpkg: error processing package cuda-drivers-515 (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cuda-drivers:
cuda-drivers depends on cuda-drivers-515 (= 515.43.04-1); however:
Package cuda-drivers-515 is not configured yet.
dpkg: error processing package cuda-drivers (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of nvidia-driver-515:
nvidia-driver-515 depends on nvidia-compute-utils-515 (= 515.43.04-0ubuntu1); however:
Package nvidia-compute-utils-515 is not installed.
nvidia-driver-515 depends on nvidia-utils-515 (= 515.43.04-0ubuntu1); however:
Package nvidia-utils-515 is not installed.
dpkg: error processing package nvidia-driver-515 (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cuda-runtime-11-7:
cuda-runtime-11-7 depends on cuda-drivers (>= 515.43.04); however:
Package cuda-drivers is not configured yet.
dpkg: error processing package cuda-runtime-11-7 (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cuda-demo-suite-11-7:
cuda-demo-suite-11-7 depends on cuda-runtime-11-7; however:
Package cuda-runtime-11-7 is not configured yet.
dpkg: error processing package cuda-demo-suite-11-7 (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cuda-11-7:
cuda-11-7 depends on cuda-runtime-11-7 (>= 11.7.0); however:
Package cuda-runtime-11-7 is not configured yet.
cuda-11-7 depends on cuda-demo-suite-11-7 (>= 11.7.50); however:
Package cuda-demo-suite-11-7 is not configured yet.
dpkg: error processing package cuda-11-7 (--configure):
dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of cuda:
cuda depends on cuda-11-7 (>= 11.7.0); however:
Package cuda-11-7 is not configured yet.
dpkg: error processing package cuda (--configure):
dependency problems - leaving unconfigured
Processing triggers for dbus (1.12.20-2ubuntu4.1) ...
Errors were encountered while processing:
cuda-drivers-515
cuda-drivers
nvidia-driver-515
cuda-runtime-11-7
cuda-demo-suite-11-7
cuda-11-7
cuda
When I try sudo apt-get remove --purge nvidia-cuda-toolkit
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).
Terminal log
This appears to be essentially the same issue as CUDA install issue: Invalid cross-device link
@steeldriver I tried and getting
´dpkg: error: cannot access archive '/var/cache/apt/archives/libnvidia-compute-450_450.36.06-0ubuntu1_amd64.deb': No such file or directory´
Updated the post with the outputs
Does this answer your question? How do I resolve unmet dependencies after adding a PPA?
Try running sudo dpkg --configure -a
You got 3 ways to fix this:
#1 Reconfigure dpkg Database:
sudo dpkg --configure -a
This command reconfigures packages that have been unpacked but not necessarily installed. An interruption at the wrong time can cause this database to become corrupt. This is especially helpful if you were running installation and the process was interrupted.
#2 Force-Install the Software:
sudo apt-get install -f
The -f option means fix-broken. It repairs any broken dependencies in your package manager.
#3 Remove Bad Software Package:
sudo apt-get remove --purge package_name
The --purge option makes the system remove config files in addition to uninstalling them. This helps get rid of all traces of the offending software.
Please check the outputs of these commands. What else can I try?
| common-pile/stackexchange_filtered |
How can I iterate through each pixel in a .gif image?
I need to step through a .gif image and determine the RGB value of each pixel, x and y coordinates. Can someone give me an overview of how I can accomplish this? (methodology, which namespaces to use, etc.)
This is a complete example with both methods, using LockBits() and GetPixel(). Besides the trust issues with LockBits() things can easily get hairy.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace BitmapReader
{
class Program
{
static void Main(string[] args)
{
//Try a small pic to be able to compare output,
//a big one to compare performance
System.Drawing.Bitmap b = new
System.Drawing.Bitmap(@"C:\Users\vinko\Pictures\Dibujo2.jpg");
doSomethingWithBitmapSlow(b);
doSomethingWithBitmapFast(b);
}
public static void doSomethingWithBitmapSlow(System.Drawing.Bitmap bmp)
{
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
Color clr = bmp.GetPixel(x, y);
int red = clr.R;
int green = clr.G;
int blue = clr.B;
Console.WriteLine("Slow: " + red + " "
+ green + " " + blue);
}
}
}
public static void doSomethingWithBitmapFast(System.Drawing.Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect,
System.Drawing.Imaging.ImageLockMode.ReadOnly,
bmp.PixelFormat);
IntPtr ptr = bmpData.Scan0;
int bytes = bmpData.Stride * bmp.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr,
rgbValues, 0, bytes);
byte red = 0;
byte green = 0;
byte blue = 0;
for (int x = 0; x < bmp.Width; x++)
{
for (int y = 0; y < bmp.Height; y++)
{
//See the link above for an explanation
//of this calculation
int position = (y * bmpData.Stride) + (x * Image.GetPixelFormatSize(bmpData.PixelFormat)/8);
blue = rgbValues[position];
green = rgbValues[position + 1];
red = rgbValues[position + 2];
Console.WriteLine("Fast: " + red + " "
+ green + " " + blue);
}
}
bmp.UnlockBits(bmpData);
}
}
}
I have never been able to implement any type of image processing using Get/SetPixel. It is always way too slow, even for trivial operations like increases overall brightness.
It's always too slow when your images are big. For icon sized images it's perfectly suitable :-)
Hi, is there a way to modify this so that it doesn't need to assume 24bppRgb format, but rather modify the formula based on bmp.PixelFormat
@hofnarwillie You can replace the hardcoded 3 in int position = (y * bmpData.Stride) + (x * 3); by Image.GetPixelFormatSize(bmpData.PixelFormat)/8.
@VinkoVrsalovic Do you think it is worth to replace the hardcoded 3 below the 24bpp comment by Image.GetPixelFormatSize(bmpData.Pixelformat)/8? I found your answer excellent and immediately useful, but I needed that safeguard because I was getting error when loading grayscale PNGs...
I don't understand why the order of bytes is "blue-green-red" when the format is R-G-B. I saw the comment about the "link above" but I see no link above.
Why is this the accepted answer if the OP was asking about each frame in gif image and this answer is about each pixel in jpg (or other Bitmap format). I don't see how this works with animated gif images
You can load the image using new Bitmap(filename) and then use Bitmap.GetPixel repeatedly. This is very slow but simple. (See Vinko's answer for an example.)
If performance is important, you might want to use Bitmap.LockBits and unsafe code. Obviously this reduces the number of places you'd be able to use the solution (in terms of trust levels) and is generally more complex - but it can be a lot faster.
Wow. I was looking for this a few weeks ago. Definitely will look more into the example. Thank you for the link.
It is quite a lot more complex (and quite a lot faster indeed), you have to take into consideration the PixelFormat of the image, check if the data is or is not padded and skip some values accordingly. The MSDN example is not particularly helpful as it doesn't mention any of this.
If your gif isn't animated use this:
Image img = Image.FromFile("image.gif");
for (int x = 0; x < img.Width; x++)
{
for (int y = 0; y < img.Height; y++)
{
// Do stuff here
}
}
(Untested)
Otherwise use this to loop through all the frames, as well:
Image img = Image.FromFile("animation.gif");
FrameDimension frameDimension = new FrameDimension(img.FrameDimensionsList[0]);
int frames = img.GetFrameCount(frameDimension);
for (int f = 0; f < frames; f++)
{
img.SelectActiveFrame(frameDimension, f);
for (int x = 0; x < img.Width; x++)
{
for (int y = 0; y < img.Height; y++)
{
// Do stuff here
}
}
}
(Untested)
I upvoted this answer because it's the only answer that correctly mentions SelectActiveFrame for animated GIFs.
| common-pile/stackexchange_filtered |
Not able to understand "Attention" para from USN-2872-2: Linux kernel (Wily HWE) vulnerability
From USN-2872-2 ,
I am not able to understand what does Attention para means.
The paragraph is
ATTENTION: Due to an unavoidable ABI change the kernel updates have
been given a new version number, which requires you to recompile and
reinstall all third party kernel modules you might have installed.
Unless you manually uninstalled the standard kernel metapackages
(e.g. linux-generic, linux-generic-lts-RELEASE, linux-virtual,
linux-powerpc), a standard system upgrade will automatically perform
this as well.
Can you any one please explain me this in simple terms ?
Also how can I update my Kernel package so that my system will be secure from this latest Kernel vulnerability.
This message just explains that there's a new version number for the kernel which has been patched. It isn't something you need to worry about unless you have previously loaded third-party modules into your kernel manually. Any kernel modules loaded with dkms (such as virtualbox) will essentially take care of themselves.
Doing the normal update/upgrade procedure will ensure you have the newest, most secure version of your kernel.
With a desktop system, use the Software Updater package as per normal to install updates.
If you're using a server system, issue the following commands, with a user who has sudo privileges (the first user you created will have these by default).
sudo apt-get update
Followed by:
sudo apt-get dist-upgrade
You will need to reboot your machine to use the updated kernel.
| common-pile/stackexchange_filtered |
How to concatenate strings to a array in a loop?
I have a table with food ingredients, suppliers, dates, and article numbers, and need a script to automatically create calendar events when the specifications need to be renewed (dates). I had a working script but as we have more and more ingredients by the same suppliers my calendar is getting too crowded. Some ingredients are by the same supplier and need renewing on the same date so I want to concatenate their article numbers into an array and use that as a calendar event description. I struggle to set up the loops and the array. My thinking was to check if the next supplier matches and the next date matches and if so concatenate the description into the array.
The following code would only append one description and I think I'd need another loop.
function createEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("name of sheet");
var lastrow = sheet.getLastRow();
var range = sheet.getRange("A2:D"+lastrow);
var cal = calendarApp.getCalendarById("calId");
range.sort({column: 2, ascending: true});
var data = range.getValues()
for (var i = 0; i < data.length(); i++){
var name = data[i][0] //event name
var supplier = data[i][1] //supplier
var nextsupplier = data[i+1][1]
var date = new Date (data[i][2]) //event date
var nextdate = new Date (data[i+1][2]);
var desc = data [i][3] //event description
if (supplier == nextsupplier){
if (nextdate == date){
append desc from i+ to i
} else {
create event from i with appended desc
}
} else {
var event = cal.createAllDayEvent(name, date, {description: desc});
Logger.log('Event ID: ' + event.getTitle());
}
}
}
| common-pile/stackexchange_filtered |
How can the Android OS identify AndroidX fragments if they are obfuscated?
I am doing a reverse-engineering work related to Android fragments. I found out in many apks (decompiled with apktool, dexToJar, ...), the androidx.fragment.app.Fragment class is obfuscated. In most of the cases the class members are obfuscated, while in some minor cases, the class name is even obfuscated. I am wondering in these cases, how can the Android OS identify AndroidX fragments in an app at runtime?
I don't think Android requires to know which class a Fragment [implementation] is. It just loads the class the the Fragment manager (which is also included in the app and thus knows which classes to use) does the rest.
@Robert I see your points, but what if the FragmentManager class is also obfuscated (which is also very common)?
As long as it is inside the app all class references are still the same even if they have obfuscated names. So the FragmentManager knows which class is now the androidx.fragment.app.Fragment class no matter what name it has and in which package it is located.
@Robert thanks for your answer. I see your points but I am now again wondering how Android accesses the obfuscated FragmentManager...Anyway, I guess there are some mechanisms. Your answer already solves the question, thanks.
| common-pile/stackexchange_filtered |
Trouble printing variables from other files
Description
I have a script → report_creator.py which will need some variables from another python script → extracted_data.py.
The number of variables from extracted_data.py will always be based on the system it extracts data from (if the system has 1 server, we will have 1 variable, if the system has 2 servers, we will have 2 variables and so on). You can never know the exact number of variables the extracted_data.py will have.
Let's say we have extracted data from a system with 2 servers and the extracted_data.py file looks something like:
parameterx_server1 = "value"
parameterx_server2 = "another value"
What I have: → report_creator.py:
import os
import extracted_data
#Extract all variables names starting with parameterx from extracted_data.py and store them into a list
variables = os.popen("""cat extracted_data.py | grep '^parameterx_*' | awk '{print $1}'""").read().strip()
variables = variables.split("\n")
#After the execution of the command, the list looks like this:
# variables = ['parameterx_server1', 'parameterx_server2']
Problem
The script now has a list containing all the parameterx variables from extracted_data.py:
variables = ['parameterx_server1', 'parameterx_server2']
The only thing remaining is to get the corresponding value of each variable from the variables list from the extracted_data.py, something like:
print extracted_data.parameterx_server1
I tried something like:
for variable in variables:
print extracted_data.variable
But for some reason I get an AttributeError: 'module' object has no attribute 'variable'.
Use print getattr(extracted_data, variable) instead to get attrbutes whose name is in a string
This sounds like an XY problem to me. You might look into the configparser module instead of trying to parse Python files.
or better yet, use dir(extracted_data) to list the attributes instead of shelling out. or loop over for k, v in vars(extracted_data).items():
You can extract the variables and their value defined in the extracted_data.py file like this:
import extracted_data
extract_vars = {name: getattr(extracted_data, name)
for name in dir(extracted_data) if not name.startswith('_')}
print(extract_vars) # -> {'parameterx_server2': 'another value', 'parameterx_server1': 'value'}
As shown, afterwards extract_vars is a dictionary containing both the variable names and associated values.
| common-pile/stackexchange_filtered |
Use Of Exists clause in SQL
Just finished Stanford lecture on SQL (by Prof. Jennifer Widom). However I have developed a confusion regarding the use of EXISTS clause. I thought it is just like a condition and an expression so that if it's true, the above query proceeds (much like the Boolean AND). So having a slight doubt regarding this question:
Passenger = {pid, pname, Age}
Reservation = {pid, class, tid}
and tables are populated with some data and following query is executed:
SELECT pid
FROM Reservation
WHERE class = 'AC' AND EXISTS
(SELECT * FROM Passenger WHERE age > 65 AND Passenger.pid = Reservation.pid)
Now the thing that is getting me troubled is that I thought that the use of EXISTS is simply that the above main query proceeds if the subquery returns something. So as the subquery was returning something, I expected the query to return all PID's where class = 'AC'. I didn't think that it was executed tuple by tuple. So how to remove this confusion?
You can make the subquery a lot faster by selecting only the primary key from the table. You aren't using any of the other data returned by SELECTing *. EXISTS performs a boolean comparison of you subquery (correlated or not). This article explains some of the process in detail.
In this particular scenario, I would consider using a join on the Passenger table and a where clause to filter the results. Something like the below:
SELECT pid
FROM Reservation
INNER JOIN Passenger
ON Passenger.pid = Reservation.pid
WHERE class = 'AC' and age > 65
For me this is a clearer version and it is easier to understand what the query is actually doing.
The exists is operating on all rows in Reservation and checking whether they meet the exists query. For me this looks confusing and can be quicker to join directly on the table using the ids and filtering where necessary.
I don't think this makes the intent clearer, but does shed some light for the OP. Exists is pretty explicit in what you're trying to do. To me, a join returns related data from both tables. Using an outer join only to find out what doesn't exist in the other table (and looking for a null) is even more confusing although it is a common technique. When I see exists, I know there are only so many things you could be trying to do.
I guess so. Maybe its personal coding styles. I prefer the join way because for me the intention comes across a lot clearer. Especially when it is a big query.
Because it refers to an object in the outer query (Reservation), the subquery is a correlated subquery. As it says in that wikipedia article,
The subquery is evaluated once for each row processed by the outer query
If the subquery weren't correlated, your reasoning would be correct. For example, hypothetically,
SELECT pid
FROM Reservation
WHERE class = 'AC' AND EXISTS
(SELECT * FROM Passenger WHERE age > 65)
would, so long as there was at least one passenger over 65, return all Reservations with class='AC'.
I think the subquery will be run once for each row of outer query, no matter what.
@user61852 not with a query optimizer that has at least a small amount of sense...
Almost any query optimizer will see that the can only return 1 data set for the non-correlated subquery.
| common-pile/stackexchange_filtered |
How to make associative array using PHP for loop to use in Yii 2 array map()?
I would like to make an associative array using PHP for loop to use in Yii2 map() method.
The array will look like in bellow format-
$listArray = [
['id' => '1', 'name' => 'Peter/5'],
['id' => '2', 'name' => 'John/7'],
['id' => '3', 'name' => 'Kamel/9'],
];
The id and name will be changed through each iteration of the loop. Here, the name will always hold customized value after some calculation inside the loop.
Finally, the list will be used in map() method like as following
$listData=ArrayHelper::map($listArray,'id','name');
I can use map() method directly after using the Active Record to find the list array and then use that in map() method. But it does not a give me way to use custom value for the name attribute.
$listArray = UserList::find()
->where(['status' => 1])
->orderBy('name')
->all();
$listData=ArrayHelper::map($listArray,'id','name');
How can achieve this? Direct source code example would be really great for me.
Thanks in advance.
If you can iterate through the returned rows, you could easily build out an associative array within the for each loop. I'm not overly familiar with Yii2 but I imagine the principles are the same and you could just use native PHP for this.
If you please help to write the code to make the associative array that would be really helpful for me. I could write for PHP generic array with () or {} but not for using [ [], [] ] this way. Thanks.
@xerxes333 answered below along the lines of what I was talking about.
I'm assuming you want to query an ActiveRecord for data then transfer the data into a simple array.
$listData = [];
$listArray = UserList::find()
->where(['status' => 1])
->orderBy('name')
->all();
foreach($listArray as $user){
$customName = $user->name . $this->someCalculation();
$listData[] = ["id" => $user->id, "name" => $customName];
}
Or you could use the ArrayHelper class like this:
$listArray = UserList::find()
->where(['status' => 1])
->orderBy('name')
->all();
$listData = ArrayHelper::toArray($listArray , [
'app\models\UserList' => [
'id',
'name' => function ($listArray ) {
return $listArray->word . strlen($listArray->word); // custom code here
},
],
]);
I think the preferred way of doing this by defining custom calculation rule in UserList model as:
public function getCustomRuleForUser(){
// Do what ever you want to do with your user name.
return $this->name.'Your custom rule for name';
}
And use as:
$userList = UserList::find()->all();
$listData=ArrayHelper::map($userList,'id','customRuleForUser');
Now, you have your custom rule for username list in $listData.
$model_userprofile = UserProfile::find()->where(['user_id' => Yii::$app->user->id])->one();
$model_userprofile1 = UserProfile::find()
->select('user_id')
->where(['group_id' => $model_userprofile->group_id])->all();
$listData = [];
foreach($model_userprofile1 as $user){
$id = $user->user_id;
$listData[] = ["id" => $id];
}
$dataProvider = new ActiveDataProvider
([
'query' => User::find()
->select('id,username,email')
->Where(['id' => $listData])
->orderBy(['id' => SORT_DESC]),
'pagination' => ['pagesize' => 15]]);
return $this->render('index',['dataProvider'=> $dataProvider]);
| common-pile/stackexchange_filtered |
exit transition from activity not working
I have three activities (A, B and C) with an image view. Activity A has a small image view, B a mid-sized image view and C a fullscreen image view. From A to B I use
makeSceneTransitionAnimation for the transition. Start and Exit transition are working fine between A and B. From B to C I also use makeSceneTransitionAnimation. Thats is also working fine but when I go from C to B and then from B to A the exit transition is not working.
Is there some overriding process from C to B that affects the exit transition from B to A?
I found a solution that I am satisfied with for the moment.
My first approach was to monitor, inspect and manage the shared elements via SharedElementCallbackbut this does not seem to work as there are no shared elements in activity B when comming from C. So now when I am in activity B and I want to go to activity A, I check which activity I come from (A or C). Is it activity A then I simply use supportFinishAfterTransition. If I am coming from activity C I use makeSceneTransitionAnimation to activity A. The second case creates a new instance of activity A. Thats why I just finish the older instance of activity A.
I uploaded my solution on github to the repo "transition" in case somebody wants to use some code (github account is linked here on stackoverflow).
If somebody knows a better solution please let me know.
| common-pile/stackexchange_filtered |
Bound the conditional expectation of a random matrix under weak dependence
Let $X$ be an $d\times d$ random matrix satisfying $\mathbb{E}[X]=0$ and $\|X\|_2\leq 1$ almost everywhere. Let $\mathcal{F}$ be the $\sigma$-field generated by $X$. Now suppose we have another $\sigma$-field $\mathcal{G}$, it satisfies that
\begin{equation*}
\rho(\mathcal{F},\mathcal{G})=\sup_{A\in\mathcal{F},B\in\mathcal{G}}|\mathbb{P}(AB)-\mathbb{P}(A)\mathbb{P}(B)|\leq\phi.
\end{equation*}
Now I want to prove that
\begin{equation}\label{eq:main}
\mathbb{E}\big[\|\mathbb{E}[X|\mathcal{G}]\|_2\big]\leq Cd\phi,
\end{equation}
where $C$ is some constant and $d$ is the dimension.
From Lemma 4.4.1 of this paper, I already know that
\begin{equation}
\mathbb{E}\big[|\mathbb{E}[X|\mathcal{G}]|\big]\leq C\phi,
\end{equation}
hold if $X$ is a scalar random variable. Now I want to extend this result to matrix case.
I tried to use the discretization technique as in Proposition 5.17 of Wainwright's book, but then I can only prove it bounded by $C9^d\phi$, which is undesirable because it is exponentially related to the dimension $d$. So I hope someone can give me some idea about it.
I have figured out how to prove a relatively weaker result.
By elementary inequality of matrix, we know that
\begin{equation*}
|X|_{\infty}\leq\|X\|\leq 1, \quad\text{ and }\quad\|X\|\leq \|X\|_F.
\end{equation*}
For every element $X_{i,j}$ of $X$, by Lemma 4.4.1 of this paper we have that
\begin{equation*}
\mathbb{E}\Big[\big|\mathbb{E}[X_{ij}|\mathcal{G}]\big|^2\Big]\leq \mathbb{E}\Big[\big|\mathbb{E}[X_{ij}|\mathcal{G}]\big|\Big]\leq 2\pi\phi.
\end{equation*}
Therefore, we have that
\begin{align*}
&\mathbb{E}\Big[\|\mathbb{E}[X|\mathcal{G}]\|\Big]\leq \mathbb{E}\Big[\|\mathbb{E}[X|\mathcal{G}]\|_F\Big],\\
\leq&\Big\{\mathbb{E}\Big[\|\mathbb{E}[X|\mathcal{G}]\|^2_F\Big]\Big\}^{1/2}\\
\leq&\Big\{\mathbb{E}\Big[\sum_{i,j=1}^d\big|\mathbb{E}[X_{ij}|\mathcal{G}]\big|^2\Big]\Big\}^{1/2}\leq\sqrt{d^22\pi\phi}=d\sqrt{2\pi\phi}.
\end{align*}
| common-pile/stackexchange_filtered |
I have a mongo db collection it has object of objects I want to update all the object inside the lteneighbors which has nbrtype as manual
Collection data:
{
"globalcellid": "00201-292-0",
"deviceid": "41733-CI9999-S453474X2203870-01-4G",
"devicename": "41733-CI9999-S453474X2203870-01-4G",
"cellname": "cell123",
"vbbudeviceid": "41733-CI9999-S453474X2203870",
"celltype": "lte",
"properties": {
"cellattributes": {
"radius": 5
}
},
"pciconfig": {
"poolname": ""
},
"workstate": "none",
"cellstate": "cell-up",
"nbrtypeanradminstate": {
"state": {
"geo": false,
"manual": true,
"uereported": true,
"x2": true
},
"isbidirectional": true
},
"neighbors": {
"nbrecgilist": [
"00103-0-3",
"00101-0-1",
"00102-0-2"
],
"lteneighbors": {
"00101-0-1": {
"globalcellid": "00101-0-1",
"deviceid": "",
"cellcfg": {
"nbrtype": [
"manual"
]
},
"celltype": "lte",
"primaryplmn": "",
"secondaryplmns": [
"00000"
],
"pci": 100,
"eci": "1",
"tac": 0,
"qoffsetcell": 0,
"bandname": 67,
"bandwidth": 10,
"bandmode": 2,
"earfcn": 6300,
"priority": 0,
"enable": true,
"mustinclude": false,
"blacklist": true,
"alias": "",
"nodetype": ""
},
"00102-0-2": {
"globalcellid": "00102-0-2",
"deviceid": "",
"cellcfg": {
"nbrtype": [
"manual"
]
},
"celltype": "lte",
"primaryplmn": "",
"secondaryplmns": [
"00000"
],
"pci": 101,
"eci": "2",
"tac": 0,
"qoffsetcell": 0,
"bandname": 67,
"bandwidth": 10,
"bandmode": 2,
"earfcn": 6300,
"priority": 0,
"enable": true,
"mustinclude": false,
"blacklist": true,
"alias": "",
"nodetype": ""
},
"00103-0-3": {
"globalcellid": "00103-0-3",
"deviceid": "",
"cellcfg": {
"nbrtype": [
"manual"
]
},
"celltype": "lte",
"primaryplmn": "",
"secondaryplmns": [
"00000"
],
"pci": 102,
"eci": "3",
"tac": 0,
"qoffsetcell": 0,
"bandname": 67,
"bandwidth": 10,
"bandmode": 2,
"earfcn": 3600,
"priority": 0,
"enable": true,
"mustinclude": false,
"blacklist": true,
"alias": "",
"nodetype": ""
}
},
"gsmneighbors": {},
"umtsneighbors": {}
}
}
I was tried to convert it in array, update and again object of objects but not able to do so
What queries have you tried so far? What is the desired output?
Expected result is for all the lteneighbors with nbrtype = manual should update blacklist from true to false
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
"nbrtype" seems to be an array. What should happen if there are multiple members of the array?
| common-pile/stackexchange_filtered |
Troubleshooting "Can't connect to local MySQL server through socket" when calling mysql_real_escape_string()
I am getting the error:
Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Why do I get this error? The mysql_real_escape_string() works on all of my pages apart from one? Is it something to do with MySQL being on a different server to the PHP server - if so, how do I fix it?
$fname = $_POST['fname'];
$fname = stripslashes($fname);
$fname = mysql_real_escape_string($fname);
Can you post the code in question?
@Tom why you call stripslashes($fname) before mysql_real_escape_string()?
This is because you never call mysql_connect() before the use of mysql_real_escape_string().
In order to use mysql_real_escape_string(), PHP must be connected to the database. In order to connect to the database, you must use mysql_connect().
Out of curiosity, why does it need to call the database to execute that function?
The PHP code invokes the MySQL's library function to escape the strings, so in order for the code to invoke the library function, it must be connected first.
It calls a MySQL library function to do the escaping. It is not done in PHP directly.
@Spencer Good question. It's because the escaping depends on the character set used by the server ( see http://dev.mysql.com/doc/refman/5.1/en/mysql-real-escape-string.html )
| common-pile/stackexchange_filtered |
How to automatically convert from org.apache.camel.converter.stream.InputStreamCache to Pojo using Jackson in a Spring Boot Camel Kotlin application
In a Spring Boot 2.7. Camel 3.20.x project written in Kotlin I have a REST endpoint that receives a JSON payload. I've added the Camel Jackson dependency to deal with JSON<->POJO transformation:
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-jackson-starter</artifactId>
<version>${camel.version}</version>
</dependency>
data class Payment(val iban: String, val amount: Float)
rest("/payments")
.post("/")
.to("direct:processPayment")
from("direct:processPayment")
.log("Body \${body}")
.log("Body \${body.getClass()}")
These are the logs of the route:
Body {"payment":{"iban":"ABCD","amount":150.0}}
Body class org.apache.camel.converter.stream.InputStreamCache
As you can see the body is correctly displayed as String, however, the type is InputStreamCache instead of my Payment DTO.
I updated the route to unmarshall the body to the Payment DTO:
from("direct:processPayment")
.unmarshal().json(JsonLibrary.Jackson, Payment::class.java)
.log("Body \${body}")
.log("Body \${body.getClass()}")
This fails with:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `xxx.Payment` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
Why isn't the conversion working?
Can you show your Payment class ? Is there a default constructor (without argument) ?
Otherwise, try to introduce a .convertBodyTo(String.class) BEFORE the unmarshalling
@TacheDeChoco nope, it doesn't have a default constructor, I'm using a Kotlin Data class
Your pojo needs to respect the Java Bean conventions (eg with default constructor) otherwise the unmarshalling cannot work
It makes sense, I verified it worked with a default constructor, if you add it as answer I'll be glad to accept it.
The encountered error has nothing to see with Camel nor Spring, but is directly related to Jackson.
As the error message indicates it, the reason is that the Payment pojo does not satisfy the requirement of having a default (parameterless) constructor.
Actually it’s about JSON (Jackson, not JAXB), but you’re right about the default empty constructor requirement
Yes of course :-/ I have just corrected
The source of the problem was correctly described in the accepted answer. However there's a Kotlin compatible solution that allows the use of data classes without default (empty) constructors.
Add jackson-module-kotlin dependency:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
With this, Spring Boot will tweak its own Jackson ObjectMapper. Now, just tell Camel to use that Spring configured object mapper:
camel:
dataformat:
jackson:
auto-discover-object-mapper: true
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.