qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
49,547,744
I am trying to deploy Lambda functions using AWS Cloud9. When I press deploy, all of my functions are deployed/synced at the same time rather than just the one I selected when deploying. Same thing when right clicking on the function and pressing deploy. I find this quite annoying and wondering if there is any work around?
2018/03/29
[ "https://Stackoverflow.com/questions/49547744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4718413/" ]
When you click deploy Cloud9 runs `aws cloudformation package` and `aws cloudformation deploy` on your `template.yaml` file in the background. (source: I developed the Lambda integration for AWS Cloud9). Because all your files are bundled into one serverless application and there is only one CloudFormation stack they can only be all deployed at once with CloudFormation. If you're only making a code change for one function and are not modifying any configuration settings you could update that one function from the command line with the command: ``` zip -r - . | aws lambda update-function-code --function-name <function-name>` ``` Run this in the same folder as your `template.yaml` file, replacing `<function-name>` with it's full generated name like `cloud9-myapp-myfunction-ABCD1234` (You can see the full name under the remote functions list in the AWS Resources panel).
In AWS Cloud9, Lambda functions are created within serverless applications and are therefore deployed via CloudFormation. With CloudFormation, the whole stack is deployed at once, so all functions are deployed together (see [this discussion](https://github.com/awslabs/serverless-application-model/issues/125) for more info).
33,402,360
I am attempting to create a random number generator for any number of numbers in a line and then repeating those random numbers until a "target" number is reached. The user will enter both the number of numbers in the sequence and the sequence they are shooting for. The program will run the random numbers over and over until the target sequence is hit, then the program will spit out the number of repetitions it took. My problem is that it keeps going on forever, seemingly never hitting the break function because num doesn't equal target or something. So far I have this and i think i am pretty close ``` #Module to get amount of numbers in the sequence def getRange(): Range =int(input("How many digits in your number?")) return Range #Target Sequence input def getTarget(): Target= [] Target =input("What is your target sequence?") return Target def lotteryNo(Range): import random integer = [] for number in range(0 , Range): integer.append(random.randint(0, 9)) return integer def printDigits(Range,Target): print("Your target list is",Target) for rep in range(10000000): num=(lotteryNo(Range)) print(num) if num == Target: rep=rep + 1 print("The number of repetitions is",rep) break else: rep=rep+1 def main(): Range=getRange() Target=getTarget() printDigits(Range,Target) main() #End ```
2015/10/28
[ "https://Stackoverflow.com/questions/33402360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5344823/" ]
The issue with your comparison is that you're testing `Target` which is a string against `num` which is a list of integers. That will never match, no matter what integers and what string you're dealing with. You need to compare two like-types to get a meaningful result. It looks like you wanted your `getTarget` function to return a list, since you're initializing `Target` to an empty string. However, when you overwrite it with `Target = input(...)`, the list is discarded. You probably want something like `Target = list(map(int, input()))`, which converts each character of the input string to an integer and then packs them all into a list. Another way of writing that would be `Target = [int(digit) for digit in input()]`. One further suggestion, unrelated to your current issue: Python's common naming convention is to use `lower_case_names_with_underscores` for variable and function names, reserving `UpperCaseNames` for classes. You don't have to follow this convention, but it's probably a good idea if you're going to share your code with anyone. You can read [PEP 8](https://www.python.org/dev/peps/pep-0008/) for more style suggestions.
Your problem is because one of your numbers is a list and the other is a string from input. Change Target to get an `int` ``` def getTarget(): Target =int(input("What is your target sequence?")) return Target ``` Change lotteryNo to get an `int` ``` def lotteryNo(Range): import random integer = 0 for number in range(0 , Range): integer += random.randint(0, 9) * (10**number) return integer ``` And your `if num == Target:` comparison should now work as it is comparing two variables of the same type.
38,356,333
Another beginners question here, coming from Delphi you always have access to another forms controls but in my early days with C# / Visual Studio I am faced with a problem which is proving more difficult than it should be. I have been getting started by writing a simple notepad style application, I have my main form and a secondary form used to select a line number. From my main form, I call the goto line number form like so: ``` private void mnuGoTo_Click(object sender, EventArgs e) { Form gotoForm = new GoToForm(); var dialogResult = gotoForm.ShowDialog(); if (dialogResult == DialogResult.OK) { // get the text from gotoForm.editLineNumber.Text MessageBox.Show(gotoForm.editLineNumber.Text); // doesn't work } } ``` As you can see from the commented code I have a `TextBox` control called `editLineNumber` which is on my other form (`GoToForm`). My problem (and likely a beginner question) is why does `editLineNumber` not show in the `intellisense` menu when I type `gotoForm.`? How do I access the `editLineNumber` control from the form `GoToForm`? The error message for the `// doesn't work` commented line is: > > Error CS1061 'Form' does not contain a definition for 'editLineNumber' > and no extension method 'editLineNumber' accepting a first argument of > type 'Form' could be found (are you missing a using directive or an > assembly reference?) > > > Unless I am missing something obvious, why are controls that exist on another form not publically available to all forms? I understand that C# / Visual Studio is different to Delphi but the way Delphi lets you access and see all controls on all forms without any extra works seems more logical to me. Why does C# / Visual Studio hide controls on secondary forms, for what purpose can this be beneficial?
2016/07/13
[ "https://Stackoverflow.com/questions/38356333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4645457/" ]
The `editLineNumber` control is private. You can change it to be public, but that's discouraged. Instead, create a property in `GoToForm` that returns the value you want. ``` public string LineNumber { get { return this.editLineNumber.Text; } } ``` Now you can just reference your new property: ``` if (dialogResult == DialogResult.OK) { MessageBox.Show(gotoForm.LineNumber); } ```
Especially if you're new to C# and WinForms, don't touch designer code with a 10 foot pole. As Grant Winney said, use a property: ``` public string GetLineNumberText { get { return this.editLineNumber.Text; } } ``` It should be mentioned that it's important to be aware of the directional nature of forms. That is to say, if I make `Form1` and then define `Form2` inside of it, you'll want to be careful how you communicate between the two forms. Properties are nearly always a better alternative than accessing form elements directly - it makes the code very difficult to change otherwise. If you, for example, removed `editLineNumber` from the other form or renamed it, *every* instance in the parent form would have to be edited. If you use a property, then you only have to change it in one place.
29,845,218
I,m trying to write a regex to check if the given string is like a + b, 2 + a + b, 3 + 6 \* 9 + 6 \* 5 + a \* b, etc... Only + and \* operators. I tried `if (str.matches("(\\d|\\w \\+|\\*){1,} \\d|\\w"))` Unfortunately it only handles cases like 3 \* 7 ... (numeric \* numeric). Waiting for your answers, thanks for reading me.
2015/04/24
[ "https://Stackoverflow.com/questions/29845218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4807032/" ]
Put `*` and `+` inside a character class. ``` str.matches("\\w(?:\\s[+*]\\s\\w)+"); ``` [DEMO](https://regex101.com/r/dI4uH0/2)
This will handle cases of simple and chained calculations ``` [0-9A-Za-a]*( ){0,}([+-/*]( ){0,}[0-9A-Za-a]*( ){0,})* ``` This would match, for example * 1+2 * 1 + 2 * 1 + a \* 14 / 9 (You can change the operators you want by updating `[+-/*]`)
66,436,586
I have the below list :- ``` someList = ["one","three","four","five","six","two"] ``` I want to change position of "two" i.e after "one" and rest string should be shifted as they are. Expected Output : - > > someList = ["one","two","three","four","five","six",] > > >
2021/03/02
[ "https://Stackoverflow.com/questions/66436586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8048800/" ]
You can pop 2 from current index and insert to new index ```py l.insert(1, l.pop(-1)) ```
You can use unpacking to redistribute ``` a,c,d,e,b = ["one","three","four","five","six","two"] someList= [a,b,c,d,e] someList ```
12,331,968
I have code like this I need to access the `mysample` variable of static class `InnerClass` in the `getInnerS()` method which is inside the the `NestedClass`. I tried accessing it by creating a new object for `InnerClass` but i am getting `java.lang.StackOverflowError`. ``` public class NestedClass{ private String outer = "Outer Class"; //NestedClass instance variable NestedClass.InnerClass innerClass = new NestedClass.InnerClass(); void getOuterS(){ System.out.println(outer); } void getInnerS(){ System.out.println(innerClass.mysample); } static class InnerClass{ private String mysample = "Inner Class"; //InnerClass instance variable, NestedClass a = new NestedClass(); void getIn(){ System.out.println(mysample); } void getOut(){ System.out.println(a.outer); } } public static void main(String[] args){ NestedClass nestedClass = new NestedClass(); NestedClass.InnerClass nestedInner = new NestedClass.InnerClass(); nestedClass.getOuterS(); nestedClass.getInnerS(); nestedInner.getIn(); nestedInner.getOut(); } } ```
2012/09/08
[ "https://Stackoverflow.com/questions/12331968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1604151/" ]
In `InnerClass` constructor: ``` NestedClass a = new NestedClass(); ``` So, you create a new `NestedClass`, which creates a new `InnerClass`, which creates itself its own `NestedClass`, with the corresponding `InnerClass`.... No wonder the stackoverflow. If you want to access the enclosing class, you should use (inside `InnerClass` methods) ``` NestedClass.this ```
With this solution member class is `static`. For better comparison you might read [Static class declarations](http://www.javaworld.com/javaqa/1999-08/01-qa-static2.html) *Static nested classes (description)* Static nested classes do not have access to non-static fields and methods of the outer class, which in some ways similar to the static methods defined within the class. Access to non-static fields and methods can only be done through an instance reference of the outer class. In this regard, static nested classes are very similar to any other top-level classes. In addition, static nested classes have access to any static methods of the outer class, including to private. The benefits of these classes is mainly in logical groupings of entities to improve encapsulation, as well as saving class-space. ``` public class NestedClass{ private static String outer = "Outer Class"; //NestedClass instance variable InnerClass innerClass = new InnerClass(); void getOuterS(){ System.out.println(outer); } void getInnerS(){ System.out.println(InnerClass.mysample); } InnerClass getInner(){ return innerClass; } static class InnerClass{ private static String mysample = "Inner Class"; //InnerClass instance variable, void getIn(){ System.out.println(mysample); } void getOut(){ System.out.println(outer); //access a static member } } public static void main(String[] args){ NestedClass nestedClass = new NestedClass(); NestedClass.InnerClass nestedInner = nestedClass.getInner(); nestedClass.getOuterS(); nestedClass.getInnerS(); nestedInner.getIn(); nestedInner.getOut(); } } ```
12,331,968
I have code like this I need to access the `mysample` variable of static class `InnerClass` in the `getInnerS()` method which is inside the the `NestedClass`. I tried accessing it by creating a new object for `InnerClass` but i am getting `java.lang.StackOverflowError`. ``` public class NestedClass{ private String outer = "Outer Class"; //NestedClass instance variable NestedClass.InnerClass innerClass = new NestedClass.InnerClass(); void getOuterS(){ System.out.println(outer); } void getInnerS(){ System.out.println(innerClass.mysample); } static class InnerClass{ private String mysample = "Inner Class"; //InnerClass instance variable, NestedClass a = new NestedClass(); void getIn(){ System.out.println(mysample); } void getOut(){ System.out.println(a.outer); } } public static void main(String[] args){ NestedClass nestedClass = new NestedClass(); NestedClass.InnerClass nestedInner = new NestedClass.InnerClass(); nestedClass.getOuterS(); nestedClass.getInnerS(); nestedInner.getIn(); nestedInner.getOut(); } } ```
2012/09/08
[ "https://Stackoverflow.com/questions/12331968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1604151/" ]
``` NestedClass a = new NestedClass(); ``` in static InnerClass class creates an instance of the NestedClass and as InnerClass is static this is a loop. InnerClass does not need to be static, this should work ``` public class NestedClass { private String outer = "Outer Class"; //NestedClass instance variable NestedClass.InnerClass innerClass = new NestedClass.InnerClass(); void getOuterS(){ System.out.println(outer); } void getInnerS(){ System.out.println(innerClass.mysample); } class InnerClass{ private String mysample = "Inner Class"; //InnerClass instance variable, NestedClass a = NestedClass.this; void getIn(){ System.out.println(mysample); } void getOut(){ System.out.println(a.outer); } } public static void main(String[] args){ NestedClass nestedClass = new NestedClass(); NestedClass.InnerClass nestedInner = nestedClass.innerClass; nestedClass.getOuterS(); nestedClass.getInnerS(); nestedInner.getIn(); nestedInner.getOut(); } } ```
With this solution member class is `static`. For better comparison you might read [Static class declarations](http://www.javaworld.com/javaqa/1999-08/01-qa-static2.html) *Static nested classes (description)* Static nested classes do not have access to non-static fields and methods of the outer class, which in some ways similar to the static methods defined within the class. Access to non-static fields and methods can only be done through an instance reference of the outer class. In this regard, static nested classes are very similar to any other top-level classes. In addition, static nested classes have access to any static methods of the outer class, including to private. The benefits of these classes is mainly in logical groupings of entities to improve encapsulation, as well as saving class-space. ``` public class NestedClass{ private static String outer = "Outer Class"; //NestedClass instance variable InnerClass innerClass = new InnerClass(); void getOuterS(){ System.out.println(outer); } void getInnerS(){ System.out.println(InnerClass.mysample); } InnerClass getInner(){ return innerClass; } static class InnerClass{ private static String mysample = "Inner Class"; //InnerClass instance variable, void getIn(){ System.out.println(mysample); } void getOut(){ System.out.println(outer); //access a static member } } public static void main(String[] args){ NestedClass nestedClass = new NestedClass(); NestedClass.InnerClass nestedInner = nestedClass.getInner(); nestedClass.getOuterS(); nestedClass.getInnerS(); nestedInner.getIn(); nestedInner.getOut(); } } ```
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
You need to add the RDS instance as an additional server listed on PHPMyAdmin while granting the host PHPMyAdmin access to your RDS instance. More details from this blog post on [How to remotely manage an Amazon RDS instance with PHPMyAdmin](http://blog.benkuhl.com/2010/12/how-to-remotely-manage-an-amazon-rds-instance-with-phpmyadmin/): > > The one thing I had trouble with was the DB Security Group setup. When you go to add access for an CIDR/IP it provides a recommended value. It took some messing around to determine that this default value isn’t actually what needed to be there. If you’re not able to connect to your instance when it’s all said and done, be sure to double check this value. The IP they provided did not match the IP address that was provided to us by our ISP. Once you’ve created your DB Instance and setup the security group you’re good to go. > > > I’m going to assume you’ve already got PHPMyAdmin up and running. What you need to do is modify config.inc.php to recognize the new server. > > >
If you can connect from the cli using `mysql -h ENDPOINT -u USERNAME -p` but not from PHPMyAdmin or your own web scripts, don't forget to [tell selinux to let your web server talk to the network](https://wiki.centos.org/TipsAndTricks/SelinuxBooleans#line-44) :) ``` sudo setsebool -P httpd_can_network_connect=1 ```
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
You need to add the RDS instance as an additional server listed on PHPMyAdmin while granting the host PHPMyAdmin access to your RDS instance. More details from this blog post on [How to remotely manage an Amazon RDS instance with PHPMyAdmin](http://blog.benkuhl.com/2010/12/how-to-remotely-manage-an-amazon-rds-instance-with-phpmyadmin/): > > The one thing I had trouble with was the DB Security Group setup. When you go to add access for an CIDR/IP it provides a recommended value. It took some messing around to determine that this default value isn’t actually what needed to be there. If you’re not able to connect to your instance when it’s all said and done, be sure to double check this value. The IP they provided did not match the IP address that was provided to us by our ISP. Once you’ve created your DB Instance and setup the security group you’re good to go. > > > I’m going to assume you’ve already got PHPMyAdmin up and running. What you need to do is modify config.inc.php to recognize the new server. > > >
``` sudo nano /etc/phpmyadmin/config.inc.php --ADD LINES BELOW THE PMA CONFIG AREA AND FILL IN DETAILS-- $i++; $cfg['Servers'][$i]['host'] = '__FILL_IN_DETAILS__'; $cfg['Servers'][$i]['port'] = '3306'; $cfg['Servers'][$i]['socket'] = ''; $cfg['Servers'][$i]['connect_type'] = 'tcp'; $cfg['Servers'][$i]['extension'] = 'mysql'; $cfg['Servers'][$i]['compress'] = FALSE; $cfg['Servers'][$i]['auth_type'] = 'config'; $cfg['Servers'][$i]['user'] = '__FILL_IN_DETAILS__'; $cfg['Servers'][$i]['password'] = '__FILL_IN_DETAILS__'; ``` Save and Exit. Refresh your phpmyadmin page and you'll see a dropdown with the server that you just added[![enter image description here](https://i.stack.imgur.com/611W4.png)](https://i.stack.imgur.com/611W4.png) Source: <https://github.com/andrewpuch/phpmyadmin_connect_to_rds>, <https://www.youtube.com/watch?v=Bz-4wTGD2_Q>
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
You need to add the RDS instance as an additional server listed on PHPMyAdmin while granting the host PHPMyAdmin access to your RDS instance. More details from this blog post on [How to remotely manage an Amazon RDS instance with PHPMyAdmin](http://blog.benkuhl.com/2010/12/how-to-remotely-manage-an-amazon-rds-instance-with-phpmyadmin/): > > The one thing I had trouble with was the DB Security Group setup. When you go to add access for an CIDR/IP it provides a recommended value. It took some messing around to determine that this default value isn’t actually what needed to be there. If you’re not able to connect to your instance when it’s all said and done, be sure to double check this value. The IP they provided did not match the IP address that was provided to us by our ISP. Once you’ve created your DB Instance and setup the security group you’re good to go. > > > I’m going to assume you’ve already got PHPMyAdmin up and running. What you need to do is modify config.inc.php to recognize the new server. > > >
I use ubuntu shell to access Amazon RDS. first of all go to ubuntu root ``` sudo -i ``` to do this use amazon RDS end user URL ``` mysql -h gelastik.cqtbtepzqfhu.us-west-2.rds.amazonaws.com -u root -p ```
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
First try this : **mysql -h xxxxx.xxxxxxx.xx-xx-2.rds.amazonaws.com -u root -p** // Your RDS server. If it waits and doesn't prompt for the password then you would need to check security group and add 3306 outbound to your Web Tier.
If you can connect from the cli using `mysql -h ENDPOINT -u USERNAME -p` but not from PHPMyAdmin or your own web scripts, don't forget to [tell selinux to let your web server talk to the network](https://wiki.centos.org/TipsAndTricks/SelinuxBooleans#line-44) :) ``` sudo setsebool -P httpd_can_network_connect=1 ```
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
You need to add the RDS instance as an additional server listed on PHPMyAdmin while granting the host PHPMyAdmin access to your RDS instance. More details from this blog post on [How to remotely manage an Amazon RDS instance with PHPMyAdmin](http://blog.benkuhl.com/2010/12/how-to-remotely-manage-an-amazon-rds-instance-with-phpmyadmin/): > > The one thing I had trouble with was the DB Security Group setup. When you go to add access for an CIDR/IP it provides a recommended value. It took some messing around to determine that this default value isn’t actually what needed to be there. If you’re not able to connect to your instance when it’s all said and done, be sure to double check this value. The IP they provided did not match the IP address that was provided to us by our ISP. Once you’ve created your DB Instance and setup the security group you’re good to go. > > > I’m going to assume you’ve already got PHPMyAdmin up and running. What you need to do is modify config.inc.php to recognize the new server. > > >
Try to connect from the mysql command line (http://dev.mysql.com/doc/refman/5.1/en/mysql.html) and see what's this utility returns you. I found it's easier to debug that way. ``` mysql -hMY-DB.us-east-1.rds.amazonaws.com -uMASTER-USER -pPASSWORD ``` If that's doesn't work, it means your amazon RDS security aren't configured correctly. (which is the common problem).
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
``` sudo nano /etc/phpmyadmin/config.inc.php --ADD LINES BELOW THE PMA CONFIG AREA AND FILL IN DETAILS-- $i++; $cfg['Servers'][$i]['host'] = '__FILL_IN_DETAILS__'; $cfg['Servers'][$i]['port'] = '3306'; $cfg['Servers'][$i]['socket'] = ''; $cfg['Servers'][$i]['connect_type'] = 'tcp'; $cfg['Servers'][$i]['extension'] = 'mysql'; $cfg['Servers'][$i]['compress'] = FALSE; $cfg['Servers'][$i]['auth_type'] = 'config'; $cfg['Servers'][$i]['user'] = '__FILL_IN_DETAILS__'; $cfg['Servers'][$i]['password'] = '__FILL_IN_DETAILS__'; ``` Save and Exit. Refresh your phpmyadmin page and you'll see a dropdown with the server that you just added[![enter image description here](https://i.stack.imgur.com/611W4.png)](https://i.stack.imgur.com/611W4.png) Source: <https://github.com/andrewpuch/phpmyadmin_connect_to_rds>, <https://www.youtube.com/watch?v=Bz-4wTGD2_Q>
If you can connect from the cli using `mysql -h ENDPOINT -u USERNAME -p` but not from PHPMyAdmin or your own web scripts, don't forget to [tell selinux to let your web server talk to the network](https://wiki.centos.org/TipsAndTricks/SelinuxBooleans#line-44) :) ``` sudo setsebool -P httpd_can_network_connect=1 ```
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
I found most of the answers in this question lack explanation. To add RDS server in phpMyAdmin installed in EC2, you can first login to your EC2 via SSH. Then, issue the following command to edit the Config file of phpMyAdmin (use `vi`, `nano` or any other favorite text editing tool): ``` sudo vi /etc/phpMyAdmin/config.inc.php # Amazon Linux sudo vi /etc/phpmyadmin/config.inc.php # Ubuntu Linux ``` Find the following lines in `config.inc.php`: ``` /* * End of servers configuration */ ``` Append the following lines **above** the "End of servers configuration" line: ``` $i++; $cfg['Servers'][$i]['host'] = 'xxxxx.xxxxxxxxxx.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['port'] = '3306'; $cfg['Servers'][$i]['verbose'] = 'YOUR_SERVER_NAME'; $cfg['Servers'][$i]['connect_type'] = 'tcp'; $cfg['Servers'][$i]['extension'] = 'mysql'; $cfg['Servers'][$i]['compress'] = TRUE; ``` which `YOUR_SERVER_NAME` is the name being displayed in phpMyAdmin login page's selection box. If you remove this line, the whole RDS hostname will be displayed in the selection box (which is too long, obviously). Remember to save the `config.inc.php`. There are several other config settings, which you can find the details in the [official documentation](https://docs.phpmyadmin.net/en/latest/config.html). --- **Note:** The other answer suggests auto login with preset username & password in Config file: ``` $cfg['Servers'][$i]['auth_type'] = 'config'; $cfg['Servers'][$i]['user'] = '__FILL_IN_DETAILS__'; $cfg['Servers'][$i]['password'] = '__FILL_IN_DETAILS__'; ``` which is **extremely dangerous** if your phpMyAdmin is exposed to public. You don't want to show your database schema to everyone, do you? If you really want to use automatic login, make sure your phpMyAdmin is accessible via specific IPs only.
If you can connect from the cli using `mysql -h ENDPOINT -u USERNAME -p` but not from PHPMyAdmin or your own web scripts, don't forget to [tell selinux to let your web server talk to the network](https://wiki.centos.org/TipsAndTricks/SelinuxBooleans#line-44) :) ``` sudo setsebool -P httpd_can_network_connect=1 ```
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
``` sudo nano /etc/phpmyadmin/config.inc.php --ADD LINES BELOW THE PMA CONFIG AREA AND FILL IN DETAILS-- $i++; $cfg['Servers'][$i]['host'] = '__FILL_IN_DETAILS__'; $cfg['Servers'][$i]['port'] = '3306'; $cfg['Servers'][$i]['socket'] = ''; $cfg['Servers'][$i]['connect_type'] = 'tcp'; $cfg['Servers'][$i]['extension'] = 'mysql'; $cfg['Servers'][$i]['compress'] = FALSE; $cfg['Servers'][$i]['auth_type'] = 'config'; $cfg['Servers'][$i]['user'] = '__FILL_IN_DETAILS__'; $cfg['Servers'][$i]['password'] = '__FILL_IN_DETAILS__'; ``` Save and Exit. Refresh your phpmyadmin page and you'll see a dropdown with the server that you just added[![enter image description here](https://i.stack.imgur.com/611W4.png)](https://i.stack.imgur.com/611W4.png) Source: <https://github.com/andrewpuch/phpmyadmin_connect_to_rds>, <https://www.youtube.com/watch?v=Bz-4wTGD2_Q>
First try this : **mysql -h xxxxx.xxxxxxx.xx-xx-2.rds.amazonaws.com -u root -p** // Your RDS server. If it waits and doesn't prompt for the password then you would need to check security group and add 3306 outbound to your Web Tier.
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
In Debian Lenny using the phpmyadmin from the repo add this to /etc/phpmyadmin/config.inc.php : ``` $i++; $cfg['Servers'][$i]['host'] = 'xxxxx.xxxxxxxxxx.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['port'] = '3306'; $cfg['Servers'][$i]['socket'] = ''; $cfg['Servers'][$i]['connect_type'] = 'tcp'; $cfg['Servers'][$i]['extension'] = 'mysql'; $cfg['Servers'][$i]['compress'] = TRUE; $cfg['Servers'][$i]['auth_type'] = 'config'; $cfg['Servers'][$i]['user'] = 'xxxxxxxxxxxx'; $cfg['Servers'][$i]['password'] = 'xxxxxxxxxxxxxxxxxx'; ```
You need to add the RDS instance as an additional server listed on PHPMyAdmin while granting the host PHPMyAdmin access to your RDS instance. More details from this blog post on [How to remotely manage an Amazon RDS instance with PHPMyAdmin](http://blog.benkuhl.com/2010/12/how-to-remotely-manage-an-amazon-rds-instance-with-phpmyadmin/): > > The one thing I had trouble with was the DB Security Group setup. When you go to add access for an CIDR/IP it provides a recommended value. It took some messing around to determine that this default value isn’t actually what needed to be there. If you’re not able to connect to your instance when it’s all said and done, be sure to double check this value. The IP they provided did not match the IP address that was provided to us by our ISP. Once you’ve created your DB Instance and setup the security group you’re good to go. > > > I’m going to assume you’ve already got PHPMyAdmin up and running. What you need to do is modify config.inc.php to recognize the new server. > > >
4,402,482
I can't get PHPMyAdmin to connect to my Amazon RDS instance. I've granted permissions for my IP address to the DB Security Group which has access to this database I'm trying to access. Here's what I'm working with... ``` $cfg['Servers'][$i]['pmadb'] = $dbname; $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; $cfg['Servers'][$i]['relation'] = 'pma_relation'; $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; $cfg['Servers'][$i]['history'] = 'pma_history'; $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /* Uncomment the following to enable logging in to passwordless accounts, * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /* Advance to next server for rest of config */ $i++; } $cfg['Servers'][$i]['auth_type'] = 'http'; //is this correct? $cfg['Servers'][$i]['user'] = 'MASTER-USER'; $cfg['Servers'][$i]['password'] = 'MASTER-USER-PASSWORD'; $cfg['Servers'][$i]['hide_db'] = '(mysql|information_schema|phpmyadmin)'; /* Server parameters */ $cfg['Servers'][$i]['host'] = 'MY-DB.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['connection_type'] = 'socket'; $cfg['Servers'][$i]['port'] = PORT; ``` I'm not sure if my configuration is correct. I'm getting this error: > > #2013 - Lost connection to MySQL server at 'reading initial communication packet', system error: 110 > > > Does anyone have any advice?
2010/12/09
[ "https://Stackoverflow.com/questions/4402482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
In Debian Lenny using the phpmyadmin from the repo add this to /etc/phpmyadmin/config.inc.php : ``` $i++; $cfg['Servers'][$i]['host'] = 'xxxxx.xxxxxxxxxx.us-east-1.rds.amazonaws.com'; $cfg['Servers'][$i]['port'] = '3306'; $cfg['Servers'][$i]['socket'] = ''; $cfg['Servers'][$i]['connect_type'] = 'tcp'; $cfg['Servers'][$i]['extension'] = 'mysql'; $cfg['Servers'][$i]['compress'] = TRUE; $cfg['Servers'][$i]['auth_type'] = 'config'; $cfg['Servers'][$i]['user'] = 'xxxxxxxxxxxx'; $cfg['Servers'][$i]['password'] = 'xxxxxxxxxxxxxxxxxx'; ```
First try this : **mysql -h xxxxx.xxxxxxx.xx-xx-2.rds.amazonaws.com -u root -p** // Your RDS server. If it waits and doesn't prompt for the password then you would need to check security group and add 3306 outbound to your Web Tier.
139,990
If an algorithm for $SAT$ runs in $O(n^{\log n})$ time, and if $L$ belongs to $\mathsf{NP}$, is there an algorithm for $L$ that runs in $O(n^{\log n})$ time?
2021/05/06
[ "https://cs.stackexchange.com/questions/139990", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/136310/" ]
As $\mathrm{SAT}$ is $\mathrm{NP}$-complete, we know that there is a polytime reduction from our language $L$ to $\mathrm{SAT}$. However, this reduction can involve a polynomial blowup of the input size. This means that an input $w$ to $L$ could be mapped to a formula $\phi\_w$ such that $|\phi\_w| \approx |w|^k$ for some constant $k$. Running our hypothetical algorithm for $\mathrm{SAT}$ on $\phi\_w$ takes time $O(|\phi\_w|^{\log |\phi\_w|}) = O((|w|^k)^{\log |w|^k}) = O(|w|^{k^2 \log |w|})$ time. But $O(n^{k^2 \log n}) \neq O(n^{\log n})$. Thus, there is no immediate reason why the assumption would yield an $O(n^{\log n})$-algorithm for $L$.
Since any input x for L can be reduced to SAT in O(|x|^c) time, the created SAT instance will have size at most n=O(|x|^c). So the n^(lg n)-time algorithm for SAT will be an |x|^O(lg |x|)-time algorithm for L.
8,305,527
What is a regular expression to allow letters only, with no spaces or numbers, with a length of 20 characters? Some examples of acceptable usernames: ``` ask1kew supacool sec1entertainment ThatPerson1 Alexking ``` Some examples of unacceptable usernames: ``` No_problem1 a_a_sidkd Thenamethatismorethen20characterslong ```
2011/11/29
[ "https://Stackoverflow.com/questions/8305527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/604023/" ]
This should work if you're limiting yourself to ASCII: ```none /\A[a-z0-9]{,20}\z/i ``` That will also match an empty string though so you might want to add a lower limit (5 in this example): ```none /\A[a-z0-9]{5,20}\z/i ``` If you wanted to be adventurous and allow non-ASCII letters and you're using Ruby 1.9 then you could use this: ```none /\A\p{Alnum}{5,20}\z/ /\A\p{Alnum}{,20}\z/ # If no lower limit on length is desired. ```
`^[a-zA-Z0-9]{1,20}$` `{1,20}` is `{min, max}` so you could set it to `{5,20}` to limit it to minimum of 5 chars and a max of 20.
37,938,413
Is there a function or something in laravel which I can use to make first letter uppercase in breadcrumbs? This is what I'm using right now but in my links and routes are all lowercase letters and if I go and try to update all will be very time consuming.. ``` <ul class="breadcrumb"> <li> <i class="glyphicon glyphicon-home"></i> <a href="{{ URL::to('/') }}">Home</a> / @for($i = 0; $i <= count(Request::segments()); $i++) <a href="">{{Request::segment($i)}}</a> @if($i < count(Request::segments()) & $i > 0) / @endif </li> @endfor </ul> ``` Or this isn't correct way of making breadcrumbs in laravel 4.2?
2016/06/21
[ "https://Stackoverflow.com/questions/37938413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Yes and no. It is not possible at the time of writing, if you want to do it only with browser client side javascript, because twitter does not allow cross site requests. Browsers execute javascript code in a sandbox environment, which does not allow you to do a request to another domain as yours, except the 3rd party domain explicitly allows it. This is called [Http Access Control (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) However the twitter api can of course be consumed by a javascript app, which is not running in a browser. So if you want this functionality for your website and you want to code it only in javascript, you would have to write a backend api for your website in nodejs or use another 3rd party service like @RationalDev suggested
If you check the twitter's api documentation, you can see how to do the login. I think your question is how insert a plugin to login similar than facebook but I think they don't did any library. When the user clicks the loggin button you must send a post request to twitter to get the oauth\_token: Example: POST request to "api.twitter.com/oauth/request\_token" and then, twitter provides you the oauth\_token and the oauth\_token\_secret (private). Once you did this step you must to redirect the user to twitter. Example: GET request to "api.twitter.com/oauth/authenticate?oauth\_token=YOUR\_OAUTH\_TOKEN\_GIVEN\_IN\_STEP\_1" If everything has gone well twitter response you with the oauth\_token and a verifier oauth token. Let's set up the last step! Send a post request to twitter api endpoint with the verifier oauth token provided in the response of step 2. Example: POST request to "api.twitter.com/oauth/access\_token" sending the verifier oauth token as post parameter. And then twitter response with a secret token and the user token, you can save it and feel free to use it in any twitter endpoint. Login documentation: <https://dev.twitter.com/web/sign-in/implementing> Browser auth flow: <https://dev.twitter.com/web/sign-in/desktop-browser> Regards!
37,938,413
Is there a function or something in laravel which I can use to make first letter uppercase in breadcrumbs? This is what I'm using right now but in my links and routes are all lowercase letters and if I go and try to update all will be very time consuming.. ``` <ul class="breadcrumb"> <li> <i class="glyphicon glyphicon-home"></i> <a href="{{ URL::to('/') }}">Home</a> / @for($i = 0; $i <= count(Request::segments()); $i++) <a href="">{{Request::segment($i)}}</a> @if($i < count(Request::segments()) & $i > 0) / @endif </li> @endfor </ul> ``` Or this isn't correct way of making breadcrumbs in laravel 4.2?
2016/06/21
[ "https://Stackoverflow.com/questions/37938413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you mean only JavaScript and HTML on the client, there are some third party libraries. Auth0 is popular and has [instructions for Twitter](https://auth0.com/docs/connections/social/twitter). Another possible solution is to use Firebase auth. It has a [JavaScript API which can be used as follows](https://firebase.google.com/docs/auth/web/twitter-login#redirect-mode): > > Create an instance of the Twitter provider object: > > > ``` var provider = new firebase.auth.TwitterAuthProvider(); ``` > > Authenticate with Firebase using the Twitter provider object. You can prompt your users to sign in with their Twitter accounts either by opening a pop-up window or by redirecting to the sign-in page. > > >
If you check the twitter's api documentation, you can see how to do the login. I think your question is how insert a plugin to login similar than facebook but I think they don't did any library. When the user clicks the loggin button you must send a post request to twitter to get the oauth\_token: Example: POST request to "api.twitter.com/oauth/request\_token" and then, twitter provides you the oauth\_token and the oauth\_token\_secret (private). Once you did this step you must to redirect the user to twitter. Example: GET request to "api.twitter.com/oauth/authenticate?oauth\_token=YOUR\_OAUTH\_TOKEN\_GIVEN\_IN\_STEP\_1" If everything has gone well twitter response you with the oauth\_token and a verifier oauth token. Let's set up the last step! Send a post request to twitter api endpoint with the verifier oauth token provided in the response of step 2. Example: POST request to "api.twitter.com/oauth/access\_token" sending the verifier oauth token as post parameter. And then twitter response with a secret token and the user token, you can save it and feel free to use it in any twitter endpoint. Login documentation: <https://dev.twitter.com/web/sign-in/implementing> Browser auth flow: <https://dev.twitter.com/web/sign-in/desktop-browser> Regards!
37,938,413
Is there a function or something in laravel which I can use to make first letter uppercase in breadcrumbs? This is what I'm using right now but in my links and routes are all lowercase letters and if I go and try to update all will be very time consuming.. ``` <ul class="breadcrumb"> <li> <i class="glyphicon glyphicon-home"></i> <a href="{{ URL::to('/') }}">Home</a> / @for($i = 0; $i <= count(Request::segments()); $i++) <a href="">{{Request::segment($i)}}</a> @if($i < count(Request::segments()) & $i > 0) / @endif </li> @endfor </ul> ``` Or this isn't correct way of making breadcrumbs in laravel 4.2?
2016/06/21
[ "https://Stackoverflow.com/questions/37938413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This javascript snippet is a working example of how to do this. You can try it and tweak it: <https://jsfiddle.net/s3egg5h7/43/> As pointed out, a Javascript-only solution requires a 3rd-party service, in this case <https://oauth.io>. Even if you do not want to use the 3rd-party service, the snippet is useful since you do not have to write any code to test out Twitter APIs to see they return what you need It is pretty short: ``` $('#twitter-button').on('click', function() { // Initialize with your OAuth.io app public key OAuth.initialize('OAUTH_IO_KEY'); // Use popup for OAuth OAuth.popup('twitter').then(twitter => { console.log('twitter:', twitter); // Retrieves user data from OAuth provider by using #get() and // OAuth provider url twitter.get('/1.1/account/verify_credentials.json?include_email=true').then(data => { console.log('self data:', data); }) }); }) ``` It requires a few external references, e.g., bootstrap css, oauthio javascript open-source library, etc. I think using a 3rd-party service may make sense since it hides all the inconsistencies in the OAuth implementation of different providers, like Twitter, Facebook, etc. I did not create this code so for attribution purposes, please refer to: <https://coderwall.com/p/t46-ta/javascript-twitter-social-login-button-for-oauth>
If you check the twitter's api documentation, you can see how to do the login. I think your question is how insert a plugin to login similar than facebook but I think they don't did any library. When the user clicks the loggin button you must send a post request to twitter to get the oauth\_token: Example: POST request to "api.twitter.com/oauth/request\_token" and then, twitter provides you the oauth\_token and the oauth\_token\_secret (private). Once you did this step you must to redirect the user to twitter. Example: GET request to "api.twitter.com/oauth/authenticate?oauth\_token=YOUR\_OAUTH\_TOKEN\_GIVEN\_IN\_STEP\_1" If everything has gone well twitter response you with the oauth\_token and a verifier oauth token. Let's set up the last step! Send a post request to twitter api endpoint with the verifier oauth token provided in the response of step 2. Example: POST request to "api.twitter.com/oauth/access\_token" sending the verifier oauth token as post parameter. And then twitter response with a secret token and the user token, you can save it and feel free to use it in any twitter endpoint. Login documentation: <https://dev.twitter.com/web/sign-in/implementing> Browser auth flow: <https://dev.twitter.com/web/sign-in/desktop-browser> Regards!
37,938,413
Is there a function or something in laravel which I can use to make first letter uppercase in breadcrumbs? This is what I'm using right now but in my links and routes are all lowercase letters and if I go and try to update all will be very time consuming.. ``` <ul class="breadcrumb"> <li> <i class="glyphicon glyphicon-home"></i> <a href="{{ URL::to('/') }}">Home</a> / @for($i = 0; $i <= count(Request::segments()); $i++) <a href="">{{Request::segment($i)}}</a> @if($i < count(Request::segments()) & $i > 0) / @endif </li> @endfor </ul> ``` Or this isn't correct way of making breadcrumbs in laravel 4.2?
2016/06/21
[ "https://Stackoverflow.com/questions/37938413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Yes and no. It is not possible at the time of writing, if you want to do it only with browser client side javascript, because twitter does not allow cross site requests. Browsers execute javascript code in a sandbox environment, which does not allow you to do a request to another domain as yours, except the 3rd party domain explicitly allows it. This is called [Http Access Control (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS) However the twitter api can of course be consumed by a javascript app, which is not running in a browser. So if you want this functionality for your website and you want to code it only in javascript, you would have to write a backend api for your website in nodejs or use another 3rd party service like @RationalDev suggested
This javascript snippet is a working example of how to do this. You can try it and tweak it: <https://jsfiddle.net/s3egg5h7/43/> As pointed out, a Javascript-only solution requires a 3rd-party service, in this case <https://oauth.io>. Even if you do not want to use the 3rd-party service, the snippet is useful since you do not have to write any code to test out Twitter APIs to see they return what you need It is pretty short: ``` $('#twitter-button').on('click', function() { // Initialize with your OAuth.io app public key OAuth.initialize('OAUTH_IO_KEY'); // Use popup for OAuth OAuth.popup('twitter').then(twitter => { console.log('twitter:', twitter); // Retrieves user data from OAuth provider by using #get() and // OAuth provider url twitter.get('/1.1/account/verify_credentials.json?include_email=true').then(data => { console.log('self data:', data); }) }); }) ``` It requires a few external references, e.g., bootstrap css, oauthio javascript open-source library, etc. I think using a 3rd-party service may make sense since it hides all the inconsistencies in the OAuth implementation of different providers, like Twitter, Facebook, etc. I did not create this code so for attribution purposes, please refer to: <https://coderwall.com/p/t46-ta/javascript-twitter-social-login-button-for-oauth>
37,938,413
Is there a function or something in laravel which I can use to make first letter uppercase in breadcrumbs? This is what I'm using right now but in my links and routes are all lowercase letters and if I go and try to update all will be very time consuming.. ``` <ul class="breadcrumb"> <li> <i class="glyphicon glyphicon-home"></i> <a href="{{ URL::to('/') }}">Home</a> / @for($i = 0; $i <= count(Request::segments()); $i++) <a href="">{{Request::segment($i)}}</a> @if($i < count(Request::segments()) & $i > 0) / @endif </li> @endfor </ul> ``` Or this isn't correct way of making breadcrumbs in laravel 4.2?
2016/06/21
[ "https://Stackoverflow.com/questions/37938413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you mean only JavaScript and HTML on the client, there are some third party libraries. Auth0 is popular and has [instructions for Twitter](https://auth0.com/docs/connections/social/twitter). Another possible solution is to use Firebase auth. It has a [JavaScript API which can be used as follows](https://firebase.google.com/docs/auth/web/twitter-login#redirect-mode): > > Create an instance of the Twitter provider object: > > > ``` var provider = new firebase.auth.TwitterAuthProvider(); ``` > > Authenticate with Firebase using the Twitter provider object. You can prompt your users to sign in with their Twitter accounts either by opening a pop-up window or by redirecting to the sign-in page. > > >
This javascript snippet is a working example of how to do this. You can try it and tweak it: <https://jsfiddle.net/s3egg5h7/43/> As pointed out, a Javascript-only solution requires a 3rd-party service, in this case <https://oauth.io>. Even if you do not want to use the 3rd-party service, the snippet is useful since you do not have to write any code to test out Twitter APIs to see they return what you need It is pretty short: ``` $('#twitter-button').on('click', function() { // Initialize with your OAuth.io app public key OAuth.initialize('OAUTH_IO_KEY'); // Use popup for OAuth OAuth.popup('twitter').then(twitter => { console.log('twitter:', twitter); // Retrieves user data from OAuth provider by using #get() and // OAuth provider url twitter.get('/1.1/account/verify_credentials.json?include_email=true').then(data => { console.log('self data:', data); }) }); }) ``` It requires a few external references, e.g., bootstrap css, oauthio javascript open-source library, etc. I think using a 3rd-party service may make sense since it hides all the inconsistencies in the OAuth implementation of different providers, like Twitter, Facebook, etc. I did not create this code so for attribution purposes, please refer to: <https://coderwall.com/p/t46-ta/javascript-twitter-social-login-button-for-oauth>
4,022,426
I am new to Iphone.How to create file browser in iphone ? I wish to show all the files and folders in the iphone.How to do this?
2010/10/26
[ "https://Stackoverflow.com/questions/4022426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/482568/" ]
Unless you are on a jailbroken phone, your app can only access files within its own "sandbox". There are [three folders](http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/RuntimeEnvironment/RuntimeEnvironment.html#//apple_ref/doc/uid/TP40007072-CH2-SW12) your app can access, which contain data specific to your application. Your app will not be able to access file data outside these folders. With that caveat in mind, you would likely use: 1. [`NSFileManager`](http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSFileManager_Class/Reference/Reference.html) and [`NSDirectoryEnumerator`](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDirectoryEnumerator_Class/Reference/Reference.html) to build a data source to a table view 2. [`UITableView`](http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html) to present the list of files and folders obtained from step 1 3. [`UINavigationController`](http://developer.apple.com/library/ios/#documentation/uikit/reference/UINavigationController_Class/Reference/Reference.html) to provide a navigation stack for walking through a hierarchy of folders: a stack of `UITableView` instances to browse the list of accessible files and folders within your application's sandbox.
If you are producing this for the App Store, I would suggest against exposing such a control even for your application's data. It violates the Human Interface Guidelines and most likely will be rejected. From the [iPad Human Interface Guidelines](http://developer.apple.com/library/ios/#documentation/general/conceptual/ipadhig/DesignGuidelines/DesignGuidelines.html%23//apple_ref/doc/uid/TP40009446-CH3-SW32): > > Although iPad applications can allow > people to create and manipulate files, > this does not mean that people should > have a sense of the file system on > iPad. > > > On iPad, there is no application > analogous to the Mac OS X Finder, and > people should not be asked to interact > with files as they do on a computer. > In particular, people should not be > faced with anything that encourages > them to think about file types or > locations, such as: > > > * An open or save dialog that exposes a file hierarchy > * Information about the permissions status of files > > >
9,735,164
How can I make `find` apply my shell's defined functions and aliases inside its *exec* parameter? For example I have defined a function analogous to **bzip2** but using **7z**: > > function 7zip() { for f in $@; do ls -alF "$f"; 7za a -t7z -m0=lzma > -mx=9 -mfb=64 -md=64m -ms=on "$f.7z" "$f" && touch -r "$f" "$f.7z" && rm -fv "$f" && ls -alF "$f.7z"; done; } > > > When I find files older than 7 days to compress: ``` find . -mtime +7 -name "G*.html" -execdir 7zip {} + ``` Rather than expanding **7zip** it errors Command Not Found. This is all inside a shell script.
2012/03/16
[ "https://Stackoverflow.com/questions/9735164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1069375/" ]
You can export a function definition with: ``` export -f 7zipi ``` but using an indentifier whose name begins with a number is asking for trouble. Try changing the name to something sensible. (eg "f7zipi", or "\_7zipi")
Being the impatient coder than I am, for now I changed it around to multiple lines with: ``` hitlist=$(find . -mtime +7 -name "G*.html") 7zipi $hitlist |awk ' !x[$0]++' ``` That *awk* bit at the end there btw is so that the output only prints lines not seen before yet, so that it doesn't clutter with a zillion lines of: ``` 7-Zip (A) 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18 p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,2 CPUs) Compressing [Content] Everything is Ok ``` *NOT* really the answer though; I'd still like **find** to use my macros generally.
9,735,164
How can I make `find` apply my shell's defined functions and aliases inside its *exec* parameter? For example I have defined a function analogous to **bzip2** but using **7z**: > > function 7zip() { for f in $@; do ls -alF "$f"; 7za a -t7z -m0=lzma > -mx=9 -mfb=64 -md=64m -ms=on "$f.7z" "$f" && touch -r "$f" "$f.7z" && rm -fv "$f" && ls -alF "$f.7z"; done; } > > > When I find files older than 7 days to compress: ``` find . -mtime +7 -name "G*.html" -execdir 7zip {} + ``` Rather than expanding **7zip** it errors Command Not Found. This is all inside a shell script.
2012/03/16
[ "https://Stackoverflow.com/questions/9735164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1069375/" ]
You can export a function definition with: ``` export -f 7zipi ``` but using an indentifier whose name begins with a number is asking for trouble. Try changing the name to something sensible. (eg "f7zipi", or "\_7zipi")
Seems that not every `find` will accept a function as an argument for `--execdir`. It did not work for me either in the original form or using `export -f`. However, if your make a script out of your function, it will work ``` find . -mtime +7 -name "G*.html" -execdir /path/to/script_7zipi {} + ```
9,735,164
How can I make `find` apply my shell's defined functions and aliases inside its *exec* parameter? For example I have defined a function analogous to **bzip2** but using **7z**: > > function 7zip() { for f in $@; do ls -alF "$f"; 7za a -t7z -m0=lzma > -mx=9 -mfb=64 -md=64m -ms=on "$f.7z" "$f" && touch -r "$f" "$f.7z" && rm -fv "$f" && ls -alF "$f.7z"; done; } > > > When I find files older than 7 days to compress: ``` find . -mtime +7 -name "G*.html" -execdir 7zip {} + ``` Rather than expanding **7zip** it errors Command Not Found. This is all inside a shell script.
2012/03/16
[ "https://Stackoverflow.com/questions/9735164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1069375/" ]
Being the impatient coder than I am, for now I changed it around to multiple lines with: ``` hitlist=$(find . -mtime +7 -name "G*.html") 7zipi $hitlist |awk ' !x[$0]++' ``` That *awk* bit at the end there btw is so that the output only prints lines not seen before yet, so that it doesn't clutter with a zillion lines of: ``` 7-Zip (A) 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18 p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,2 CPUs) Compressing [Content] Everything is Ok ``` *NOT* really the answer though; I'd still like **find** to use my macros generally.
Seems that not every `find` will accept a function as an argument for `--execdir`. It did not work for me either in the original form or using `export -f`. However, if your make a script out of your function, it will work ``` find . -mtime +7 -name "G*.html" -execdir /path/to/script_7zipi {} + ```
9,735,164
How can I make `find` apply my shell's defined functions and aliases inside its *exec* parameter? For example I have defined a function analogous to **bzip2** but using **7z**: > > function 7zip() { for f in $@; do ls -alF "$f"; 7za a -t7z -m0=lzma > -mx=9 -mfb=64 -md=64m -ms=on "$f.7z" "$f" && touch -r "$f" "$f.7z" && rm -fv "$f" && ls -alF "$f.7z"; done; } > > > When I find files older than 7 days to compress: ``` find . -mtime +7 -name "G*.html" -execdir 7zip {} + ``` Rather than expanding **7zip** it errors Command Not Found. This is all inside a shell script.
2012/03/16
[ "https://Stackoverflow.com/questions/9735164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1069375/" ]
All four of these command works just fine with the function call. Adjust your find specs as need be.. They all cater for spaces in file names. Personally, I can't see the point of shelling out to another bash instance, but I've included two versions which call bash. ``` IFS=$'\n'; f=($(find /tmp -maxdepth 1 -name "$USER.*")); f7zipi "${f[@]}" IFS=; find /tmp -maxdepth 1 -name "$USER.*" | while read -r f ;do f7zipi "$f"; done IFS=$'\n'; bash -c 'IFS=; f7zipi "$@"' 0 $(find /tmp -maxdepth 1 -name "$USER.*") find /tmp -maxdepth 1 -name "$USER.*" -exec bash -c 'IFS=; f7zipi "$@"' 0 {} +; ``` --- What follows is how I've set up the function, using GNU bash 4.1.5 in Ubuntu 10.04 BTW. You should use `local f` in your function, so that it **does not clash** with the calling script's variable of the same name. This is exactly what I added to my ~/.bashrc ``` function f7zipi() { local f for f in $@; do ls -alF "$f" 7za a -si -t7z -m0=lzma -mx=9 -mfb=64 \ -md=64m -ms=on "$f.7z" < "$f" && touch -r "$f" "$f.7z" && rm -fv "$f" && ls -alF "$f.7z" done } export -f f7zipi ``` When I only assign the above function into a terminal's bash command line, a script running from that command line fails when it calls the function... If I further apply `export -f f7zipi` to that same command line.. then the script succeeds... However the scipt only works for that particular commandline session. When the function and export are included into `~/bashrc`, the script works every time, in any bash session.. This is the test script ``` #!/bin/bash f=/tmp/$USER.abc g=/tmp/$USER.lmn rm -fv "$f" "$f".7z rm -fv "$g" "$g".7z printf 'abcdefg'>"$f" printf 'lmnopqr'>"$g" IFS=$'\n'; f=($(find /tmp -maxdepth 1 -name "$USER.*")); f7zipi "${f[@]}" exit ```
Being the impatient coder than I am, for now I changed it around to multiple lines with: ``` hitlist=$(find . -mtime +7 -name "G*.html") 7zipi $hitlist |awk ' !x[$0]++' ``` That *awk* bit at the end there btw is so that the output only prints lines not seen before yet, so that it doesn't clutter with a zillion lines of: ``` 7-Zip (A) 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18 p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,2 CPUs) Compressing [Content] Everything is Ok ``` *NOT* really the answer though; I'd still like **find** to use my macros generally.
9,735,164
How can I make `find` apply my shell's defined functions and aliases inside its *exec* parameter? For example I have defined a function analogous to **bzip2** but using **7z**: > > function 7zip() { for f in $@; do ls -alF "$f"; 7za a -t7z -m0=lzma > -mx=9 -mfb=64 -md=64m -ms=on "$f.7z" "$f" && touch -r "$f" "$f.7z" && rm -fv "$f" && ls -alF "$f.7z"; done; } > > > When I find files older than 7 days to compress: ``` find . -mtime +7 -name "G*.html" -execdir 7zip {} + ``` Rather than expanding **7zip** it errors Command Not Found. This is all inside a shell script.
2012/03/16
[ "https://Stackoverflow.com/questions/9735164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1069375/" ]
All four of these command works just fine with the function call. Adjust your find specs as need be.. They all cater for spaces in file names. Personally, I can't see the point of shelling out to another bash instance, but I've included two versions which call bash. ``` IFS=$'\n'; f=($(find /tmp -maxdepth 1 -name "$USER.*")); f7zipi "${f[@]}" IFS=; find /tmp -maxdepth 1 -name "$USER.*" | while read -r f ;do f7zipi "$f"; done IFS=$'\n'; bash -c 'IFS=; f7zipi "$@"' 0 $(find /tmp -maxdepth 1 -name "$USER.*") find /tmp -maxdepth 1 -name "$USER.*" -exec bash -c 'IFS=; f7zipi "$@"' 0 {} +; ``` --- What follows is how I've set up the function, using GNU bash 4.1.5 in Ubuntu 10.04 BTW. You should use `local f` in your function, so that it **does not clash** with the calling script's variable of the same name. This is exactly what I added to my ~/.bashrc ``` function f7zipi() { local f for f in $@; do ls -alF "$f" 7za a -si -t7z -m0=lzma -mx=9 -mfb=64 \ -md=64m -ms=on "$f.7z" < "$f" && touch -r "$f" "$f.7z" && rm -fv "$f" && ls -alF "$f.7z" done } export -f f7zipi ``` When I only assign the above function into a terminal's bash command line, a script running from that command line fails when it calls the function... If I further apply `export -f f7zipi` to that same command line.. then the script succeeds... However the scipt only works for that particular commandline session. When the function and export are included into `~/bashrc`, the script works every time, in any bash session.. This is the test script ``` #!/bin/bash f=/tmp/$USER.abc g=/tmp/$USER.lmn rm -fv "$f" "$f".7z rm -fv "$g" "$g".7z printf 'abcdefg'>"$f" printf 'lmnopqr'>"$g" IFS=$'\n'; f=($(find /tmp -maxdepth 1 -name "$USER.*")); f7zipi "${f[@]}" exit ```
Seems that not every `find` will accept a function as an argument for `--execdir`. It did not work for me either in the original form or using `export -f`. However, if your make a script out of your function, it will work ``` find . -mtime +7 -name "G*.html" -execdir /path/to/script_7zipi {} + ```
34,352,840
I am using an extendible hash and I want to have strings as keys. The problem is that the current hash function that I am using iterates over the whole string/key and I think that this is pretty bad for the program's performance since the hash function is called multiple times especially when I am splitting buckets. **Current hash function** ``` int hash(const string& key) { int seed = 131; unsigned long hash = 0; for(unsigned i = 0; i < key.length(); i++) { hash = (hash * seed) + key[i]; } return hash; } ``` The keys could be as long as 40 characters. **Example of string/key** ``` string key = "from-to condition" ``` I have searched over the internet for a better one but I didn't find anything to match my case. Any suggestions?
2015/12/18
[ "https://Stackoverflow.com/questions/34352840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4484809/" ]
You should prefer to use `std::hash` unless measurement shows that you can do better. To limit the number of characters it uses, use something like: ``` const auto limit = min(key.length(), 16); for(unsigned i = 0; i < limit; i++) ``` You will want to experiment to find the best value of 16 to use. I would actually expect the performance to get worse (because you will have more collisions). If your strings were several k, then limiting to the first 64 bytes might well be worth while. Depending on your strings, it might be worth starting not at the beginning. For example, hashing filenames you would probably do better using the characters between 20 and 5 from the end (ignore the often constant pathname prefix, and the file extension). But you still have to measure.
You can directly use `std::hash`[link](http://en.cppreference.com/w/cpp/string/basic_string/hash "std::hash") instead of implementing your own function. ``` #include <iostream> #include <functional> #include <string> size_t hash(const std::string& key) { std::hash<std::string> hasher; return hasher(key); } int main() { std::cout << hash("abc") << std::endl; return 0; } ``` See this code here: <https://ideone.com/4U89aU>
34,352,840
I am using an extendible hash and I want to have strings as keys. The problem is that the current hash function that I am using iterates over the whole string/key and I think that this is pretty bad for the program's performance since the hash function is called multiple times especially when I am splitting buckets. **Current hash function** ``` int hash(const string& key) { int seed = 131; unsigned long hash = 0; for(unsigned i = 0; i < key.length(); i++) { hash = (hash * seed) + key[i]; } return hash; } ``` The keys could be as long as 40 characters. **Example of string/key** ``` string key = "from-to condition" ``` I have searched over the internet for a better one but I didn't find anything to match my case. Any suggestions?
2015/12/18
[ "https://Stackoverflow.com/questions/34352840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4484809/" ]
You should prefer to use `std::hash` unless measurement shows that you can do better. To limit the number of characters it uses, use something like: ``` const auto limit = min(key.length(), 16); for(unsigned i = 0; i < limit; i++) ``` You will want to experiment to find the best value of 16 to use. I would actually expect the performance to get worse (because you will have more collisions). If your strings were several k, then limiting to the first 64 bytes might well be worth while. Depending on your strings, it might be worth starting not at the beginning. For example, hashing filenames you would probably do better using the characters between 20 and 5 from the end (ignore the often constant pathname prefix, and the file extension). But you still have to measure.
> > I am using an extendible hash and I want to have strings as keys. > > > As mentioned before, use `std::hash` until there is a good reason not to. > > The problem is that the current hash function that I am using iterates over the whole string/key and I think that this is pretty bad... > > > It's an understandable thought, but is actually unlikely to be a real concern. > > (anticipating) why? > > > A quick scan over stack overflow will reveal many experienced developers talking about caches and cache lines. (forgive me if I'm teaching my grandmother to suck eggs) A modern CPU is incredibly quick at processing instructions and performing (very complex) arithmetic. In almost all cases, what limits its performance is having to talk to memory across a bus, which is by comparison, horribly slow. So chip designers build in memory caches - extremely fast memory that sits in the CPU (and therefore does not have to be communicated with over a slow bus). Unhappily, there is only so much space available [plus heat constraints - a topic for another day] for this cache memory so the CPU must treat it like an OS does a disk cache, flushing memory and reading in memory as and when it needs to. As mentioned, communicating across the bus is slow - (simply put) it requires all the electronic components on the motherboard to stop and synchronise with each other. This wastes a horrible amount of time [This would be a fantastic point to go into a discussion about the propagation of electronic signals across the motherboard being constrained by approximately half the speed of light - it's fascinating but there's only so much space here and I have only so much time]. So rather than transfer one byte, word or longword at a time, the memory is accessed in chunks - called *cache lines*. It turns out that this is a good decision by chip designers because they understand that most memory is accessed sequentially - because most programs spend most of their time accessing memory linearly (such as when calculating a hash, comparing strings or objects, transforming sequences, copying and initialising sequences and so on). What's the upshot of all this? Well, bizarrely, if your string is not already in-cache it turns of that reading one byte of it is almost exactly as expensive as reading *all* the bytes in the first (say) 128 bytes of it. Plus, because the cache circuitry assumes that memory access is linear, it will begin a fetch of the next *cache line* as soon as it has fetched your first one. It will do this while your CPU is performing its hash computation. I hope you can see that in this case, even if your string was many thousands of bytes long, and you chose to only hash (say) every 128th byte, all you would be doing would be to compute a very much inferior hash which still causing the memory cache to halt the processor while it fetched large chunks of unused memory. **It would take just as long - for a worse result!** > > Having said that, what are good reasons not to use the standard implementation? > > > Only when: 1. The users are complaining that your software is too slow to be useful, and 2. The program is verifiably CPU-bound (using 100% of CPU time), and 3. The program is not wasting any cycles by spinning, and 4. Careful profiling has revealed that the program's biggest bottleneck is the hash function, and 5. Independent analysis by another experienced developer confirms that there is no way to improve the algorithm (for example by calling hash less often). **In short, almost never.**
34,352,840
I am using an extendible hash and I want to have strings as keys. The problem is that the current hash function that I am using iterates over the whole string/key and I think that this is pretty bad for the program's performance since the hash function is called multiple times especially when I am splitting buckets. **Current hash function** ``` int hash(const string& key) { int seed = 131; unsigned long hash = 0; for(unsigned i = 0; i < key.length(); i++) { hash = (hash * seed) + key[i]; } return hash; } ``` The keys could be as long as 40 characters. **Example of string/key** ``` string key = "from-to condition" ``` I have searched over the internet for a better one but I didn't find anything to match my case. Any suggestions?
2015/12/18
[ "https://Stackoverflow.com/questions/34352840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4484809/" ]
> > I am using an extendible hash and I want to have strings as keys. > > > As mentioned before, use `std::hash` until there is a good reason not to. > > The problem is that the current hash function that I am using iterates over the whole string/key and I think that this is pretty bad... > > > It's an understandable thought, but is actually unlikely to be a real concern. > > (anticipating) why? > > > A quick scan over stack overflow will reveal many experienced developers talking about caches and cache lines. (forgive me if I'm teaching my grandmother to suck eggs) A modern CPU is incredibly quick at processing instructions and performing (very complex) arithmetic. In almost all cases, what limits its performance is having to talk to memory across a bus, which is by comparison, horribly slow. So chip designers build in memory caches - extremely fast memory that sits in the CPU (and therefore does not have to be communicated with over a slow bus). Unhappily, there is only so much space available [plus heat constraints - a topic for another day] for this cache memory so the CPU must treat it like an OS does a disk cache, flushing memory and reading in memory as and when it needs to. As mentioned, communicating across the bus is slow - (simply put) it requires all the electronic components on the motherboard to stop and synchronise with each other. This wastes a horrible amount of time [This would be a fantastic point to go into a discussion about the propagation of electronic signals across the motherboard being constrained by approximately half the speed of light - it's fascinating but there's only so much space here and I have only so much time]. So rather than transfer one byte, word or longword at a time, the memory is accessed in chunks - called *cache lines*. It turns out that this is a good decision by chip designers because they understand that most memory is accessed sequentially - because most programs spend most of their time accessing memory linearly (such as when calculating a hash, comparing strings or objects, transforming sequences, copying and initialising sequences and so on). What's the upshot of all this? Well, bizarrely, if your string is not already in-cache it turns of that reading one byte of it is almost exactly as expensive as reading *all* the bytes in the first (say) 128 bytes of it. Plus, because the cache circuitry assumes that memory access is linear, it will begin a fetch of the next *cache line* as soon as it has fetched your first one. It will do this while your CPU is performing its hash computation. I hope you can see that in this case, even if your string was many thousands of bytes long, and you chose to only hash (say) every 128th byte, all you would be doing would be to compute a very much inferior hash which still causing the memory cache to halt the processor while it fetched large chunks of unused memory. **It would take just as long - for a worse result!** > > Having said that, what are good reasons not to use the standard implementation? > > > Only when: 1. The users are complaining that your software is too slow to be useful, and 2. The program is verifiably CPU-bound (using 100% of CPU time), and 3. The program is not wasting any cycles by spinning, and 4. Careful profiling has revealed that the program's biggest bottleneck is the hash function, and 5. Independent analysis by another experienced developer confirms that there is no way to improve the algorithm (for example by calling hash less often). **In short, almost never.**
You can directly use `std::hash`[link](http://en.cppreference.com/w/cpp/string/basic_string/hash "std::hash") instead of implementing your own function. ``` #include <iostream> #include <functional> #include <string> size_t hash(const std::string& key) { std::hash<std::string> hasher; return hasher(key); } int main() { std::cout << hash("abc") << std::endl; return 0; } ``` See this code here: <https://ideone.com/4U89aU>
3,412,699
Suppose you have the product of two expressions: $ 2^5$ \* $ 2^2$, the result will be : $ 2^{5+2}$ = $ 2^7$. This is because we know the exponent rule that if they have the same base, we can add the power. Is there a way to express the product of two expressions of different bases and powers into 1 expression with one base and power, like: $ 3^7$ \* $ 4^8$ = $ a^b$
2019/10/28
[ "https://math.stackexchange.com/questions/3412699", "https://math.stackexchange.com", "https://math.stackexchange.com/users/711602/" ]
No, the definition you gave is correct. Take for example $\mathbb N$ with discrete metric. Of course $\mathbb N$ is dense in it self. If you use $\mathcal B(x\_0,\varepsilon )\setminus \{x\_0\}$ instead of $\mathcal B(x\_0,\varepsilon )$, then when $\varepsilon <1$ and $n\in\mathbb N$, you'll get $$\mathcal B(n,\varepsilon )\setminus \{n\}=\emptyset,$$ what contradict density.
To rephrase the definition given, $$ \forall x\_0 \in B,\ \forall \varepsilon > 0,\ \exists a \in A,\ d(x\_0,a) < \varepsilon $$ where $d$ is the metric. If $x\_0 \in A$ already, then that's fine. But what's more interesting is that points of $B \setminus A$ also have points of $A$ arbitrarily close to them.
40,734,246
Consider the following (simplified) example where two lambda functions call each other, one of which also takes another function as an argument. I need to use lambda functions, since the functions also pass modified, nested functions between each other. ``` #include <iostream> using namespace std; auto f = [](int n, auto h) { if(n >= 5) return n; cout << "h is some function " << h(4.0) << end; auto func = [](int m){ return m*h(m); }; // some nested function return g(n+1,func); }; auto g = [](int n, auto h) { if(n >= 5) return n; cout << "h is some function " << h(5.0) << end; auto func = [](int m){ return m*h(m); }; // some nested function return f(n+1,func); }; int main() { auto initial_function = [](int m){ return m*m; }; f(1, initial_function); return 0.0; } ``` This returns the usual error *undeclared identifier 'g'* which was to expect since there is no header file. So my question is: What is the proper syntax to declare the two lambda functions?
2016/11/22
[ "https://Stackoverflow.com/questions/40734246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4114626/" ]
You need to capture the lambda inside `g` (or vice versa). `g` and `f` are variables which are **pointing** to a (unnamed) function. Making these lambdas doesn't make sense. Lambdas work best when you need a function in local scope. You will have to convert at-least one of them as a function and do a forward-declare for it to get this code working ``` int f(int n); auto g = [](int n) { if(n >= 5) return n; return f(n+1); }; int f(int n) { if(n >= 5) return n; return g(n+1); } int main() { f(1); return 0.0; } ``` Based on OP's edit, probably what the OP needs is ``` template<typename T1, typename T2> auto g(int n, const T1& f, const T2& h) { if(n >= 5) return n; cout << "h is some function " << h(5.0) << end; return f(n+1); } ``` To be called as: ``` auto h = [](int m) { return m*m; }; auto f = [h](int m) { return n >= 5 ? n : return g(n+1, f, h); }; g(n, f, h); ```
Use std::function to address the issue. ``` #include <functional> #include <iostream> std::function<int(int)> f; std::function<int(int)> g; int main() { f = [](int n) { if(n >= 5) return n; return g(n+1); }; g = [](int n) { if(n >= 5) return n; return f(n+1); }; std::cout << f(1) << std::endl; return 0; } ```
40,734,246
Consider the following (simplified) example where two lambda functions call each other, one of which also takes another function as an argument. I need to use lambda functions, since the functions also pass modified, nested functions between each other. ``` #include <iostream> using namespace std; auto f = [](int n, auto h) { if(n >= 5) return n; cout << "h is some function " << h(4.0) << end; auto func = [](int m){ return m*h(m); }; // some nested function return g(n+1,func); }; auto g = [](int n, auto h) { if(n >= 5) return n; cout << "h is some function " << h(5.0) << end; auto func = [](int m){ return m*h(m); }; // some nested function return f(n+1,func); }; int main() { auto initial_function = [](int m){ return m*m; }; f(1, initial_function); return 0.0; } ``` This returns the usual error *undeclared identifier 'g'* which was to expect since there is no header file. So my question is: What is the proper syntax to declare the two lambda functions?
2016/11/22
[ "https://Stackoverflow.com/questions/40734246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4114626/" ]
You need to capture the lambda inside `g` (or vice versa). `g` and `f` are variables which are **pointing** to a (unnamed) function. Making these lambdas doesn't make sense. Lambdas work best when you need a function in local scope. You will have to convert at-least one of them as a function and do a forward-declare for it to get this code working ``` int f(int n); auto g = [](int n) { if(n >= 5) return n; return f(n+1); }; int f(int n) { if(n >= 5) return n; return g(n+1); } int main() { f(1); return 0.0; } ``` Based on OP's edit, probably what the OP needs is ``` template<typename T1, typename T2> auto g(int n, const T1& f, const T2& h) { if(n >= 5) return n; cout << "h is some function " << h(5.0) << end; return f(n+1); } ``` To be called as: ``` auto h = [](int m) { return m*m; }; auto f = [h](int m) { return n >= 5 ? n : return g(n+1, f, h); }; g(n, f, h); ```
The type of a lambda is not well defined, so there isn't a straightfoward answer. I prefer @bashrc's answer, but if you insist on having two lambdas, this variation might do the job: ``` extern int (*f)(int n); auto g = [](int n) { if (n >= 5) return n; return f(n + 1); }; int (*f)(int n) = [](int n) { if (n >= 5) return n; return g(n + 1); }; int main() { f(1); return 0; } ```
40,734,246
Consider the following (simplified) example where two lambda functions call each other, one of which also takes another function as an argument. I need to use lambda functions, since the functions also pass modified, nested functions between each other. ``` #include <iostream> using namespace std; auto f = [](int n, auto h) { if(n >= 5) return n; cout << "h is some function " << h(4.0) << end; auto func = [](int m){ return m*h(m); }; // some nested function return g(n+1,func); }; auto g = [](int n, auto h) { if(n >= 5) return n; cout << "h is some function " << h(5.0) << end; auto func = [](int m){ return m*h(m); }; // some nested function return f(n+1,func); }; int main() { auto initial_function = [](int m){ return m*m; }; f(1, initial_function); return 0.0; } ``` This returns the usual error *undeclared identifier 'g'* which was to expect since there is no header file. So my question is: What is the proper syntax to declare the two lambda functions?
2016/11/22
[ "https://Stackoverflow.com/questions/40734246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4114626/" ]
You need to capture the lambda inside `g` (or vice versa). `g` and `f` are variables which are **pointing** to a (unnamed) function. Making these lambdas doesn't make sense. Lambdas work best when you need a function in local scope. You will have to convert at-least one of them as a function and do a forward-declare for it to get this code working ``` int f(int n); auto g = [](int n) { if(n >= 5) return n; return f(n+1); }; int f(int n) { if(n >= 5) return n; return g(n+1); } int main() { f(1); return 0.0; } ``` Based on OP's edit, probably what the OP needs is ``` template<typename T1, typename T2> auto g(int n, const T1& f, const T2& h) { if(n >= 5) return n; cout << "h is some function " << h(5.0) << end; return f(n+1); } ``` To be called as: ``` auto h = [](int m) { return m*m; }; auto f = [h](int m) { return n >= 5 ? n : return g(n+1, f, h); }; g(n, f, h); ```
This works on my machine: ``` #include <functional> #include <iostream> #include <stdio.h> using namespace std; extern function<int(int, function<int(int)>)> g; auto f = [](int n, function<int(int)> h) { if (n >= 5) return n; cout << "h is some function " << h(4.0) << endl; auto func = [h](int m) { return m*h(m); }; return g(n + 1, func); }; function<int(int, function<int(int)>)> g = [](int n, function<int(int)> h) { if (n >= 5) return n; cout << "h is some function " << h(5.0) << endl; auto func = [h](int m) { return m*h(m); }; return f(n + 1, func); }; int main() { auto initial_function = [](int m) { return m*m; }; f(1, initial_function); getchar(); return 0; // Return value of the function is int so its better to use 0 rather than 0.0 } ```
1,701
Throughout both my academic and professional career I've encountered situations where in such roles (as most of us would have), where as a happy go lucky graduate who doesn't know it all (but thought I did) would attend meetings and I wouldn't know what certain industry terminology meant or understood certain aspects of the project cycle. I would become really pedantic about asking stupid questions that should be (what I felt) well known. But, I wouldn't ask them in the meeting (especially in a group setting) purposely to not look stupid. To overcome this I would do two things: * I would always go home (after the day is done) and look up the terminology/subject matter and teach myself that way, so if the topic comes up again I'd be armed with the newly obtained knowledge. * I would wait until my superior came up to me and if they mentioned it, I would have a look of confusion on my face and then ask the question. (But this to me, seemed like I wasn't listening in the meeting and/or unprofessional). Which made me contemplate the best time to ask these questions to make myself seem less like I wasn't paying attention but more because I'm willing to learn. --- So, when is it okay to ask "stupid" questions in the workplace?
2017/08/12
[ "https://interpersonal.stackexchange.com/questions/1701", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/2167/" ]
**Note**: as the question specifically aims at meetings, this answer aligns to that scenario. You'll have to weigh up the problems you face, either look attentive and eager to learn by overcoming your fear of looking stupid or keep doing what you're currently doing. But, my advice is if someone knows and you don't, **just ask**. [Asking more questions is not only effective](https://www.inc.com/alison-davis/why-asking-dumb-questions-is-so-darn-smart.html), you learn a hell of a lot from asking even the most simple ones. Don't worry too much, though. You have several times you can ask and whom to ask (depending on your confidence): 1. *If and only if* you aren't disrupting the meeting or the person hosting the meeting, just ask the question there and then. i.e. > > "Sorry, could you elaborate on that?" > > > or > > "Sorry, what does XYZ mean?" > > > this will not only quench your worry about not looking like you're paying attention, it also has multiple benefits: You'll learn (rather than waiting the rest of the day to go home and read up on it) about it there and then, but it can also set the tone for the meeting (someone else might be in the same boat, and you've just set the bar for the types of questions you can ask, thus, an opportunity to learn more from more questions from your peers). 2. After the meeting pull the person who ran the meeting to the side (if you didn't want to disrupt them, or didn't want to engage within a group setting) and ask them to elaborate further on what they said. I'm sure most people wouldn't mind (unless it's something you've learnt in the office before and should already know) 3. If the person is a superior and you want to keep face with them, you can simply pull a trusted colleague to one side after the meeting and ask them about one of the problems you faced or compare notes (they might have something written down you didn't know about), sometimes with other programmers, I would compare notes and [rubberduck](https://en.wikipedia.org/wiki/Rubber_duck_debugging) them and learn that way. But, in a normal office environment, just simply ask them: > > "Hey, you know when they mentioned XYZ in the meeting, do you know any > more about that? I'm looking to learn a little more." > > > These options may make you come across as "stupid", but you'll also come across as someone who is willing to own up when they don't know something and someone who is wanting to learn more about the topic at hand. **Further Reading:** * [Why asking stupid questions is the smartest thing to do.](https://www.stroudinternational.com/latest-insights/stupid-questions) * [Why you should ask stupid questions.](http://www.yuhiro.de/why-you-should-ask-stupid-questions/)
When is it OK to ask "stupid" questions? Whenever you need to! You're absolutely right that it is very common for people to find themselves in these situations. The reason for that is that no one will know everything as soon as they begin (a new job, project, class, etc.). And *that* is why there is no reason at all to consider these questions stupid. That's the first point. Besides, industry terminology and project parameters both seem rather critical, and not-stupid, to me. The thing that would be "stupid," or not a good idea, let's say, is if you let yourself get behind just for not asking, if you undermine your own genius just to save yourself a little embarrassment ... when, in fact, the boss will probably be grateful that you're following along well enough to have intelligent, pertinent questions. But maybe what you're trying to ask is, "how do I know when I'm crossing the line from asking intelligent, pertinent questions ... to being pedantic about it?" The thing about pedants is that they're "excessively concerned with minor details." Will your boss look fondly on you if you keep interrupting his or her presentation for definitions to every word you haven't heard before or with every little question that pops into your head? No...probably not! How I draw the line is by asking (myself) questions like this: Can I follow along? Are the terms I'm NOT familiar with keeping me from understanding the presentation I'm listening to (or whatever), overall? If I answer yes and no, respectively, then I try to save my questions at least until the end, and if I can take thorough enough notes, maybe I can take what I *DID* learn and piece it together myself, after, by looking up the few terms I hadn't heard before on my own. Or if I can tell at the end that I *am* going to need a primer, I try to ask a brief, cogent question that gets right to the heart of whatever I'm not getting. It is also important to do what we can on our own, as much for our own minds as anything else, and when piecing together what I can, after, that's when I usually figure out what it really is that I don't understand. And then the next morning, I just try to get in the office maybe 10 minutes early and plainly tell the supervisor, "Hey, I was looking over what you were talking about and there's a bit here I just don't understand." They're usually really happy to be approached this way. But be prepared, because you may have to say, "Well, you see..." and break down what you do get so he or she will understand what you don't get. And just one more thing. I'm with you that it can be very embarrassing to have to raise your hand right in the middle of something, but sometimes it happens. It's really no big deal – who'll even know in 200 years, right? But when that happens, I've always found that you come across more intelligently when you can say, "If [blah, blah, blah...] and [blah, blah, blah,] too, then [question, question, question]?" instead of just, "what is [that]?" In other words, while it's true that "there are no stupid questions," it's best to make them as smart as you can!
1,701
Throughout both my academic and professional career I've encountered situations where in such roles (as most of us would have), where as a happy go lucky graduate who doesn't know it all (but thought I did) would attend meetings and I wouldn't know what certain industry terminology meant or understood certain aspects of the project cycle. I would become really pedantic about asking stupid questions that should be (what I felt) well known. But, I wouldn't ask them in the meeting (especially in a group setting) purposely to not look stupid. To overcome this I would do two things: * I would always go home (after the day is done) and look up the terminology/subject matter and teach myself that way, so if the topic comes up again I'd be armed with the newly obtained knowledge. * I would wait until my superior came up to me and if they mentioned it, I would have a look of confusion on my face and then ask the question. (But this to me, seemed like I wasn't listening in the meeting and/or unprofessional). Which made me contemplate the best time to ask these questions to make myself seem less like I wasn't paying attention but more because I'm willing to learn. --- So, when is it okay to ask "stupid" questions in the workplace?
2017/08/12
[ "https://interpersonal.stackexchange.com/questions/1701", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/2167/" ]
**Note**: as the question specifically aims at meetings, this answer aligns to that scenario. You'll have to weigh up the problems you face, either look attentive and eager to learn by overcoming your fear of looking stupid or keep doing what you're currently doing. But, my advice is if someone knows and you don't, **just ask**. [Asking more questions is not only effective](https://www.inc.com/alison-davis/why-asking-dumb-questions-is-so-darn-smart.html), you learn a hell of a lot from asking even the most simple ones. Don't worry too much, though. You have several times you can ask and whom to ask (depending on your confidence): 1. *If and only if* you aren't disrupting the meeting or the person hosting the meeting, just ask the question there and then. i.e. > > "Sorry, could you elaborate on that?" > > > or > > "Sorry, what does XYZ mean?" > > > this will not only quench your worry about not looking like you're paying attention, it also has multiple benefits: You'll learn (rather than waiting the rest of the day to go home and read up on it) about it there and then, but it can also set the tone for the meeting (someone else might be in the same boat, and you've just set the bar for the types of questions you can ask, thus, an opportunity to learn more from more questions from your peers). 2. After the meeting pull the person who ran the meeting to the side (if you didn't want to disrupt them, or didn't want to engage within a group setting) and ask them to elaborate further on what they said. I'm sure most people wouldn't mind (unless it's something you've learnt in the office before and should already know) 3. If the person is a superior and you want to keep face with them, you can simply pull a trusted colleague to one side after the meeting and ask them about one of the problems you faced or compare notes (they might have something written down you didn't know about), sometimes with other programmers, I would compare notes and [rubberduck](https://en.wikipedia.org/wiki/Rubber_duck_debugging) them and learn that way. But, in a normal office environment, just simply ask them: > > "Hey, you know when they mentioned XYZ in the meeting, do you know any > more about that? I'm looking to learn a little more." > > > These options may make you come across as "stupid", but you'll also come across as someone who is willing to own up when they don't know something and someone who is wanting to learn more about the topic at hand. **Further Reading:** * [Why asking stupid questions is the smartest thing to do.](https://www.stroudinternational.com/latest-insights/stupid-questions) * [Why you should ask stupid questions.](http://www.yuhiro.de/why-you-should-ask-stupid-questions/)
In your shoes, besides thinking about "when" to ask, I would think about *who* to ask. Your instinct of waiting until you are "offline" to ask is a good one. Unless you absolutely "need to" (you are one of the principal participants), you don't want to ask questions in front of a lot of people at a meeting. So the other issue is who to ask. Usually, that person is your boss. The reason is, the boss has the greatest stake in your development; the better you are, the better s/he is. A good boss will recognize that and try to accommodate your questions. There are some situations when you have a bad boss, or one who favors another co-worker over you, which would (largely) rule out that option. Who else can you ask? Basically, someone you can trust. Possibly a peer or co-worker, possibly a prospective (or actual) mentor. Executives have been known to confide in secretaries or janitors, and find that these people are more knowledgeable than they would have guessed. Having focused on who to ask, the question of "when to ask" is answered by "at a good time for them." The reason I emphasize "who" comes from Michael Lewis' "Liar's Poker." Someone asked a trainer, "how do you become successful at Salomon Brothers?" The trainer thought about it and said something like, "Most of you are going about it wrong. You are asking yourselves what you want. You should be asking yourself who you want. It's a jungle out there. So figure out who is willing to "adopt" you and help you advance in the company." And then ask them what you need to know.
1,701
Throughout both my academic and professional career I've encountered situations where in such roles (as most of us would have), where as a happy go lucky graduate who doesn't know it all (but thought I did) would attend meetings and I wouldn't know what certain industry terminology meant or understood certain aspects of the project cycle. I would become really pedantic about asking stupid questions that should be (what I felt) well known. But, I wouldn't ask them in the meeting (especially in a group setting) purposely to not look stupid. To overcome this I would do two things: * I would always go home (after the day is done) and look up the terminology/subject matter and teach myself that way, so if the topic comes up again I'd be armed with the newly obtained knowledge. * I would wait until my superior came up to me and if they mentioned it, I would have a look of confusion on my face and then ask the question. (But this to me, seemed like I wasn't listening in the meeting and/or unprofessional). Which made me contemplate the best time to ask these questions to make myself seem less like I wasn't paying attention but more because I'm willing to learn. --- So, when is it okay to ask "stupid" questions in the workplace?
2017/08/12
[ "https://interpersonal.stackexchange.com/questions/1701", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/2167/" ]
**Note**: as the question specifically aims at meetings, this answer aligns to that scenario. You'll have to weigh up the problems you face, either look attentive and eager to learn by overcoming your fear of looking stupid or keep doing what you're currently doing. But, my advice is if someone knows and you don't, **just ask**. [Asking more questions is not only effective](https://www.inc.com/alison-davis/why-asking-dumb-questions-is-so-darn-smart.html), you learn a hell of a lot from asking even the most simple ones. Don't worry too much, though. You have several times you can ask and whom to ask (depending on your confidence): 1. *If and only if* you aren't disrupting the meeting or the person hosting the meeting, just ask the question there and then. i.e. > > "Sorry, could you elaborate on that?" > > > or > > "Sorry, what does XYZ mean?" > > > this will not only quench your worry about not looking like you're paying attention, it also has multiple benefits: You'll learn (rather than waiting the rest of the day to go home and read up on it) about it there and then, but it can also set the tone for the meeting (someone else might be in the same boat, and you've just set the bar for the types of questions you can ask, thus, an opportunity to learn more from more questions from your peers). 2. After the meeting pull the person who ran the meeting to the side (if you didn't want to disrupt them, or didn't want to engage within a group setting) and ask them to elaborate further on what they said. I'm sure most people wouldn't mind (unless it's something you've learnt in the office before and should already know) 3. If the person is a superior and you want to keep face with them, you can simply pull a trusted colleague to one side after the meeting and ask them about one of the problems you faced or compare notes (they might have something written down you didn't know about), sometimes with other programmers, I would compare notes and [rubberduck](https://en.wikipedia.org/wiki/Rubber_duck_debugging) them and learn that way. But, in a normal office environment, just simply ask them: > > "Hey, you know when they mentioned XYZ in the meeting, do you know any > more about that? I'm looking to learn a little more." > > > These options may make you come across as "stupid", but you'll also come across as someone who is willing to own up when they don't know something and someone who is wanting to learn more about the topic at hand. **Further Reading:** * [Why asking stupid questions is the smartest thing to do.](https://www.stroudinternational.com/latest-insights/stupid-questions) * [Why you should ask stupid questions.](http://www.yuhiro.de/why-you-should-ask-stupid-questions/)
Your question seems to be directed towards meetings specifically, and not so much towards a classroom/group setting ... that being said, I suggest you ask for an agenda in advance for the meetings to which you are attending. Meetings should have an agenda anyway to keep people on task and efficient. This will give you the necessary time to prepare yourself to give as much concise contribution as possible which will increase your value to everybody else in attendance. The purpose of a meeting is to allow collaboration and input from individuals and/or a place to give instruction. If you foresee an unclear subject matter that could affect how you do your work, and you've done what time permits to delve into it beforehand, then there is no 'shame' in asking a 'stupid' question. If you've requested preparatory information and were not given it, and such an unclear topic comes up in conversation during the meeting, go ahead and ask the 'stupid' question. Meetings bring together individuals that are really good at different things as to get the best ideas brought forward. Not everybody in the room will have your jargon or perspective, just as you don't have theirs; it's part of the purpose of having a meeting. With proper preparation on the meeting planners part the little questions won't need to be asked, but it happens, and when it does, don't feel bad for asking. Companies also have their own jargon and way of doing things, many people come from other companies that have different procedures and traditions. If you are newer to a group that has always done their own thing a certain way, it wouldn't hurt to pull somebody aside (a new friend?) after the meeting and explain to them the unfamiliarity of your circumstance and ask them if they can clarify some things, with a follow up of asking if that person can be approached in similar circumstances in the future. This will also provide perspective for this person to recognize situations which may be a bit unclear for you and provide an opportunity for him to help with the clarity during the actual meeting. I must note though that many items on a meeting's agenda won't apply to everybody. If the subject material at hand doesn't apply to yourself, then don't interrupt the flow of conversation to ask to get the question/material clarified that doesn't apply to yourself.
1,701
Throughout both my academic and professional career I've encountered situations where in such roles (as most of us would have), where as a happy go lucky graduate who doesn't know it all (but thought I did) would attend meetings and I wouldn't know what certain industry terminology meant or understood certain aspects of the project cycle. I would become really pedantic about asking stupid questions that should be (what I felt) well known. But, I wouldn't ask them in the meeting (especially in a group setting) purposely to not look stupid. To overcome this I would do two things: * I would always go home (after the day is done) and look up the terminology/subject matter and teach myself that way, so if the topic comes up again I'd be armed with the newly obtained knowledge. * I would wait until my superior came up to me and if they mentioned it, I would have a look of confusion on my face and then ask the question. (But this to me, seemed like I wasn't listening in the meeting and/or unprofessional). Which made me contemplate the best time to ask these questions to make myself seem less like I wasn't paying attention but more because I'm willing to learn. --- So, when is it okay to ask "stupid" questions in the workplace?
2017/08/12
[ "https://interpersonal.stackexchange.com/questions/1701", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/2167/" ]
In your shoes, besides thinking about "when" to ask, I would think about *who* to ask. Your instinct of waiting until you are "offline" to ask is a good one. Unless you absolutely "need to" (you are one of the principal participants), you don't want to ask questions in front of a lot of people at a meeting. So the other issue is who to ask. Usually, that person is your boss. The reason is, the boss has the greatest stake in your development; the better you are, the better s/he is. A good boss will recognize that and try to accommodate your questions. There are some situations when you have a bad boss, or one who favors another co-worker over you, which would (largely) rule out that option. Who else can you ask? Basically, someone you can trust. Possibly a peer or co-worker, possibly a prospective (or actual) mentor. Executives have been known to confide in secretaries or janitors, and find that these people are more knowledgeable than they would have guessed. Having focused on who to ask, the question of "when to ask" is answered by "at a good time for them." The reason I emphasize "who" comes from Michael Lewis' "Liar's Poker." Someone asked a trainer, "how do you become successful at Salomon Brothers?" The trainer thought about it and said something like, "Most of you are going about it wrong. You are asking yourselves what you want. You should be asking yourself who you want. It's a jungle out there. So figure out who is willing to "adopt" you and help you advance in the company." And then ask them what you need to know.
When is it OK to ask "stupid" questions? Whenever you need to! You're absolutely right that it is very common for people to find themselves in these situations. The reason for that is that no one will know everything as soon as they begin (a new job, project, class, etc.). And *that* is why there is no reason at all to consider these questions stupid. That's the first point. Besides, industry terminology and project parameters both seem rather critical, and not-stupid, to me. The thing that would be "stupid," or not a good idea, let's say, is if you let yourself get behind just for not asking, if you undermine your own genius just to save yourself a little embarrassment ... when, in fact, the boss will probably be grateful that you're following along well enough to have intelligent, pertinent questions. But maybe what you're trying to ask is, "how do I know when I'm crossing the line from asking intelligent, pertinent questions ... to being pedantic about it?" The thing about pedants is that they're "excessively concerned with minor details." Will your boss look fondly on you if you keep interrupting his or her presentation for definitions to every word you haven't heard before or with every little question that pops into your head? No...probably not! How I draw the line is by asking (myself) questions like this: Can I follow along? Are the terms I'm NOT familiar with keeping me from understanding the presentation I'm listening to (or whatever), overall? If I answer yes and no, respectively, then I try to save my questions at least until the end, and if I can take thorough enough notes, maybe I can take what I *DID* learn and piece it together myself, after, by looking up the few terms I hadn't heard before on my own. Or if I can tell at the end that I *am* going to need a primer, I try to ask a brief, cogent question that gets right to the heart of whatever I'm not getting. It is also important to do what we can on our own, as much for our own minds as anything else, and when piecing together what I can, after, that's when I usually figure out what it really is that I don't understand. And then the next morning, I just try to get in the office maybe 10 minutes early and plainly tell the supervisor, "Hey, I was looking over what you were talking about and there's a bit here I just don't understand." They're usually really happy to be approached this way. But be prepared, because you may have to say, "Well, you see..." and break down what you do get so he or she will understand what you don't get. And just one more thing. I'm with you that it can be very embarrassing to have to raise your hand right in the middle of something, but sometimes it happens. It's really no big deal – who'll even know in 200 years, right? But when that happens, I've always found that you come across more intelligently when you can say, "If [blah, blah, blah...] and [blah, blah, blah,] too, then [question, question, question]?" instead of just, "what is [that]?" In other words, while it's true that "there are no stupid questions," it's best to make them as smart as you can!
1,701
Throughout both my academic and professional career I've encountered situations where in such roles (as most of us would have), where as a happy go lucky graduate who doesn't know it all (but thought I did) would attend meetings and I wouldn't know what certain industry terminology meant or understood certain aspects of the project cycle. I would become really pedantic about asking stupid questions that should be (what I felt) well known. But, I wouldn't ask them in the meeting (especially in a group setting) purposely to not look stupid. To overcome this I would do two things: * I would always go home (after the day is done) and look up the terminology/subject matter and teach myself that way, so if the topic comes up again I'd be armed with the newly obtained knowledge. * I would wait until my superior came up to me and if they mentioned it, I would have a look of confusion on my face and then ask the question. (But this to me, seemed like I wasn't listening in the meeting and/or unprofessional). Which made me contemplate the best time to ask these questions to make myself seem less like I wasn't paying attention but more because I'm willing to learn. --- So, when is it okay to ask "stupid" questions in the workplace?
2017/08/12
[ "https://interpersonal.stackexchange.com/questions/1701", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/2167/" ]
In your shoes, besides thinking about "when" to ask, I would think about *who* to ask. Your instinct of waiting until you are "offline" to ask is a good one. Unless you absolutely "need to" (you are one of the principal participants), you don't want to ask questions in front of a lot of people at a meeting. So the other issue is who to ask. Usually, that person is your boss. The reason is, the boss has the greatest stake in your development; the better you are, the better s/he is. A good boss will recognize that and try to accommodate your questions. There are some situations when you have a bad boss, or one who favors another co-worker over you, which would (largely) rule out that option. Who else can you ask? Basically, someone you can trust. Possibly a peer or co-worker, possibly a prospective (or actual) mentor. Executives have been known to confide in secretaries or janitors, and find that these people are more knowledgeable than they would have guessed. Having focused on who to ask, the question of "when to ask" is answered by "at a good time for them." The reason I emphasize "who" comes from Michael Lewis' "Liar's Poker." Someone asked a trainer, "how do you become successful at Salomon Brothers?" The trainer thought about it and said something like, "Most of you are going about it wrong. You are asking yourselves what you want. You should be asking yourself who you want. It's a jungle out there. So figure out who is willing to "adopt" you and help you advance in the company." And then ask them what you need to know.
Your question seems to be directed towards meetings specifically, and not so much towards a classroom/group setting ... that being said, I suggest you ask for an agenda in advance for the meetings to which you are attending. Meetings should have an agenda anyway to keep people on task and efficient. This will give you the necessary time to prepare yourself to give as much concise contribution as possible which will increase your value to everybody else in attendance. The purpose of a meeting is to allow collaboration and input from individuals and/or a place to give instruction. If you foresee an unclear subject matter that could affect how you do your work, and you've done what time permits to delve into it beforehand, then there is no 'shame' in asking a 'stupid' question. If you've requested preparatory information and were not given it, and such an unclear topic comes up in conversation during the meeting, go ahead and ask the 'stupid' question. Meetings bring together individuals that are really good at different things as to get the best ideas brought forward. Not everybody in the room will have your jargon or perspective, just as you don't have theirs; it's part of the purpose of having a meeting. With proper preparation on the meeting planners part the little questions won't need to be asked, but it happens, and when it does, don't feel bad for asking. Companies also have their own jargon and way of doing things, many people come from other companies that have different procedures and traditions. If you are newer to a group that has always done their own thing a certain way, it wouldn't hurt to pull somebody aside (a new friend?) after the meeting and explain to them the unfamiliarity of your circumstance and ask them if they can clarify some things, with a follow up of asking if that person can be approached in similar circumstances in the future. This will also provide perspective for this person to recognize situations which may be a bit unclear for you and provide an opportunity for him to help with the clarity during the actual meeting. I must note though that many items on a meeting's agenda won't apply to everybody. If the subject material at hand doesn't apply to yourself, then don't interrupt the flow of conversation to ask to get the question/material clarified that doesn't apply to yourself.
6,825,198
I have a large text string and about 200 keywords that I want to filter out of the text. There are numerous ways todo this, but I'm stuck on which way is the best: 1) Use a for loop with a gsub for each keyword 3) Use a massive regular expression Any other ideas, what would you guys suggest
2011/07/26
[ "https://Stackoverflow.com/questions/6825198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340939/" ]
A massive regex is faster as it's going to walk the text only once. Also, if you don't need the text, only the words, at the end, you can make the text a Set of downcased words and then remove the words that are in the filter array. But this only works if you don't need the "text" to make sense at the end (usually for tags or full text search).
Create a hash with each valid keyword as key. ``` keywords = %w[foo bar baz] keywords_hash = Hash[keywords.map{|k|[k,true]}] ``` Assuming all keywords are 3 letters or more, and consist of alphanumeric characters or a dash, case is irrelevant, and you only want each keyword present in the text returned once: ``` keywords_in_text = text.downcase.scan(/[[:alnum:][-]]{3,}/).select { |word| keywords_hash.has_key? word }.uniq ``` This should be reasonably efficient even when both the text to be searched and the list of valid keywords are very large.
15,843,230
i have an XML that we were able to generate using HAPI libraries and use XSL to change the format of the XML. I am using the following template. The current template looks at the OBX.5 segment for a digital value and then interprets the OBX6 (units of measure). However I am trying to also interpret the OBX6 when they come from one of the clients in a style as duplicates with the caret `^` in between (ex: `%^%` or `mL^mL`). My current template ignores this but I would like to be able to get the value of the segment substring before or after the `^`. ``` <xsl:template match="hl7:OBX.6[matches(./../hl7:OBX.5, '^\d+(\.\d+)?$') and index-of($percentList, .) or index-of($mgdlList, .) or index-of($mlList, .) or index-of($mmList, .) or index-of($mgList, .))]"> <result><xsl:value-of select="./../hl7:OBX.5" /></result> <xsl:when test="index-of($percentList, .)"> <units>%</units> </xsl:when> ... <xsl:when test="index-of($mlList, .)"> <units>ml</units> </xsl:when> <xsl:otherwise> <units><xsl:value-of select="./hl7:CE.1" /></units> </xsl:otherwise> ... </xsl:template> ``` The result should produce ``` <result>38.0</result> <units>%</units> ``` from ``` <OBX.5>38.0</OBX.5> <OBX.6> <CE.1>%^%</CE.1> </OBX.6> ``` Thanks in advance!
2013/04/05
[ "https://Stackoverflow.com/questions/15843230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552782/" ]
**Use**: ``` tokenize(hl7:CE.1, '\^')[1] ``` **Here is a simple XSLT 2.0 - based verification:** ``` <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="OBX.6"> <xsl:sequence select="tokenize(CE.1, '\^')[1]"/> </xsl:template> <xsl:template match="text()"/> </xsl:stylesheet> ``` **when this transformation is applied on the following XML document** (derived from the provided XML fragment and made well-formed): ``` <t> <OBX.5>38.0</OBX.5> <OBX.6> <CE.1>%^%</CE.1> </OBX.6> </t> ``` **the wanted, correct result is produced:** ``` % ```
I also found that HAPI can be tweaked to delimit within the segments by line terminator, `|` for segment terminator and `^` for field terminator. This helped immensely The corresponding xsl looks like: ``` <xsl:template match="hl7:OBX.6[matches(./../hl7:OBX.5, '^\d+(\.\d+)?$') ]"> <xsl:if test="hl7:CE.1[ index-of($percentList, .) or index-of($mgdlList, .) or index-of($mlList, .) or index-of($mmList, .) or index-of($mgList, .))]"> <result><xsl:value-of select="./../hl7:OBX.5" /></result> <xsl:choose> <xsl:when test="index-of($percentList, hl7:CE.1)"> <units>%</units> </xsl:when> ... <xsl:when test="index-of($mlList, hl7:CE.1)"> <units>mL</units> </xsl:when> ... <xsl:otherwise> <units><xsl:value-of select="hl7:CE.1" /></units> </xsl:otherwise> </xsl:choose> </xsl:if> </xsl:template> ```
2,653,047
So I'm trying to register for the MPMoviePlayerDidExitFullscreenNotification notification in my universal app (iPhone and iPad). Problem is, OS 3.1.3 doesn't support this notification, and just crashes. I've tried version checking, like so: ``` if ([MPMoviePlayerController instancesRespondToSelector:@selector(setShouldAutoplay:)]) {//Check for shouldSetAutoplay, this ensures that we are running at least 3.2 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:(NSString*)class2 object:[self player]]; ``` Doesn't work, still crashes. How do I do this?
2010/04/16
[ "https://Stackoverflow.com/questions/2653047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310175/" ]
Since MPMoviePlayerDidExitFullscreenNotification is a symbol, it must be known at (dynamic) link time for any versions. Run time check doesn't help. To solve this, you need to delay loading of this to run time. You could use `dlsym`: ``` NSString* x_MPMoviePlayerDidExitFullscreenNotification = dlsym(RTLD_DEFAULT, "MPMoviePlayerDidExitFullscreenNotification"); if (x_MPMoviePlayerDidExitFullscreenNotification != nil) { [[NSNotificationCenter defaultCenter] addObserver:self ...]; } ``` Alternatively, you may make MPMoviePlayerDidExitFullscreenNotification [a weak symbol](https://stackoverflow.com/questions/274753/how-to-make-weak-linking-work-with-gcc) so when `dyld` doesn't find that symbol, instead of crashing it will just set it to NULL. Finally, since MPMoviePlayerDidExitFullscreenNotification is just a constant string, you could simply use ``` … name:@"MPMoviePlayerDidExitFullscreenNotification" … ``` But the content of that string is implementation detail. There's no guarantee (although rare) that Apple won't change it to something else in the later versions.
To answer your actual question: You should be able to register for any notification without crashing. As Kenny says, it's a symbol, so the correct registration for 3.2 is; ``` [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:MPMoviePlayerDidExitFullscreenNotification object:[self player]]; ``` For code that works in 3.13, you can assume that the symbol is just a convenience for the compiler, and use a string instead: ``` [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:@"MPMoviePlayerDidExitFullscreenNotification" object:[self player]]; ``` You test using `shouldAutoplay` is fine, although I'd prefer to all it directly on the instance I would be using - ie `[self player]`. It's probably that your real problem is using `class2` cast to `NSString` as the notification name.
2,653,047
So I'm trying to register for the MPMoviePlayerDidExitFullscreenNotification notification in my universal app (iPhone and iPad). Problem is, OS 3.1.3 doesn't support this notification, and just crashes. I've tried version checking, like so: ``` if ([MPMoviePlayerController instancesRespondToSelector:@selector(setShouldAutoplay:)]) {//Check for shouldSetAutoplay, this ensures that we are running at least 3.2 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:(NSString*)class2 object:[self player]]; ``` Doesn't work, still crashes. How do I do this?
2010/04/16
[ "https://Stackoverflow.com/questions/2653047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310175/" ]
Since MPMoviePlayerDidExitFullscreenNotification is a symbol, it must be known at (dynamic) link time for any versions. Run time check doesn't help. To solve this, you need to delay loading of this to run time. You could use `dlsym`: ``` NSString* x_MPMoviePlayerDidExitFullscreenNotification = dlsym(RTLD_DEFAULT, "MPMoviePlayerDidExitFullscreenNotification"); if (x_MPMoviePlayerDidExitFullscreenNotification != nil) { [[NSNotificationCenter defaultCenter] addObserver:self ...]; } ``` Alternatively, you may make MPMoviePlayerDidExitFullscreenNotification [a weak symbol](https://stackoverflow.com/questions/274753/how-to-make-weak-linking-work-with-gcc) so when `dyld` doesn't find that symbol, instead of crashing it will just set it to NULL. Finally, since MPMoviePlayerDidExitFullscreenNotification is just a constant string, you could simply use ``` … name:@"MPMoviePlayerDidExitFullscreenNotification" … ``` But the content of that string is implementation detail. There's no guarantee (although rare) that Apple won't change it to something else in the later versions.
This also works: ``` if (&MPMoviePlayerDidExitFullscreenNotification) { } ``` Note you have to check the address of the symbol otherwise you will get a crash.
2,653,047
So I'm trying to register for the MPMoviePlayerDidExitFullscreenNotification notification in my universal app (iPhone and iPad). Problem is, OS 3.1.3 doesn't support this notification, and just crashes. I've tried version checking, like so: ``` if ([MPMoviePlayerController instancesRespondToSelector:@selector(setShouldAutoplay:)]) {//Check for shouldSetAutoplay, this ensures that we are running at least 3.2 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:(NSString*)class2 object:[self player]]; ``` Doesn't work, still crashes. How do I do this?
2010/04/16
[ "https://Stackoverflow.com/questions/2653047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310175/" ]
Since MPMoviePlayerDidExitFullscreenNotification is a symbol, it must be known at (dynamic) link time for any versions. Run time check doesn't help. To solve this, you need to delay loading of this to run time. You could use `dlsym`: ``` NSString* x_MPMoviePlayerDidExitFullscreenNotification = dlsym(RTLD_DEFAULT, "MPMoviePlayerDidExitFullscreenNotification"); if (x_MPMoviePlayerDidExitFullscreenNotification != nil) { [[NSNotificationCenter defaultCenter] addObserver:self ...]; } ``` Alternatively, you may make MPMoviePlayerDidExitFullscreenNotification [a weak symbol](https://stackoverflow.com/questions/274753/how-to-make-weak-linking-work-with-gcc) so when `dyld` doesn't find that symbol, instead of crashing it will just set it to NULL. Finally, since MPMoviePlayerDidExitFullscreenNotification is just a constant string, you could simply use ``` … name:@"MPMoviePlayerDidExitFullscreenNotification" … ``` But the content of that string is implementation detail. There's no guarantee (although rare) that Apple won't change it to something else in the later versions.
I needed exactly this but I did prefer using `dlsym` as KennyTM suggested, however, I needed to do a small change for it to work so I guess that was a bug (please correct me if I'm wrong). This is the code snippet I'm using which works great: ``` NSString* x_MPMoviePlayerDidExitFullscreenNotification = *(NSString**)dlsym(RTLD_DEFAULT, "MPMoviePlayerDidExitFullscreenNotification"); if (x_MPMoviePlayerDidExitFullscreenNotification != nil) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didExitFullscreen:) name:x_MPMoviePlayerDidExitFullscreenNotification object: self.videoPlayer]; } ``` The change from KennyTM's snippet was the `*(NSString**)` cast after dlsym as it seems dlsym will return a pointer to the symbol.
2,653,047
So I'm trying to register for the MPMoviePlayerDidExitFullscreenNotification notification in my universal app (iPhone and iPad). Problem is, OS 3.1.3 doesn't support this notification, and just crashes. I've tried version checking, like so: ``` if ([MPMoviePlayerController instancesRespondToSelector:@selector(setShouldAutoplay:)]) {//Check for shouldSetAutoplay, this ensures that we are running at least 3.2 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:(NSString*)class2 object:[self player]]; ``` Doesn't work, still crashes. How do I do this?
2010/04/16
[ "https://Stackoverflow.com/questions/2653047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310175/" ]
This also works: ``` if (&MPMoviePlayerDidExitFullscreenNotification) { } ``` Note you have to check the address of the symbol otherwise you will get a crash.
To answer your actual question: You should be able to register for any notification without crashing. As Kenny says, it's a symbol, so the correct registration for 3.2 is; ``` [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:MPMoviePlayerDidExitFullscreenNotification object:[self player]]; ``` For code that works in 3.13, you can assume that the symbol is just a convenience for the compiler, and use a string instead: ``` [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:@"MPMoviePlayerDidExitFullscreenNotification" object:[self player]]; ``` You test using `shouldAutoplay` is fine, although I'd prefer to all it directly on the instance I would be using - ie `[self player]`. It's probably that your real problem is using `class2` cast to `NSString` as the notification name.
2,653,047
So I'm trying to register for the MPMoviePlayerDidExitFullscreenNotification notification in my universal app (iPhone and iPad). Problem is, OS 3.1.3 doesn't support this notification, and just crashes. I've tried version checking, like so: ``` if ([MPMoviePlayerController instancesRespondToSelector:@selector(setShouldAutoplay:)]) {//Check for shouldSetAutoplay, this ensures that we are running at least 3.2 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidFinish:) name:(NSString*)class2 object:[self player]]; ``` Doesn't work, still crashes. How do I do this?
2010/04/16
[ "https://Stackoverflow.com/questions/2653047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310175/" ]
This also works: ``` if (&MPMoviePlayerDidExitFullscreenNotification) { } ``` Note you have to check the address of the symbol otherwise you will get a crash.
I needed exactly this but I did prefer using `dlsym` as KennyTM suggested, however, I needed to do a small change for it to work so I guess that was a bug (please correct me if I'm wrong). This is the code snippet I'm using which works great: ``` NSString* x_MPMoviePlayerDidExitFullscreenNotification = *(NSString**)dlsym(RTLD_DEFAULT, "MPMoviePlayerDidExitFullscreenNotification"); if (x_MPMoviePlayerDidExitFullscreenNotification != nil) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didExitFullscreen:) name:x_MPMoviePlayerDidExitFullscreenNotification object: self.videoPlayer]; } ``` The change from KennyTM's snippet was the `*(NSString**)` cast after dlsym as it seems dlsym will return a pointer to the symbol.
21,951,969
In Eclipse, there is an option Export -> JAR File. Then we select desirable classes which want to export to output jar. How can we do that in IntelliJ?
2014/02/22
[ "https://Stackoverflow.com/questions/21951969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2361910/" ]
I don't know if you need this answer anymore, but I had the same issue today and I figured out how to solve it. Please, follow these steps: 1. File -> Project Structure (Ctrl + Alt + Shift + S); 2. Go to the "Artifacts" Menu -> click on the "+" button -> JAR -> From modules with dependencies... 3. Select the module you want to generate the Jar file; 4. Don't select any main class; 5. On the JAR files from libraries menu, select "extract to the target JAR" option -> Click Ok; 6. Name your jar file -> select the output directory -> Click "Apply" and "Ok"; 7. After these steps, go to: Build -> Build Artifacts... 8. A flying menu will appear with the artifact that you have previously created; 9. Click Build and it's done. Hope that that helps you and everyone that have this issue. I wasted all day trying generate the jar file on Eclipse with FatJar and I couldn't generate it.
You can use Ant to do that. 1. Create your Ant project. 2. Drag and drop ant file to Ant Build view. 3. Execute the task to generate the .jar file. [![ IntelliJ Ant Build view](https://i.stack.imgur.com/MyNEw.png)](https://i.stack.imgur.com/MyNEw.png) ``` <?xml version="1.0" encoding="utf-8"?> <project name="CustomJar" default="dist" basedir="."> <description> Package clases selected package to jar. </description> <!-- set global properties for this build. **** The paths are relative to the ant file location *** --> <property name="src" location="../src/main/java/com/dto/myclasespackage"/> <property name="build" location="../build"/> <property name="dist" location="../dist/custom_jar"/> <property name="version" value="1.0"/> <target name="init"> <!-- Create the time stamp --> <tstamp/> <!-- Create the build directory defined above --> <mkdir dir="${build}"/> </target> <target name="compile" depends="init" description="compile the source"> <!-- Compile java code from ${src} into ${build} --> <javac srcdir="${src}" destdir="${build}"/> </target> <target name="dist" depends="compile" description="generate the distribution"> <buildnumber/> <!-- Create the distribution directory --> <mkdir dir="${dist}/lib"/> <!-- Put everything in ${build} into the MyApplication-${version}.${build.number}.jar --> <jar destfile="${dist}/lib/desglose-reports-beans-${version}.${build.number}.jar" basedir="${build}"/> </target> <target name="clean" description="clean up"> <!-- Delete the ${build} and ${dist} directories --> <delete dir="${build}"/> <delete dir="${dist}"/> </target> </project> ```
36,502,572
``` function convertToRoman(num) { //seperate the number in to singular digits which are strings and pass to array. var array = ("" + num).split(""), arrayLength = array.length, romStr = ""; //Convert the strings in the array to numbers array = array.map(Number); //Itterate over every number in the array for (var i = 0; i < array.length; i++) { //Calculate what power of ten the digit is by minusing it's index from the array length and passing it to variable "tenToPowerOf" var tenToPowerOf = arrayLength - array.indexOf(array[i]) - 1, low = "", mid = "", upp = ""; //Set the low, mid and high variables based on their tenToPowerOf value switch (tenToPowerOf) { case 0: low = "I"; mid = "V"; upp = "X"; break; case 1: low = "X"; mid = "L"; upp = "C"; break; case 2: low = "C"; mid = "D"; upp = "M"; break; case 3: low = "M"; mid = "¯V"; upp = "¯X"; break; } //Check for digit value and add it's Roman Numeral value (based on it's power from the above switch statement) to romStr //The problem is, switch "remembers" the value of low, mid and high from the last time it itterated over the number. Thus 99 becomes "XCXC" and not "XCIX". switch (array[i]) { case 1: romStr += low; break; case 2: romStr += low.repeat(2); break; case 3: romStr += low.repeat(3); break; case 4: romStr += low + mid; break; case 5: romStr += mid; break; case 6: romStr += mid + low; break; case 7: romStr += mid + low.repeat(2); break; case 8: romStr += mid + low.repeat(3); break; case 9: romStr += low + upp; break; case 10: romStr += upp; break; default: break; } } //return array; return romStr; } convertToRoman(99); ``` * Yes, I have spent my share share of time looking for a relevant answer before asking (1.5+ hours). * The function converts numbers in to Roman Numerals. + It takes a number argument passed to it + Splits the number in to digits + Converts then in to an array + Then based on the number's power of ten (or position relevant to the length of the number) sets the low mid and high values + These values are then applied in the order dictated by Roman Numerals and pushed to a string + Finally, the string is returned. * It works with numbers that have digits occurring no more than once. The reason for this is because when the switch case is matched more than once in the for loop, it applies the low, mid and high values from the previous iteration. * The question is in the title but I would also like to ask for a solution to the problem that I am trying to solve please. * I will gladly provide more information and will answer every question
2016/04/08
[ "https://Stackoverflow.com/questions/36502572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5950725/" ]
It seems to me your problem is in the use of `array.indexOf(array[i])` to calculate the power. Guess what, if you have the same value in your array twice, **the first found index is returned**, not the index of your *current* element. Guess what the index of your current element actually is? → `i` No need for `indexOf`. Nothing to do with `switch`.
Because Javascript uses function closures and your loop doesn't reset the values by default, in other words the variables inside the for still exists outside of it.
36,502,572
``` function convertToRoman(num) { //seperate the number in to singular digits which are strings and pass to array. var array = ("" + num).split(""), arrayLength = array.length, romStr = ""; //Convert the strings in the array to numbers array = array.map(Number); //Itterate over every number in the array for (var i = 0; i < array.length; i++) { //Calculate what power of ten the digit is by minusing it's index from the array length and passing it to variable "tenToPowerOf" var tenToPowerOf = arrayLength - array.indexOf(array[i]) - 1, low = "", mid = "", upp = ""; //Set the low, mid and high variables based on their tenToPowerOf value switch (tenToPowerOf) { case 0: low = "I"; mid = "V"; upp = "X"; break; case 1: low = "X"; mid = "L"; upp = "C"; break; case 2: low = "C"; mid = "D"; upp = "M"; break; case 3: low = "M"; mid = "¯V"; upp = "¯X"; break; } //Check for digit value and add it's Roman Numeral value (based on it's power from the above switch statement) to romStr //The problem is, switch "remembers" the value of low, mid and high from the last time it itterated over the number. Thus 99 becomes "XCXC" and not "XCIX". switch (array[i]) { case 1: romStr += low; break; case 2: romStr += low.repeat(2); break; case 3: romStr += low.repeat(3); break; case 4: romStr += low + mid; break; case 5: romStr += mid; break; case 6: romStr += mid + low; break; case 7: romStr += mid + low.repeat(2); break; case 8: romStr += mid + low.repeat(3); break; case 9: romStr += low + upp; break; case 10: romStr += upp; break; default: break; } } //return array; return romStr; } convertToRoman(99); ``` * Yes, I have spent my share share of time looking for a relevant answer before asking (1.5+ hours). * The function converts numbers in to Roman Numerals. + It takes a number argument passed to it + Splits the number in to digits + Converts then in to an array + Then based on the number's power of ten (or position relevant to the length of the number) sets the low mid and high values + These values are then applied in the order dictated by Roman Numerals and pushed to a string + Finally, the string is returned. * It works with numbers that have digits occurring no more than once. The reason for this is because when the switch case is matched more than once in the for loop, it applies the low, mid and high values from the previous iteration. * The question is in the title but I would also like to ask for a solution to the problem that I am trying to solve please. * I will gladly provide more information and will answer every question
2016/04/08
[ "https://Stackoverflow.com/questions/36502572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5950725/" ]
It seems to me your problem is in the use of `array.indexOf(array[i])` to calculate the power. Guess what, if you have the same value in your array twice, **the first found index is returned**, not the index of your *current* element. Guess what the index of your current element actually is? → `i` No need for `indexOf`. Nothing to do with `switch`.
Variables declared as `var` inside a `for` loop are not reset on each iteration, it has nothing to do with the `switch`. Try pasting this into your console - ``` for (var i = 1; i <= 10; i++) { console.log('before', i, j); var j = i * 10; console.log('after', i, j); } ``` Note that on the first loop, the "before" `j` is `undefined`, and then after that is always one step behind. If you run the same code again, `j` will start at `100` To fix this, I would set `j` to `null` (or some other sensible value) at the start of the loop - ``` for (var i = 1; i <= 10; i++) { var j = null; console.log('before', i, j); j = i * 10; console.log('after', i, j); } ```
28,828,145
I got a table named "Stock" as shown below. ``` +-----------+--------------+---------------+---------+ | client_id | date | credit | debit| +-----------+--------------+---------------+---------+ | 1 | 01-01-2015 | 50 | 0 | | 2 | 01-01-2015 | 250 | 0 | | 2 | 01-01-2015 | 500 | 0 | | 2 | 02-01-2015 | 0 | 500 | | 1 | 02-01-2015 | 0 | 40 | | 1 | 02-01-2015 | 0 | 80 | | 3 | 05-01-2015 | 3000 | 0 | | 2 | 06-01-2015 | 0 | 350 | | 4 | 06-01-2015 | 0 | 1000 | | 4 | 06-01-2015 | 0 | 2000 | | 4 | 07-01-2015 | 500 | 0 | | 5 | 07-01-2015 | 500 | 0 | | 5 | 08-01-2015 | 500 | 0 | | 1 | 09-01-2015 | 0 | 100 | +-----------+--------------+---------------+---------+ ``` The result I am expecting is something like: ``` +---------+-----------+-------------+--------+---------+----------+ |client_id| date |Open_Balance | credit | debit | balance | +---------+-----------+-------------+--------+---------+----------+ | 1 |01-01-2015 | 0 | 50 | 0 | 50 | | 1 |02-01-2015 | 50 | 0 | 40 | 10 | | 1 |02-01-2015 | 10 | 0 | 80 | -70 | | 1 |09-01-2015 | -70 | 0 | 100 | -170 | | 2 |01-01-2015 | 0 | 250 | 0 | 250 | | 2 |01-01-2015 | 250 | 500 | 0 | 750 | | 2 |02-01-2015 | 750 | 0 | 500 | 250 | | 2 |06-01-2015 | 250 | 0 | 350 | -100 | | 3 |05-01-2015 | 0 | 3000 | 0 | 3000 | | 4 |06-01-2015 | 0 | 0 | 1000 | -1000 | | 4 |06-01-2015 | -1000 | 0 | 2000 | -3000 | | 4 |07-01-2015 | -3000 | 500 | 0 | -2500 | | 5 |07-01-2015 | 0 | 500 | 0 | 500 | | 5 |08-01-2015 | 500 | 500 | 0 | 1000 | +---------+-----------+-------------+--------+---------+---- -----+ ``` I need balances and 'Open balances' to be calculated by client\_id and date order as shown above. Please help.
2015/03/03
[ "https://Stackoverflow.com/questions/28828145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4608311/" ]
Here how you can do it.. ``` select s.client_id, s.date, s.op_balance as Open_Balance, s.credit, s.debit, s.balance from ( select t.client_id, t.date, t.credit, t.debit, @tot_credit := if(@prev_client = t.client_id, @tot_credit + t.credit,t.credit) as tot_cred, @tot_debit := if(@prev_client = t.client_id,@tot_debit + t.debit,t.debit) as tot_deb, @cur_bal := if(@prev_client = t.client_id, @tot_credit - @tot_debit,t.credit-t.debit) as balance, (@cur_bal + t.debit) - t.credit as op_balance, @prev_client := t.client_id from( select * from stock order by client_id,date )t,(select @prev_client:=0,@cur_bal:=0,@tot_credit:=0,@tot_debit:= 0,@open_balance:=0)r )s ``` **[DEMO](http://www.sqlfiddle.com/#!2/2f7c1/18)** Also I have noticed that the same data you have date column which I have used to do the sort per client id, but its good to have datetime for date so that the sorting does not get confused with same date or may be a primary key in the table.
First of all set two variables for open balance and balance; ``` mysql> set @balance = 0; mysql> set @openBalance = 0; ``` then set id variable ``` mysql> set @id := (select client_id from Stock order by client_id asc limit 1); ``` and now run this query ``` select client_id,date,IF(client_id=@id,@balance:=@balance,@balance:=0), @openBalance:=@balance as OpenBalance,credit,debit,@balance:=(credit+@openBalance)-debit as bal,@id:=client_id from Stock order by client_id,date; ``` Yeah since some data have same date and id, query may work different way so pls make some changes in your table definition such as rather than date you can make it date time and then sort accordingly.
3,241,286
The problem is to solve this: $$a^2 + b^2 =c^4 \text{ }a,b,c\in \Bbb{N}\text{ }a,b,c<100$$ My idea: To see this problem I at first must see idea with Pythagorean triplets, and to problem is to find hypotheses of length square number. Is there any easier approach to this problem?
2019/05/27
[ "https://math.stackexchange.com/questions/3241286", "https://math.stackexchange.com", "https://math.stackexchange.com/users/259483/" ]
I think, the way with using Pythagorean triplets is the best. Let $\gcd(a,b,c)=1$. Thus, there are natural $m$ and $n$ with different parity such that $m>n$ and $\gcd(m,n)=1$ and $a=2mn,$ $b=m^2-n^2$. Thus, $c^2=m^2+m^2$ and by the same way there are naturals $p$ and $q$ with a different parity, such that $p>q$, $\gcd(p,q)=1$ and $m=2pq$ and $n=p^2-q^2$. Thus, $a=4pq(p^2-q^2)$, $b=4p^2q^2-(p^2-q^2)^2=6p^2q^2-p^4-q^4$ and $c=p^2+q^2$. Can you end it now? For example, for $p=2$ and $q=1$ we obtain: $(a,b,c)=(24,7,5)$.
All Solutions are $$(a=7\land b=24\land c=5)\lor (a=15\land b=20\land c=5)\lor (a=20\land b=15\land c=5)\lor (a=24\land b=7\land c=5)\lor (a=28\land b=96\land c=10)\lor (a=60\land b=80\land c=10)\lor (a=80\land b=60\land c=10)\lor (a=96\land b=28\land c=10)$$
3,241,286
The problem is to solve this: $$a^2 + b^2 =c^4 \text{ }a,b,c\in \Bbb{N}\text{ }a,b,c<100$$ My idea: To see this problem I at first must see idea with Pythagorean triplets, and to problem is to find hypotheses of length square number. Is there any easier approach to this problem?
2019/05/27
[ "https://math.stackexchange.com/questions/3241286", "https://math.stackexchange.com", "https://math.stackexchange.com/users/259483/" ]
I think, the way with using Pythagorean triplets is the best. Let $\gcd(a,b,c)=1$. Thus, there are natural $m$ and $n$ with different parity such that $m>n$ and $\gcd(m,n)=1$ and $a=2mn,$ $b=m^2-n^2$. Thus, $c^2=m^2+m^2$ and by the same way there are naturals $p$ and $q$ with a different parity, such that $p>q$, $\gcd(p,q)=1$ and $m=2pq$ and $n=p^2-q^2$. Thus, $a=4pq(p^2-q^2)$, $b=4p^2q^2-(p^2-q^2)^2=6p^2q^2-p^4-q^4$ and $c=p^2+q^2$. Can you end it now? For example, for $p=2$ and $q=1$ we obtain: $(a,b,c)=(24,7,5)$.
We need to find Pythagorean triples where the hypotenuse is already a square. We can certainly use $5\*(3,4,5)=(15,20,25)$ or $20\*(3,4,5)=(60,80,100)$ but we can also use the following formula to find one or more triples for a given hypotenuse, if they exist. For any $C,m$ that yields an integer, we have the $m,n$ we need for a triple with that hypotenuse. For $C= m^2+n^2,\space n=\sqrt{C-m^2}$ where $\biggl\lceil\sqrt{\frac{C}{2}}\space\space\biggr\rceil \le m\le\bigl\lfloor\sqrt{C}\bigr\rfloor$. Let $$n=\sqrt{25-m^2}\text{ where }\biggl\lceil\sqrt{\frac{25}{2}}\space\space\biggr\rceil=4 \le m\le\bigl\lfloor\sqrt{25}\bigr\rfloor=5$$ We find $n(25,4)=3\rightarrow f(4,3)=(7,24,25)$ but $n(25,5)=0$; there is no triple for $m=5$ We could also find $(3,4,5)$ by using $C=5$, a factor of $25$ $$n=\sqrt{5-m^2}\text{ where }\biggl\lceil\sqrt{\frac{5}{2}}\space\space\biggr\rceil=2 \le m\le\bigl\lfloor\sqrt{5}\bigr\rfloor=2$$ We find $n(5,2)=1\rightarrow f(2,1)=(3,4,5)$ We find no integer values of $n$ for $C=49$ or $C=81$ or their factors $$n=\sqrt{100-m^2}\text{ where }\biggl\lceil\sqrt{\frac{100}{2}}\space\space\biggr\rceil=8 \le m\le\bigl\lfloor\sqrt{100}\bigr\rfloor=10$$ We find $n(100,8)=6\rightarrow f(8,6)=(28,96,100)$ but $n(100,10)=0$; there is no triple for $m=10$
3,241,286
The problem is to solve this: $$a^2 + b^2 =c^4 \text{ }a,b,c\in \Bbb{N}\text{ }a,b,c<100$$ My idea: To see this problem I at first must see idea with Pythagorean triplets, and to problem is to find hypotheses of length square number. Is there any easier approach to this problem?
2019/05/27
[ "https://math.stackexchange.com/questions/3241286", "https://math.stackexchange.com", "https://math.stackexchange.com/users/259483/" ]
I think, the way with using Pythagorean triplets is the best. Let $\gcd(a,b,c)=1$. Thus, there are natural $m$ and $n$ with different parity such that $m>n$ and $\gcd(m,n)=1$ and $a=2mn,$ $b=m^2-n^2$. Thus, $c^2=m^2+m^2$ and by the same way there are naturals $p$ and $q$ with a different parity, such that $p>q$, $\gcd(p,q)=1$ and $m=2pq$ and $n=p^2-q^2$. Thus, $a=4pq(p^2-q^2)$, $b=4p^2q^2-(p^2-q^2)^2=6p^2q^2-p^4-q^4$ and $c=p^2+q^2$. Can you end it now? For example, for $p=2$ and $q=1$ we obtain: $(a,b,c)=(24,7,5)$.
> > $a^2 + b^2 =c^4 \quad a,b,c\in \Bbb{N}\quad a,b,c<100$ > > > and > > Can you please comment how you get this solutions? > > > The involved numbers are so small we can compute everything by hand and without brute-force search or such: Due to $a, b < 100$ we have $c^4=a^2+b^2 < 2\cdot 100^2$ and thus $$c < \sqrt[4]{2}\cdot10<\sqrt{1.44}\cdot10=1.2\cdot10=12$$ where I used $\sqrt 2 < 1.44$. Hence $c$ is 11 at most. Finding Pythagorean triples is equivalent to solving the norm equation in $\Bbb Z[i]$ with $i=\sqrt{-1}$, the [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer). As $1\leqslant c\leqslant 11$ we solve the norm equation for primes not 3 mod 4 and multiply the resulting prime ideals together to get the solutions. The only integer primes that decay over $\Bbb Z[i]$ are 2 and 5: $\def\p{\mathfrak p} \def\b{\bar{\p}}$ $2 = \p\_2 \b\_2$ $5 = \p\_5 \b\_5$ Real solutions like for for 0 and 1 are of no interest because you only want $a, b\in\Bbb N$. We then take the 4-th powers of these ideals (or their conjugate) to find the solutions for $c$. The only products that do not exceed 11 are: 2, 5 and 2·5=10 where 2 is of no interest because $\p\_2^{2n}=2^n$ is real and thus only gives unwanted solutions like $4^2 + 0^2 = 2^4$ (this is because $\p\_2=\b\_2$ modulo units where $\bar{\,\cdot\,}$ denotes complex conjugation). We arrive at the following 4 solutions (modulo units and conjugation): \begin{align} s\_1 &= \p\_5^4 \\ s\_2 &= \p\_5^3\b\_5=5\p\_5^2 \\ s\_3 &= \p\_2^4\p\_5^4=2^2\p\_5^4 = 4s\_1\\ s\_4 &= \p\_2^4\p\_5^3\b\_5=2^25\p\_5^2 = 4s\_2 \end{align} With $\p\_5 = 2+i$ we have $\p\_5^2=3+4i$ and $\p\_5^4=-7+24i$, thus: \begin{array}{rclll} s\_1 &=& -7+24i &\Rightarrow& (7,24,5)\\ s\_2 &=& 5(3+4i) &\Rightarrow&(15,20,5)\\ s\_3 &=& 4(-7+24i)&\Rightarrow&(28,96,10)\\ s\_4 &=& 20(3+4i)&\Rightarrow&(60,80,10) \end{array} These solutions are only up to ordering $a$ and $b$, i.e. $(24,7,5)$ etc. are also solutions, of course.
41,411,432
Simple Code: ``` <div id="right"> <h2>Zamiana jednostek temperatury</h2> temperatura w <sup>o</sup>Celsjusza<br> <input type="text" id="cyfry" name="cyfry"><br> <button onclick="fahrenheit()">Fahrenheit</button> <button onclick="kelwin()">Kelwin</button> <span id="wynik"></span> </div> ``` And Script: ``` function fahrenheit(){ var x=Document.getElementById("cyfry"); parseInt(x); x = (x*1,8)+32; document.getElementById("wynik").innerHTML=x; } function kelwin(){ var x=Document.getElementById("cyfry"); parseInt(x); x = x + 273,15; document.getElementById("wynik").innerHTML=x; } ``` As you can see all I want to do is convert units in Celsius to Fahrenheit or Calvins, but I get an error: ``` Uncaught TypeError: Document.getElementById is not a function at fahrenheit (script.js:2) at HTMLButtonElement.onclick (index.html?cyfry=:32) ``` Thanks a lot in advance and Happy New Year! After some changes I have problem that answer is always 40 in Fahrenheit and 15 on Calvin: ``` function fahrenheit(){ var x=document.getElementById("cyfry").value; parseFloat(x); var y = ((x*1,8)+32); document.getElementById("wynik").innerHTML=y; } function kelwin(){ var a=document.getElementById("cyfry").value; parseFloat(a); var b = (a + 273,15); document.getElementById("wynik").innerHTML=b; ``` }
2016/12/31
[ "https://Stackoverflow.com/questions/41411432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7361359/" ]
You should use document.getElementById **not** Document.getElementById . Heres a working solution. Hope it helps! ```js function fahrenheit(){ var x=document.getElementById("cyfry"); parseInt(x); x = (x*1,8)+32; document.getElementById("wynik").innerHTML=x; } function kelwin(){ var x=document.getElementById("cyfry"); parseInt(x); x = x + 273,15; document.getElementById("wynik").innerHTML=x; } ``` ```html <div id="right"> <h2>Zamiana jednostek temperatury</h2> temperatura w <sup>o</sup>Celsjusza<br> <input type="text" id="cyfry" name="cyfry"><br> <button onclick="fahrenheit()">Fahrenheit</button> <button onclick="kelwin()">Kelwin</button> <span id="wynik"></span> </div> ```
JavaScript is a case sensitive language. You have to use the uncapitalized `document`, not `Document`
15,760,336
These two views are inside of `RelativeLayout`. The IDE throws an error there is no `@id/et_pass`, but if I set `@+id/et_pass` it is OK. Why is that? ``` <ImageView android:id="@+id/devider_zero" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/et_pass" <!-- Error is here --> android:src="@drawable/registration_line" /> <EditText android:id="@+id/et_pass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/devider_first" android:background="@android:color/transparent" android:layout_gravity="left" android:ellipsize="start" android:ems="8" android:hint="@string/password" android:inputType="textPassword" android:layout_marginTop="@dimen/register_layout_edittext_margin_top" android:maxLines="1" /> ```
2013/04/02
[ "https://Stackoverflow.com/questions/15760336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/397991/" ]
You did not allocate any memory for the pointer to point at. You can do so like this: ``` int *a = malloc(sizeof(*a)); ``` or like this: ``` int value; int *a = &value; ``` If you allocate with `malloc` then you'll want to call `free` on the pointer when you are finished using it. Accessing an uninitialized pointer leads to undefined behaviour. In your program it led to segmentation fault, one very common outcome of uninitialized pointer access.
In `int* a;` `a`'s default value is garbage, and points to an invalid memory, you can't assign to that. And assignment like `*a=20;` this is causes an undefined behavior at run time. (syntax wise code is correct so compiled) you may some time get a seg-fault too. either do: ``` int i; int *a = &i; // a points to a valid memory that is i *a = 20; ``` or with dynamic memory allocation using calloc() or malloc() functions. ``` int *a = malloc(sizeof(int)); *a = 20; ``` Remember dynamic allocated memories we have to deallocate (free) explicitly when we have done with that.
15,760,336
These two views are inside of `RelativeLayout`. The IDE throws an error there is no `@id/et_pass`, but if I set `@+id/et_pass` it is OK. Why is that? ``` <ImageView android:id="@+id/devider_zero" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/et_pass" <!-- Error is here --> android:src="@drawable/registration_line" /> <EditText android:id="@+id/et_pass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/devider_first" android:background="@android:color/transparent" android:layout_gravity="left" android:ellipsize="start" android:ems="8" android:hint="@string/password" android:inputType="textPassword" android:layout_marginTop="@dimen/register_layout_edittext_margin_top" android:maxLines="1" /> ```
2013/04/02
[ "https://Stackoverflow.com/questions/15760336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/397991/" ]
You did not allocate any memory for the pointer to point at. You can do so like this: ``` int *a = malloc(sizeof(*a)); ``` or like this: ``` int value; int *a = &value; ``` If you allocate with `malloc` then you'll want to call `free` on the pointer when you are finished using it. Accessing an uninitialized pointer leads to undefined behaviour. In your program it led to segmentation fault, one very common outcome of uninitialized pointer access.
You have `wild pointer`, either assign memory to it using `malloc` ``` int* a = malloc(sizeof(int)); ``` or use a stack variable ``` int b = 0; int *a = &b; *a=20; ```
15,760,336
These two views are inside of `RelativeLayout`. The IDE throws an error there is no `@id/et_pass`, but if I set `@+id/et_pass` it is OK. Why is that? ``` <ImageView android:id="@+id/devider_zero" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/et_pass" <!-- Error is here --> android:src="@drawable/registration_line" /> <EditText android:id="@+id/et_pass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/devider_first" android:background="@android:color/transparent" android:layout_gravity="left" android:ellipsize="start" android:ems="8" android:hint="@string/password" android:inputType="textPassword" android:layout_marginTop="@dimen/register_layout_edittext_margin_top" android:maxLines="1" /> ```
2013/04/02
[ "https://Stackoverflow.com/questions/15760336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/397991/" ]
You did not allocate any memory for the pointer to point at. You can do so like this: ``` int *a = malloc(sizeof(*a)); ``` or like this: ``` int value; int *a = &value; ``` If you allocate with `malloc` then you'll want to call `free` on the pointer when you are finished using it. Accessing an uninitialized pointer leads to undefined behaviour. In your program it led to segmentation fault, one very common outcome of uninitialized pointer access.
The problem is in your assignment \*a = 20. You can't allocate a value to a pointer variable like that. int b = 20; a = &b Thanks, Santhosh
15,760,336
These two views are inside of `RelativeLayout`. The IDE throws an error there is no `@id/et_pass`, but if I set `@+id/et_pass` it is OK. Why is that? ``` <ImageView android:id="@+id/devider_zero" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/et_pass" <!-- Error is here --> android:src="@drawable/registration_line" /> <EditText android:id="@+id/et_pass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/devider_first" android:background="@android:color/transparent" android:layout_gravity="left" android:ellipsize="start" android:ems="8" android:hint="@string/password" android:inputType="textPassword" android:layout_marginTop="@dimen/register_layout_edittext_margin_top" android:maxLines="1" /> ```
2013/04/02
[ "https://Stackoverflow.com/questions/15760336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/397991/" ]
In `int* a;` `a`'s default value is garbage, and points to an invalid memory, you can't assign to that. And assignment like `*a=20;` this is causes an undefined behavior at run time. (syntax wise code is correct so compiled) you may some time get a seg-fault too. either do: ``` int i; int *a = &i; // a points to a valid memory that is i *a = 20; ``` or with dynamic memory allocation using calloc() or malloc() functions. ``` int *a = malloc(sizeof(int)); *a = 20; ``` Remember dynamic allocated memories we have to deallocate (free) explicitly when we have done with that.
You have `wild pointer`, either assign memory to it using `malloc` ``` int* a = malloc(sizeof(int)); ``` or use a stack variable ``` int b = 0; int *a = &b; *a=20; ```
15,760,336
These two views are inside of `RelativeLayout`. The IDE throws an error there is no `@id/et_pass`, but if I set `@+id/et_pass` it is OK. Why is that? ``` <ImageView android:id="@+id/devider_zero" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@id/et_pass" <!-- Error is here --> android:src="@drawable/registration_line" /> <EditText android:id="@+id/et_pass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/devider_first" android:background="@android:color/transparent" android:layout_gravity="left" android:ellipsize="start" android:ems="8" android:hint="@string/password" android:inputType="textPassword" android:layout_marginTop="@dimen/register_layout_edittext_margin_top" android:maxLines="1" /> ```
2013/04/02
[ "https://Stackoverflow.com/questions/15760336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/397991/" ]
In `int* a;` `a`'s default value is garbage, and points to an invalid memory, you can't assign to that. And assignment like `*a=20;` this is causes an undefined behavior at run time. (syntax wise code is correct so compiled) you may some time get a seg-fault too. either do: ``` int i; int *a = &i; // a points to a valid memory that is i *a = 20; ``` or with dynamic memory allocation using calloc() or malloc() functions. ``` int *a = malloc(sizeof(int)); *a = 20; ``` Remember dynamic allocated memories we have to deallocate (free) explicitly when we have done with that.
The problem is in your assignment \*a = 20. You can't allocate a value to a pointer variable like that. int b = 20; a = &b Thanks, Santhosh
65,854,355
I'm doing a project and I'm having problems moving files into different subfolders. So for example, I have 2 files in the main folder, I want to read the first line, and if the first line has the word "Job", then I will move to the subfolder (main\_folder/files/jobs). My code looks like this: ``` # Get all file names in the directory def file_names(): files = [file for file in listdir(source_dir) if file.endswith('csv')] return files # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True # Move files def move_files(file_name, category): print(file_name) print(category) return shutil.move(source_dir + file_name, destination_dir + category + file_name) ``` So from my research, I'm guessing the file is still open (?) so I tried closing it. And move on, but somehow I end up having one file in the subfolder, and the original files still in the main folder. The error looks like this: ``` Traceback (most recent call last): File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 557, in move os.rename(src, real_dst) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' -> 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/files/jobs/file_14.csv' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 38, in <module> categorize_files(files) File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 22, in categorize_files move_files(file, 'jobs/') File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 35, in move_files return shutil.move(source_dir + file_name, destination_dir + category + file_name) File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 572, in move os.unlink(src) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' ``` Can someone please explain why I'm having a problem? Any advice will be greatly appreciated. ++ I also tried closing the file. And even restart the computer and never opened any files. Still get the same error..
2021/01/23
[ "https://Stackoverflow.com/questions/65854355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11639529/" ]
You're getting the error because you're trying to move move the file that you have open for reading inside the `with` statement. The following avoids that by moving the call to `move_files()` so it isn't called until the file has been closed. ``` # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: move_files(file, 'jobs/') print("This is a job related file") else: print("no") return True ```
Your file is being Used, Just close the program that it uses in the Taskmanager.
65,854,355
I'm doing a project and I'm having problems moving files into different subfolders. So for example, I have 2 files in the main folder, I want to read the first line, and if the first line has the word "Job", then I will move to the subfolder (main\_folder/files/jobs). My code looks like this: ``` # Get all file names in the directory def file_names(): files = [file for file in listdir(source_dir) if file.endswith('csv')] return files # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True # Move files def move_files(file_name, category): print(file_name) print(category) return shutil.move(source_dir + file_name, destination_dir + category + file_name) ``` So from my research, I'm guessing the file is still open (?) so I tried closing it. And move on, but somehow I end up having one file in the subfolder, and the original files still in the main folder. The error looks like this: ``` Traceback (most recent call last): File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 557, in move os.rename(src, real_dst) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' -> 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/files/jobs/file_14.csv' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 38, in <module> categorize_files(files) File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 22, in categorize_files move_files(file, 'jobs/') File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 35, in move_files return shutil.move(source_dir + file_name, destination_dir + category + file_name) File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 572, in move os.unlink(src) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' ``` Can someone please explain why I'm having a problem? Any advice will be greatly appreciated. ++ I also tried closing the file. And even restart the computer and never opened any files. Still get the same error..
2021/01/23
[ "https://Stackoverflow.com/questions/65854355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11639529/" ]
The error happens because you are trying to move a file while it is active and being read inside the `with` statement. The problem should be fixed if you un-indent the `if` statement by one layer. This should close the file and allow it to be moved. Here is the code: ``` # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True ```
Your file is being Used, Just close the program that it uses in the Taskmanager.
65,854,355
I'm doing a project and I'm having problems moving files into different subfolders. So for example, I have 2 files in the main folder, I want to read the first line, and if the first line has the word "Job", then I will move to the subfolder (main\_folder/files/jobs). My code looks like this: ``` # Get all file names in the directory def file_names(): files = [file for file in listdir(source_dir) if file.endswith('csv')] return files # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True # Move files def move_files(file_name, category): print(file_name) print(category) return shutil.move(source_dir + file_name, destination_dir + category + file_name) ``` So from my research, I'm guessing the file is still open (?) so I tried closing it. And move on, but somehow I end up having one file in the subfolder, and the original files still in the main folder. The error looks like this: ``` Traceback (most recent call last): File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 557, in move os.rename(src, real_dst) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' -> 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/files/jobs/file_14.csv' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 38, in <module> categorize_files(files) File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 22, in categorize_files move_files(file, 'jobs/') File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 35, in move_files return shutil.move(source_dir + file_name, destination_dir + category + file_name) File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 572, in move os.unlink(src) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' ``` Can someone please explain why I'm having a problem? Any advice will be greatly appreciated. ++ I also tried closing the file. And even restart the computer and never opened any files. Still get the same error..
2021/01/23
[ "https://Stackoverflow.com/questions/65854355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11639529/" ]
The easiest solution is just to unindent the `if` block in your program. ``` # Get all file names in the directory def file_names(): files = [file for file in listdir(source_dir) if file.endswith('csv')] return files # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True # Move files def move_files(file_name, category): print(file_name) print(category) return shutil.move(source_dir + file_name, destination_dir + category + file_name) ``` Although, I probably wouldn't have even used a `with` block for this application, just: ``` text = open(file, mode='r', encoding='utf8').readline().split(",") ``` Edit: In my (somewhat perverse) love of one liners, the if statement could be reduced to: ``` if 'Job ID' in open(file, mode='r', encoding='utf8').readline().split(",")[0]: ``` Share and Enjoy!
Your file is being Used, Just close the program that it uses in the Taskmanager.
65,854,355
I'm doing a project and I'm having problems moving files into different subfolders. So for example, I have 2 files in the main folder, I want to read the first line, and if the first line has the word "Job", then I will move to the subfolder (main\_folder/files/jobs). My code looks like this: ``` # Get all file names in the directory def file_names(): files = [file for file in listdir(source_dir) if file.endswith('csv')] return files # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True # Move files def move_files(file_name, category): print(file_name) print(category) return shutil.move(source_dir + file_name, destination_dir + category + file_name) ``` So from my research, I'm guessing the file is still open (?) so I tried closing it. And move on, but somehow I end up having one file in the subfolder, and the original files still in the main folder. The error looks like this: ``` Traceback (most recent call last): File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 557, in move os.rename(src, real_dst) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' -> 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/files/jobs/file_14.csv' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 38, in <module> categorize_files(files) File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 22, in categorize_files move_files(file, 'jobs/') File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 35, in move_files return shutil.move(source_dir + file_name, destination_dir + category + file_name) File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 572, in move os.unlink(src) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' ``` Can someone please explain why I'm having a problem? Any advice will be greatly appreciated. ++ I also tried closing the file. And even restart the computer and never opened any files. Still get the same error..
2021/01/23
[ "https://Stackoverflow.com/questions/65854355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11639529/" ]
The error happens because you are trying to move a file while it is active and being read inside the `with` statement. The problem should be fixed if you un-indent the `if` statement by one layer. This should close the file and allow it to be moved. Here is the code: ``` # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True ```
You're getting the error because you're trying to move move the file that you have open for reading inside the `with` statement. The following avoids that by moving the call to `move_files()` so it isn't called until the file has been closed. ``` # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: move_files(file, 'jobs/') print("This is a job related file") else: print("no") return True ```
65,854,355
I'm doing a project and I'm having problems moving files into different subfolders. So for example, I have 2 files in the main folder, I want to read the first line, and if the first line has the word "Job", then I will move to the subfolder (main\_folder/files/jobs). My code looks like this: ``` # Get all file names in the directory def file_names(): files = [file for file in listdir(source_dir) if file.endswith('csv')] return files # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True # Move files def move_files(file_name, category): print(file_name) print(category) return shutil.move(source_dir + file_name, destination_dir + category + file_name) ``` So from my research, I'm guessing the file is still open (?) so I tried closing it. And move on, but somehow I end up having one file in the subfolder, and the original files still in the main folder. The error looks like this: ``` Traceback (most recent call last): File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 557, in move os.rename(src, real_dst) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' -> 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/files/jobs/file_14.csv' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 38, in <module> categorize_files(files) File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 22, in categorize_files move_files(file, 'jobs/') File "C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_organizer.py", line 35, in move_files return shutil.move(source_dir + file_name, destination_dir + category + file_name) File "C:\Users\Muffin\AppData\Local\Programs\Python\Python37-32\lib\shutil.py", line 572, in move os.unlink(src) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/Muffin/Desktop/python/projects/Telegram-Database/file_14.csv' ``` Can someone please explain why I'm having a problem? Any advice will be greatly appreciated. ++ I also tried closing the file. And even restart the computer and never opened any files. Still get the same error..
2021/01/23
[ "https://Stackoverflow.com/questions/65854355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11639529/" ]
The easiest solution is just to unindent the `if` block in your program. ``` # Get all file names in the directory def file_names(): files = [file for file in listdir(source_dir) if file.endswith('csv')] return files # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: ## Problem Here ## move_files(file, 'jobs/') f.close() print("This is a job related file") else: print("no") return True # Move files def move_files(file_name, category): print(file_name) print(category) return shutil.move(source_dir + file_name, destination_dir + category + file_name) ``` Although, I probably wouldn't have even used a `with` block for this application, just: ``` text = open(file, mode='r', encoding='utf8').readline().split(",") ``` Edit: In my (somewhat perverse) love of one liners, the if statement could be reduced to: ``` if 'Job ID' in open(file, mode='r', encoding='utf8').readline().split(",")[0]: ``` Share and Enjoy!
You're getting the error because you're trying to move move the file that you have open for reading inside the `with` statement. The following avoids that by moving the call to `move_files()` so it isn't called until the file has been closed. ``` # Read files and separate them def categorize_files(files): for file in files: with open(file, mode='r', encoding='utf8') as f: text = f.readline().split(",") if 'Job ID' in text[0]: move_files(file, 'jobs/') print("This is a job related file") else: print("no") return True ```
14,138,188
[the error and the class http://puu.sh/1ITnS.png](http://puu.sh/1ITnS.png) When I name the class file Main.class, java says it has the wrong name, and when I name it shop.Main.class it says that the main class can't be found. Can anyone help? ``` package shop; import java.text.DecimalFormat; public class Main { public static void main(String args[]) { Cart cart = new Cart(new Catalogue()); printOrder(cart); } public static void printOrder(Cart cart) { DecimalFormat df = new DecimalFormat("0.00"); System.out.println("Your order:"); for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) if (cart.itemsInCart.products.get(itemIndex).quantity != 0) System.out.println(cart.itemsInCart.products.get(itemIndex).quantity + " " + cart.itemsInCart.products.get(itemIndex).name + " $"+ df.format(cart.itemsInCart.products.get(itemIndex).price) + " = $" + df.format ((cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price))); double subtotal = 0; int taxPercent = 20; double tax; double total; for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) subtotal += cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price; tax = subtotal * taxPercent / 100; total = subtotal + tax; System.out.print("Subtotal: $" + df.format(subtotal) + " Tax @ " + taxPercent + "%: $" + df.format(tax) + " Grand Total: $" + df.format(total)); } } ``` Ignore between the following two lines ––––––––––––––––––––––––– Edit Summary Oops! Your edit couldn't be submitted because: Your post does not have much context to explain the code sections; please explain your scenario more clearly. cancel ––––––––––––––––––––––---
2013/01/03
[ "https://Stackoverflow.com/questions/14138188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1774214/" ]
keep it Main.class and try `java shop.Main` from command line in java folder
compile: ~/java> javac shop/Main.java run: ~/java> java shop.Main
14,138,188
[the error and the class http://puu.sh/1ITnS.png](http://puu.sh/1ITnS.png) When I name the class file Main.class, java says it has the wrong name, and when I name it shop.Main.class it says that the main class can't be found. Can anyone help? ``` package shop; import java.text.DecimalFormat; public class Main { public static void main(String args[]) { Cart cart = new Cart(new Catalogue()); printOrder(cart); } public static void printOrder(Cart cart) { DecimalFormat df = new DecimalFormat("0.00"); System.out.println("Your order:"); for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) if (cart.itemsInCart.products.get(itemIndex).quantity != 0) System.out.println(cart.itemsInCart.products.get(itemIndex).quantity + " " + cart.itemsInCart.products.get(itemIndex).name + " $"+ df.format(cart.itemsInCart.products.get(itemIndex).price) + " = $" + df.format ((cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price))); double subtotal = 0; int taxPercent = 20; double tax; double total; for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) subtotal += cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price; tax = subtotal * taxPercent / 100; total = subtotal + tax; System.out.print("Subtotal: $" + df.format(subtotal) + " Tax @ " + taxPercent + "%: $" + df.format(tax) + " Grand Total: $" + df.format(total)); } } ``` Ignore between the following two lines ––––––––––––––––––––––––– Edit Summary Oops! Your edit couldn't be submitted because: Your post does not have much context to explain the code sections; please explain your scenario more clearly. cancel ––––––––––––––––––––––---
2013/01/03
[ "https://Stackoverflow.com/questions/14138188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1774214/" ]
keep it Main.class and try `java shop.Main` from command line in java folder
You should be careful to place classes in correct folders if compiling manually (package name equals folder name on disk). I recommend using an IDE (Eclipse and Netbeans are both good and free choices). Your example will work if you place Main.class in folder called "shop" and then from project root folder execute "java shop/Main"
14,138,188
[the error and the class http://puu.sh/1ITnS.png](http://puu.sh/1ITnS.png) When I name the class file Main.class, java says it has the wrong name, and when I name it shop.Main.class it says that the main class can't be found. Can anyone help? ``` package shop; import java.text.DecimalFormat; public class Main { public static void main(String args[]) { Cart cart = new Cart(new Catalogue()); printOrder(cart); } public static void printOrder(Cart cart) { DecimalFormat df = new DecimalFormat("0.00"); System.out.println("Your order:"); for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) if (cart.itemsInCart.products.get(itemIndex).quantity != 0) System.out.println(cart.itemsInCart.products.get(itemIndex).quantity + " " + cart.itemsInCart.products.get(itemIndex).name + " $"+ df.format(cart.itemsInCart.products.get(itemIndex).price) + " = $" + df.format ((cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price))); double subtotal = 0; int taxPercent = 20; double tax; double total; for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) subtotal += cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price; tax = subtotal * taxPercent / 100; total = subtotal + tax; System.out.print("Subtotal: $" + df.format(subtotal) + " Tax @ " + taxPercent + "%: $" + df.format(tax) + " Grand Total: $" + df.format(total)); } } ``` Ignore between the following two lines ––––––––––––––––––––––––– Edit Summary Oops! Your edit couldn't be submitted because: Your post does not have much context to explain the code sections; please explain your scenario more clearly. cancel ––––––––––––––––––––––---
2013/01/03
[ "https://Stackoverflow.com/questions/14138188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1774214/" ]
Execute these commands: ``` cd .. java shop.Main ``` You can't run java code from inside a package you are trying to reference.
compile: ~/java> javac shop/Main.java run: ~/java> java shop.Main
14,138,188
[the error and the class http://puu.sh/1ITnS.png](http://puu.sh/1ITnS.png) When I name the class file Main.class, java says it has the wrong name, and when I name it shop.Main.class it says that the main class can't be found. Can anyone help? ``` package shop; import java.text.DecimalFormat; public class Main { public static void main(String args[]) { Cart cart = new Cart(new Catalogue()); printOrder(cart); } public static void printOrder(Cart cart) { DecimalFormat df = new DecimalFormat("0.00"); System.out.println("Your order:"); for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) if (cart.itemsInCart.products.get(itemIndex).quantity != 0) System.out.println(cart.itemsInCart.products.get(itemIndex).quantity + " " + cart.itemsInCart.products.get(itemIndex).name + " $"+ df.format(cart.itemsInCart.products.get(itemIndex).price) + " = $" + df.format ((cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price))); double subtotal = 0; int taxPercent = 20; double tax; double total; for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) subtotal += cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price; tax = subtotal * taxPercent / 100; total = subtotal + tax; System.out.print("Subtotal: $" + df.format(subtotal) + " Tax @ " + taxPercent + "%: $" + df.format(tax) + " Grand Total: $" + df.format(total)); } } ``` Ignore between the following two lines ––––––––––––––––––––––––– Edit Summary Oops! Your edit couldn't be submitted because: Your post does not have much context to explain the code sections; please explain your scenario more clearly. cancel ––––––––––––––––––––––---
2013/01/03
[ "https://Stackoverflow.com/questions/14138188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1774214/" ]
compile: ~/java> javac shop/Main.java run: ~/java> java shop.Main
You should be careful to place classes in correct folders if compiling manually (package name equals folder name on disk). I recommend using an IDE (Eclipse and Netbeans are both good and free choices). Your example will work if you place Main.class in folder called "shop" and then from project root folder execute "java shop/Main"
14,138,188
[the error and the class http://puu.sh/1ITnS.png](http://puu.sh/1ITnS.png) When I name the class file Main.class, java says it has the wrong name, and when I name it shop.Main.class it says that the main class can't be found. Can anyone help? ``` package shop; import java.text.DecimalFormat; public class Main { public static void main(String args[]) { Cart cart = new Cart(new Catalogue()); printOrder(cart); } public static void printOrder(Cart cart) { DecimalFormat df = new DecimalFormat("0.00"); System.out.println("Your order:"); for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) if (cart.itemsInCart.products.get(itemIndex).quantity != 0) System.out.println(cart.itemsInCart.products.get(itemIndex).quantity + " " + cart.itemsInCart.products.get(itemIndex).name + " $"+ df.format(cart.itemsInCart.products.get(itemIndex).price) + " = $" + df.format ((cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price))); double subtotal = 0; int taxPercent = 20; double tax; double total; for(int itemIndex = 0; itemIndex < cart.itemsInCart.products.size(); itemIndex++) subtotal += cart.itemsInCart.products.get(itemIndex).quantity * cart.itemsInCart.products.get(itemIndex).price; tax = subtotal * taxPercent / 100; total = subtotal + tax; System.out.print("Subtotal: $" + df.format(subtotal) + " Tax @ " + taxPercent + "%: $" + df.format(tax) + " Grand Total: $" + df.format(total)); } } ``` Ignore between the following two lines ––––––––––––––––––––––––– Edit Summary Oops! Your edit couldn't be submitted because: Your post does not have much context to explain the code sections; please explain your scenario more clearly. cancel ––––––––––––––––––––––---
2013/01/03
[ "https://Stackoverflow.com/questions/14138188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1774214/" ]
Execute these commands: ``` cd .. java shop.Main ``` You can't run java code from inside a package you are trying to reference.
You should be careful to place classes in correct folders if compiling manually (package name equals folder name on disk). I recommend using an IDE (Eclipse and Netbeans are both good and free choices). Your example will work if you place Main.class in folder called "shop" and then from project root folder execute "java shop/Main"
44,135,248
I am trying to retrieve data from excel and put them into the following format in python: ``` dataset={ 'User A': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5, 'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5, 'The Night Listener': 3.0}, 'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5, 'Just My Luck': 1.5, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5, 'The Night Listener': 3.0 }} ``` Where the excel file looks like ``` User A User B Lady in the Water 2.5 3 Snakes on a Plane 3.5 3.5 Just My Luck 3 1.5 Superman Returns 3.5 5 You, Me and Dupree 2.5 3.5 The Night Listener 3 3 ```
2017/05/23
[ "https://Stackoverflow.com/questions/44135248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7677413/" ]
The `pandas` module makes this pretty easy: ``` import pandas as pd df = pd.read_excel('workbook.xlsx', index_col=0) dataset = df.to_dict() ``` In this code the `pd.read_excel` function collects all data from the excel file and stores it into a pandas [DataFrame](https://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe) variable. Dataframes come with an enormous amount of very powerful [built-in methods for data reorganization and manipulation](https://github.com/pandas-dev/pandas/blob/master/doc/cheatsheet/Pandas_Cheat_Sheet.pdf). One of these methods is the `to_dict`, which is used in the code here to convert the data to nested dictionaries.
Another way is through openpyxl: ``` from openpyxl import Workbook wb = load_workbook(filename = 'workbook.xlsx') sheet_ranges = wb['cell range'] values = sheet_ranges['cell locations'].values() data = values.to_dict() ```
28,645
I'm developing a finite volume solver for the simple twodimensional advection equation with constant velocities $u, v$ and constant mesh spaces $\Delta x$: $$ \frac{\partial \rho}{\partial t} + u \frac{\partial \rho}{\partial x} + v \frac{\partial \rho}{\partial y} = 0$$ where $u,v > 0$. According to [this lecture](http://www.mpia.de/homes/dullemon/lectures/hydrodynamicsII/chap_4.pdf), the piecewise linear update scheme in 1D is $$ \rho\_i^{n+1} = \rho\_i^n - \frac{u \Delta t}{\Delta x} ( \rho\_i ^n - \rho\_{i-1}^n) - \frac{u \Delta t}{\Delta x} \frac{1}{2} (s\_i^n - s\_{i-1}^n)(\Delta x - u\Delta t) $$ where $s\_i^n$ is a slope, that may be chosen as Centered slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i-1}}{2\Delta x}$ (Fromm's method) Upwind slope: $s\_i^n = \frac{\rho\_{i} - \rho\_{i-1}}{\Delta x}$ (Beam-Warming method) Downwind slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i}}{\Delta x}$ (Lax-Wendroff method) and any of these choices results in second-order accurate methods. I implemented these methods in 1D, and they work as expected. In the plot below is the 1D advection for $u=1$ with periodic boundaries for a step function at various time steps with 1000 cells. An integer time step means that the curve has gone that many times through the whole domain. [![1d advection results](https://i.stack.imgur.com/tkiLb.png)](https://i.stack.imgur.com/tkiLb.png) For the 2D method, I evaluate the new value simultaneously in both directions, according to the 2d advection equation as above, while approximating the divergence terms by the piecewise linear scheme as stated above. If I only let the density advect in one direction, i.e. $u = 0, v=1$ or $u=1, v=0$, I get the expected results, corresponding to the 1D solution. If I choose the timestep to be $\Delta t = [u/\Delta x + v/\Delta y]^{-1}$ as [wikipedia suggests](https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition) (as opposed to $t< [u/\Delta x + v/\Delta y]^{-1}$), I even get perfect advection without diffusion, as it is predicted by the 1d case. But if I give both $u$ and $v$ nonzero values, e.g. $u = v = \sqrt{2}/2$, at some point, apparently at some point in time, the solution becomes unstable, and I do not know why. This happens for any choice of the slope. Or does it only look unstable to the inexperienced me, but is in fact just the interference of the oscillations produced by the piecewise linear scheme without any slope limiters? (The situation gets a bit better with a minmod or Van Leer slope limiter). Below you can see the results of a 2d simulation at various time steps for $nx = ny = 200$ for a 2D step function, using the downwind slope. (The timesteps are 0, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 5.0, 10.0) [![2d advection results](https://i.stack.imgur.com/ClEOV.png)](https://i.stack.imgur.com/ClEOV.png) Can anyone tell me how/why this apparent instability occurs, and what to do against it?
2018/01/18
[ "https://scicomp.stackexchange.com/questions/28645", "https://scicomp.stackexchange.com", "https://scicomp.stackexchange.com/users/26461/" ]
Oscillations is a natural result of higher-order approximations near discontinuities/shocks for hyperbolic conservation laws. Recall that the finite-difference approximations you have listed are generally derived using truncated Taylor expansions, which requires a degree of smoothness which is not present in your model problem. As you have observed, the single-point upwinding does not suffer from oscillations, but has low order. One solution is to use a limiter, which uses the low order approximation where the solution is not sufficiently smooth. Many possible choices are found in the literature, some of which are detailed on wikipedia: <https://en.wikipedia.org/wiki/Flux_limiter>
Each numerical scheme can have a different stability condition, so you can not use the single one as suggested by the page in Wikipedia. Simply try a smaller time step and if your code is correct you should obtain a stable solution for enough small time step. I am on phone so i can not check it and write it in a mathematical mode, but in your case, I think, your time step must be smaller than the minimal time step of two related one dimensional stability restriction. By the way if you are showing us a typical example you want to solve, you should check the so called Corner Transport Upwind scheme, e.g. in the book of LeVeque on hyperbolic problems, that has the stability condition you are quoting.
28,645
I'm developing a finite volume solver for the simple twodimensional advection equation with constant velocities $u, v$ and constant mesh spaces $\Delta x$: $$ \frac{\partial \rho}{\partial t} + u \frac{\partial \rho}{\partial x} + v \frac{\partial \rho}{\partial y} = 0$$ where $u,v > 0$. According to [this lecture](http://www.mpia.de/homes/dullemon/lectures/hydrodynamicsII/chap_4.pdf), the piecewise linear update scheme in 1D is $$ \rho\_i^{n+1} = \rho\_i^n - \frac{u \Delta t}{\Delta x} ( \rho\_i ^n - \rho\_{i-1}^n) - \frac{u \Delta t}{\Delta x} \frac{1}{2} (s\_i^n - s\_{i-1}^n)(\Delta x - u\Delta t) $$ where $s\_i^n$ is a slope, that may be chosen as Centered slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i-1}}{2\Delta x}$ (Fromm's method) Upwind slope: $s\_i^n = \frac{\rho\_{i} - \rho\_{i-1}}{\Delta x}$ (Beam-Warming method) Downwind slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i}}{\Delta x}$ (Lax-Wendroff method) and any of these choices results in second-order accurate methods. I implemented these methods in 1D, and they work as expected. In the plot below is the 1D advection for $u=1$ with periodic boundaries for a step function at various time steps with 1000 cells. An integer time step means that the curve has gone that many times through the whole domain. [![1d advection results](https://i.stack.imgur.com/tkiLb.png)](https://i.stack.imgur.com/tkiLb.png) For the 2D method, I evaluate the new value simultaneously in both directions, according to the 2d advection equation as above, while approximating the divergence terms by the piecewise linear scheme as stated above. If I only let the density advect in one direction, i.e. $u = 0, v=1$ or $u=1, v=0$, I get the expected results, corresponding to the 1D solution. If I choose the timestep to be $\Delta t = [u/\Delta x + v/\Delta y]^{-1}$ as [wikipedia suggests](https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition) (as opposed to $t< [u/\Delta x + v/\Delta y]^{-1}$), I even get perfect advection without diffusion, as it is predicted by the 1d case. But if I give both $u$ and $v$ nonzero values, e.g. $u = v = \sqrt{2}/2$, at some point, apparently at some point in time, the solution becomes unstable, and I do not know why. This happens for any choice of the slope. Or does it only look unstable to the inexperienced me, but is in fact just the interference of the oscillations produced by the piecewise linear scheme without any slope limiters? (The situation gets a bit better with a minmod or Van Leer slope limiter). Below you can see the results of a 2d simulation at various time steps for $nx = ny = 200$ for a 2D step function, using the downwind slope. (The timesteps are 0, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 5.0, 10.0) [![2d advection results](https://i.stack.imgur.com/ClEOV.png)](https://i.stack.imgur.com/ClEOV.png) Can anyone tell me how/why this apparent instability occurs, and what to do against it?
2018/01/18
[ "https://scicomp.stackexchange.com/questions/28645", "https://scicomp.stackexchange.com", "https://scicomp.stackexchange.com/users/26461/" ]
It turns out that the main problem here was that I thought just naively extending the 1D advection $$ \rho^{n+1}\_{i} = \rho^n\_{i} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2} - \rho^n\_{i+1/2}) $$ to 2D just by adding the $y$ term like this: $$ \rho^{n+1}\_{i,j} = \rho^n\_{i,j} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2,j} - \rho^n\_{i+1/2,j}) + v\frac{\Delta t}{\Delta x}(\rho^n\_{i, j-1/2} - \rho^n\_{i,j+1/2}) $$ would be a good idea. It isn't. Suppose we have $u = v = 1$. Then what one would naturally expect is that the value $\rho\_{i-1, j-1}$ advects to the position $\rho\_{i, j}$ over one adequately chosen timestep. But looking at the formula above which I tried to implement, the value of $\rho\_{i-1, j-1}$ never comes into play. Hence the stencil that I'm using is inadequate. Looking for example at the upper left corner of the square with higher density in the initial conditions, what happens is that we do get diffusion from the right and from below, but do not interact with the cell one place below and to the left, so more material will advect into the cell. Over many time steps, the result is that "stripes" perpendicular to the direction of advection will develop. Instead, I should have been using an adequate multidimensional technique. Since I wanted to extend my 1D solvers to 2D, a proper extension is dimensional splitting, where you compute an intermediate state first: $$ \rho^{n+1/2}\_{i} = \rho^n\_{i} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2, j} - \rho^n\_{i+1/2, j}) $$ called the "$x$-sweep", and then we do the "$y$-sweep": $$ \rho^{n+1}\_{i} = \rho^{n+1/2}\_{i} + v\frac{\Delta t}{\Delta x}(\rho^{n+1/2}\_{i,j-1/2} - \rho^{n+1/2}\_{i,j+1/2}) $$ This way, the values "on the corners" are taken care of. Another really cool thing about this dimensional splitting is that one can show that if we keep the time steps $\Delta t$ constant and switch the order of the sweeps every step, the method will become second order accurate in time for basically no extra effort. This is called "Strang splitting". To demonstrate: Here is what happens if no dimensional/Strang splitting is used: [![no strang splitting](https://i.stack.imgur.com/KNGiG.png)](https://i.stack.imgur.com/KNGiG.png) notice the stripes I was talking about. And this is what happens if the only change is doing proper Strang splitting: [![with strang splitting](https://i.stack.imgur.com/gSTvd.png)](https://i.stack.imgur.com/gSTvd.png)
Each numerical scheme can have a different stability condition, so you can not use the single one as suggested by the page in Wikipedia. Simply try a smaller time step and if your code is correct you should obtain a stable solution for enough small time step. I am on phone so i can not check it and write it in a mathematical mode, but in your case, I think, your time step must be smaller than the minimal time step of two related one dimensional stability restriction. By the way if you are showing us a typical example you want to solve, you should check the so called Corner Transport Upwind scheme, e.g. in the book of LeVeque on hyperbolic problems, that has the stability condition you are quoting.
28,645
I'm developing a finite volume solver for the simple twodimensional advection equation with constant velocities $u, v$ and constant mesh spaces $\Delta x$: $$ \frac{\partial \rho}{\partial t} + u \frac{\partial \rho}{\partial x} + v \frac{\partial \rho}{\partial y} = 0$$ where $u,v > 0$. According to [this lecture](http://www.mpia.de/homes/dullemon/lectures/hydrodynamicsII/chap_4.pdf), the piecewise linear update scheme in 1D is $$ \rho\_i^{n+1} = \rho\_i^n - \frac{u \Delta t}{\Delta x} ( \rho\_i ^n - \rho\_{i-1}^n) - \frac{u \Delta t}{\Delta x} \frac{1}{2} (s\_i^n - s\_{i-1}^n)(\Delta x - u\Delta t) $$ where $s\_i^n$ is a slope, that may be chosen as Centered slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i-1}}{2\Delta x}$ (Fromm's method) Upwind slope: $s\_i^n = \frac{\rho\_{i} - \rho\_{i-1}}{\Delta x}$ (Beam-Warming method) Downwind slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i}}{\Delta x}$ (Lax-Wendroff method) and any of these choices results in second-order accurate methods. I implemented these methods in 1D, and they work as expected. In the plot below is the 1D advection for $u=1$ with periodic boundaries for a step function at various time steps with 1000 cells. An integer time step means that the curve has gone that many times through the whole domain. [![1d advection results](https://i.stack.imgur.com/tkiLb.png)](https://i.stack.imgur.com/tkiLb.png) For the 2D method, I evaluate the new value simultaneously in both directions, according to the 2d advection equation as above, while approximating the divergence terms by the piecewise linear scheme as stated above. If I only let the density advect in one direction, i.e. $u = 0, v=1$ or $u=1, v=0$, I get the expected results, corresponding to the 1D solution. If I choose the timestep to be $\Delta t = [u/\Delta x + v/\Delta y]^{-1}$ as [wikipedia suggests](https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition) (as opposed to $t< [u/\Delta x + v/\Delta y]^{-1}$), I even get perfect advection without diffusion, as it is predicted by the 1d case. But if I give both $u$ and $v$ nonzero values, e.g. $u = v = \sqrt{2}/2$, at some point, apparently at some point in time, the solution becomes unstable, and I do not know why. This happens for any choice of the slope. Or does it only look unstable to the inexperienced me, but is in fact just the interference of the oscillations produced by the piecewise linear scheme without any slope limiters? (The situation gets a bit better with a minmod or Van Leer slope limiter). Below you can see the results of a 2d simulation at various time steps for $nx = ny = 200$ for a 2D step function, using the downwind slope. (The timesteps are 0, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 5.0, 10.0) [![2d advection results](https://i.stack.imgur.com/ClEOV.png)](https://i.stack.imgur.com/ClEOV.png) Can anyone tell me how/why this apparent instability occurs, and what to do against it?
2018/01/18
[ "https://scicomp.stackexchange.com/questions/28645", "https://scicomp.stackexchange.com", "https://scicomp.stackexchange.com/users/26461/" ]
Oscillations is a natural result of higher-order approximations near discontinuities/shocks for hyperbolic conservation laws. Recall that the finite-difference approximations you have listed are generally derived using truncated Taylor expansions, which requires a degree of smoothness which is not present in your model problem. As you have observed, the single-point upwinding does not suffer from oscillations, but has low order. One solution is to use a limiter, which uses the low order approximation where the solution is not sufficiently smooth. Many possible choices are found in the literature, some of which are detailed on wikipedia: <https://en.wikipedia.org/wiki/Flux_limiter>
A numerical scheme can be unconditionally unstable, conditionally stable and unconditionally stable. You would want the later two. I would recommend that you learn to do **Von-Neumann stability analysis** for numerical schemes. You learn it once. And you can find yourself the stability status of any arbitrary governing differential equation for any arbitrary numerical scheme.
28,645
I'm developing a finite volume solver for the simple twodimensional advection equation with constant velocities $u, v$ and constant mesh spaces $\Delta x$: $$ \frac{\partial \rho}{\partial t} + u \frac{\partial \rho}{\partial x} + v \frac{\partial \rho}{\partial y} = 0$$ where $u,v > 0$. According to [this lecture](http://www.mpia.de/homes/dullemon/lectures/hydrodynamicsII/chap_4.pdf), the piecewise linear update scheme in 1D is $$ \rho\_i^{n+1} = \rho\_i^n - \frac{u \Delta t}{\Delta x} ( \rho\_i ^n - \rho\_{i-1}^n) - \frac{u \Delta t}{\Delta x} \frac{1}{2} (s\_i^n - s\_{i-1}^n)(\Delta x - u\Delta t) $$ where $s\_i^n$ is a slope, that may be chosen as Centered slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i-1}}{2\Delta x}$ (Fromm's method) Upwind slope: $s\_i^n = \frac{\rho\_{i} - \rho\_{i-1}}{\Delta x}$ (Beam-Warming method) Downwind slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i}}{\Delta x}$ (Lax-Wendroff method) and any of these choices results in second-order accurate methods. I implemented these methods in 1D, and they work as expected. In the plot below is the 1D advection for $u=1$ with periodic boundaries for a step function at various time steps with 1000 cells. An integer time step means that the curve has gone that many times through the whole domain. [![1d advection results](https://i.stack.imgur.com/tkiLb.png)](https://i.stack.imgur.com/tkiLb.png) For the 2D method, I evaluate the new value simultaneously in both directions, according to the 2d advection equation as above, while approximating the divergence terms by the piecewise linear scheme as stated above. If I only let the density advect in one direction, i.e. $u = 0, v=1$ or $u=1, v=0$, I get the expected results, corresponding to the 1D solution. If I choose the timestep to be $\Delta t = [u/\Delta x + v/\Delta y]^{-1}$ as [wikipedia suggests](https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition) (as opposed to $t< [u/\Delta x + v/\Delta y]^{-1}$), I even get perfect advection without diffusion, as it is predicted by the 1d case. But if I give both $u$ and $v$ nonzero values, e.g. $u = v = \sqrt{2}/2$, at some point, apparently at some point in time, the solution becomes unstable, and I do not know why. This happens for any choice of the slope. Or does it only look unstable to the inexperienced me, but is in fact just the interference of the oscillations produced by the piecewise linear scheme without any slope limiters? (The situation gets a bit better with a minmod or Van Leer slope limiter). Below you can see the results of a 2d simulation at various time steps for $nx = ny = 200$ for a 2D step function, using the downwind slope. (The timesteps are 0, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 5.0, 10.0) [![2d advection results](https://i.stack.imgur.com/ClEOV.png)](https://i.stack.imgur.com/ClEOV.png) Can anyone tell me how/why this apparent instability occurs, and what to do against it?
2018/01/18
[ "https://scicomp.stackexchange.com/questions/28645", "https://scicomp.stackexchange.com", "https://scicomp.stackexchange.com/users/26461/" ]
It turns out that the main problem here was that I thought just naively extending the 1D advection $$ \rho^{n+1}\_{i} = \rho^n\_{i} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2} - \rho^n\_{i+1/2}) $$ to 2D just by adding the $y$ term like this: $$ \rho^{n+1}\_{i,j} = \rho^n\_{i,j} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2,j} - \rho^n\_{i+1/2,j}) + v\frac{\Delta t}{\Delta x}(\rho^n\_{i, j-1/2} - \rho^n\_{i,j+1/2}) $$ would be a good idea. It isn't. Suppose we have $u = v = 1$. Then what one would naturally expect is that the value $\rho\_{i-1, j-1}$ advects to the position $\rho\_{i, j}$ over one adequately chosen timestep. But looking at the formula above which I tried to implement, the value of $\rho\_{i-1, j-1}$ never comes into play. Hence the stencil that I'm using is inadequate. Looking for example at the upper left corner of the square with higher density in the initial conditions, what happens is that we do get diffusion from the right and from below, but do not interact with the cell one place below and to the left, so more material will advect into the cell. Over many time steps, the result is that "stripes" perpendicular to the direction of advection will develop. Instead, I should have been using an adequate multidimensional technique. Since I wanted to extend my 1D solvers to 2D, a proper extension is dimensional splitting, where you compute an intermediate state first: $$ \rho^{n+1/2}\_{i} = \rho^n\_{i} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2, j} - \rho^n\_{i+1/2, j}) $$ called the "$x$-sweep", and then we do the "$y$-sweep": $$ \rho^{n+1}\_{i} = \rho^{n+1/2}\_{i} + v\frac{\Delta t}{\Delta x}(\rho^{n+1/2}\_{i,j-1/2} - \rho^{n+1/2}\_{i,j+1/2}) $$ This way, the values "on the corners" are taken care of. Another really cool thing about this dimensional splitting is that one can show that if we keep the time steps $\Delta t$ constant and switch the order of the sweeps every step, the method will become second order accurate in time for basically no extra effort. This is called "Strang splitting". To demonstrate: Here is what happens if no dimensional/Strang splitting is used: [![no strang splitting](https://i.stack.imgur.com/KNGiG.png)](https://i.stack.imgur.com/KNGiG.png) notice the stripes I was talking about. And this is what happens if the only change is doing proper Strang splitting: [![with strang splitting](https://i.stack.imgur.com/gSTvd.png)](https://i.stack.imgur.com/gSTvd.png)
A numerical scheme can be unconditionally unstable, conditionally stable and unconditionally stable. You would want the later two. I would recommend that you learn to do **Von-Neumann stability analysis** for numerical schemes. You learn it once. And you can find yourself the stability status of any arbitrary governing differential equation for any arbitrary numerical scheme.
28,645
I'm developing a finite volume solver for the simple twodimensional advection equation with constant velocities $u, v$ and constant mesh spaces $\Delta x$: $$ \frac{\partial \rho}{\partial t} + u \frac{\partial \rho}{\partial x} + v \frac{\partial \rho}{\partial y} = 0$$ where $u,v > 0$. According to [this lecture](http://www.mpia.de/homes/dullemon/lectures/hydrodynamicsII/chap_4.pdf), the piecewise linear update scheme in 1D is $$ \rho\_i^{n+1} = \rho\_i^n - \frac{u \Delta t}{\Delta x} ( \rho\_i ^n - \rho\_{i-1}^n) - \frac{u \Delta t}{\Delta x} \frac{1}{2} (s\_i^n - s\_{i-1}^n)(\Delta x - u\Delta t) $$ where $s\_i^n$ is a slope, that may be chosen as Centered slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i-1}}{2\Delta x}$ (Fromm's method) Upwind slope: $s\_i^n = \frac{\rho\_{i} - \rho\_{i-1}}{\Delta x}$ (Beam-Warming method) Downwind slope: $s\_i^n = \frac{\rho\_{i+1} - \rho\_{i}}{\Delta x}$ (Lax-Wendroff method) and any of these choices results in second-order accurate methods. I implemented these methods in 1D, and they work as expected. In the plot below is the 1D advection for $u=1$ with periodic boundaries for a step function at various time steps with 1000 cells. An integer time step means that the curve has gone that many times through the whole domain. [![1d advection results](https://i.stack.imgur.com/tkiLb.png)](https://i.stack.imgur.com/tkiLb.png) For the 2D method, I evaluate the new value simultaneously in both directions, according to the 2d advection equation as above, while approximating the divergence terms by the piecewise linear scheme as stated above. If I only let the density advect in one direction, i.e. $u = 0, v=1$ or $u=1, v=0$, I get the expected results, corresponding to the 1D solution. If I choose the timestep to be $\Delta t = [u/\Delta x + v/\Delta y]^{-1}$ as [wikipedia suggests](https://en.wikipedia.org/wiki/Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition) (as opposed to $t< [u/\Delta x + v/\Delta y]^{-1}$), I even get perfect advection without diffusion, as it is predicted by the 1d case. But if I give both $u$ and $v$ nonzero values, e.g. $u = v = \sqrt{2}/2$, at some point, apparently at some point in time, the solution becomes unstable, and I do not know why. This happens for any choice of the slope. Or does it only look unstable to the inexperienced me, but is in fact just the interference of the oscillations produced by the piecewise linear scheme without any slope limiters? (The situation gets a bit better with a minmod or Van Leer slope limiter). Below you can see the results of a 2d simulation at various time steps for $nx = ny = 200$ for a 2D step function, using the downwind slope. (The timesteps are 0, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 5.0, 10.0) [![2d advection results](https://i.stack.imgur.com/ClEOV.png)](https://i.stack.imgur.com/ClEOV.png) Can anyone tell me how/why this apparent instability occurs, and what to do against it?
2018/01/18
[ "https://scicomp.stackexchange.com/questions/28645", "https://scicomp.stackexchange.com", "https://scicomp.stackexchange.com/users/26461/" ]
It turns out that the main problem here was that I thought just naively extending the 1D advection $$ \rho^{n+1}\_{i} = \rho^n\_{i} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2} - \rho^n\_{i+1/2}) $$ to 2D just by adding the $y$ term like this: $$ \rho^{n+1}\_{i,j} = \rho^n\_{i,j} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2,j} - \rho^n\_{i+1/2,j}) + v\frac{\Delta t}{\Delta x}(\rho^n\_{i, j-1/2} - \rho^n\_{i,j+1/2}) $$ would be a good idea. It isn't. Suppose we have $u = v = 1$. Then what one would naturally expect is that the value $\rho\_{i-1, j-1}$ advects to the position $\rho\_{i, j}$ over one adequately chosen timestep. But looking at the formula above which I tried to implement, the value of $\rho\_{i-1, j-1}$ never comes into play. Hence the stencil that I'm using is inadequate. Looking for example at the upper left corner of the square with higher density in the initial conditions, what happens is that we do get diffusion from the right and from below, but do not interact with the cell one place below and to the left, so more material will advect into the cell. Over many time steps, the result is that "stripes" perpendicular to the direction of advection will develop. Instead, I should have been using an adequate multidimensional technique. Since I wanted to extend my 1D solvers to 2D, a proper extension is dimensional splitting, where you compute an intermediate state first: $$ \rho^{n+1/2}\_{i} = \rho^n\_{i} + u\frac{\Delta t}{\Delta x}(\rho^n\_{i-1/2, j} - \rho^n\_{i+1/2, j}) $$ called the "$x$-sweep", and then we do the "$y$-sweep": $$ \rho^{n+1}\_{i} = \rho^{n+1/2}\_{i} + v\frac{\Delta t}{\Delta x}(\rho^{n+1/2}\_{i,j-1/2} - \rho^{n+1/2}\_{i,j+1/2}) $$ This way, the values "on the corners" are taken care of. Another really cool thing about this dimensional splitting is that one can show that if we keep the time steps $\Delta t$ constant and switch the order of the sweeps every step, the method will become second order accurate in time for basically no extra effort. This is called "Strang splitting". To demonstrate: Here is what happens if no dimensional/Strang splitting is used: [![no strang splitting](https://i.stack.imgur.com/KNGiG.png)](https://i.stack.imgur.com/KNGiG.png) notice the stripes I was talking about. And this is what happens if the only change is doing proper Strang splitting: [![with strang splitting](https://i.stack.imgur.com/gSTvd.png)](https://i.stack.imgur.com/gSTvd.png)
Oscillations is a natural result of higher-order approximations near discontinuities/shocks for hyperbolic conservation laws. Recall that the finite-difference approximations you have listed are generally derived using truncated Taylor expansions, which requires a degree of smoothness which is not present in your model problem. As you have observed, the single-point upwinding does not suffer from oscillations, but has low order. One solution is to use a limiter, which uses the low order approximation where the solution is not sufficiently smooth. Many possible choices are found in the literature, some of which are detailed on wikipedia: <https://en.wikipedia.org/wiki/Flux_limiter>
21,107,057
Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid?
2014/01/14
[ "https://Stackoverflow.com/questions/21107057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813758/" ]
I've solved the problem using `set_request_factory`: ``` from pyramid.request import Request from pyramid.request import Response def request_factory(environ): request = Request(environ) if request.is_xhr: request.response = Response() request.response.headerlist = [] request.response.headerlist.extend( ( ('Access-Control-Allow-Origin', '*'), ('Content-Type', 'application/json') ) ) return request config.set_request_factory(request_factory) ```
I could send file with Ajax from a server to another server : ``` import uuid from pyramid.view import view_config from pyramid.response import Response class FManager: def __init__(self, request): self.request = request @view_config(route_name='f_manager', request_method='POST', renderer='json') def post(self): file_ = self.request.POST.items() content_type = str(file_[0][1].type).split('/') file_[0][1].filename = str(uuid.uuid4()) + '.' + content_type[1] file_id = self.request.storage.save(file_[0][1]) response = Response(body="{'data':'success'}") response.headers.update({ 'Access-Control-Allow-Origin': '*', }) return response ```
21,107,057
Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid?
2014/01/14
[ "https://Stackoverflow.com/questions/21107057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813758/" ]
I've solved the problem using `set_request_factory`: ``` from pyramid.request import Request from pyramid.request import Response def request_factory(environ): request = Request(environ) if request.is_xhr: request.response = Response() request.response.headerlist = [] request.response.headerlist.extend( ( ('Access-Control-Allow-Origin', '*'), ('Content-Type', 'application/json') ) ) return request config.set_request_factory(request_factory) ```
Here is another solution: ``` from pyramid.events import NewResponse, subscriber @subscriber(NewResponse) def add_cors_headers(event): if event.request.is_xhr: event.response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', }) ```
21,107,057
Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid?
2014/01/14
[ "https://Stackoverflow.com/questions/21107057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813758/" ]
I've solved the problem using `set_request_factory`: ``` from pyramid.request import Request from pyramid.request import Response def request_factory(environ): request = Request(environ) if request.is_xhr: request.response = Response() request.response.headerlist = [] request.response.headerlist.extend( ( ('Access-Control-Allow-Origin', '*'), ('Content-Type', 'application/json') ) ) return request config.set_request_factory(request_factory) ```
I fixed this with add some headers to response, by create a response callback: `pyramid.events.NewResponse` **cors.py** ``` from pyramid.security import NO_PERMISSION_REQUIRED def includeme(config): config.add_directive( 'add_cors_preflight_handler', add_cors_preflight_handler) config.add_route_predicate('cors_preflight', CorsPreflightPredicate) config.add_subscriber(add_cors_to_response, 'pyramid.events.NewResponse') class CorsPreflightPredicate(object): def __init__(self, val, config): self.val = val def text(self): return 'cors_preflight = %s' % bool(self.val) phash = text def __call__(self, context, request): if not self.val: return False return ( request.method == 'OPTIONS' and 'HTTP_ORIGIN' in request.headers.environ and 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.headers.environ ) def add_cors_preflight_handler(config): config.add_route( 'cors-options-preflight', '/{catch_all:.*}', cors_preflight=True, ) config.add_view( cors_options_view, route_name='cors-options-preflight', permission=NO_PERMISSION_REQUIRED, ) def add_cors_to_response(event): request = event.request response = event.response if 'HTTP_ORIGIN' in request.headers.environ: response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Content-Type,Date,Content-Length,Authorization,X-Request-ID', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Accept-Language, Authorization ,X-Request-ID', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) def cors_options_view(context, request): response = request.response if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.headers.environ: response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Content-Type,Date,Content-Length,Authorization,X-Request-ID', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Accept-Language, Authorization ,X-Request-ID', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) else: response.headers['HTTP_ACCESS_CONTROL_ALLOW_HEADERS'] = ( 'Origin,Content-Type,Accept,Accept-Language,Authorization,X-Request-ID') return response ``` At the end add this two line on your own Configurator object : ``` # cors config.include('FileManager.classes.cors') # make sure to add this before other routes to intercept OPTIONS config.add_cors_preflight_handler() ```
21,107,057
Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid?
2014/01/14
[ "https://Stackoverflow.com/questions/21107057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813758/" ]
There are several ways to do this: 1) a custom request factory like drnextgis showed, a NewRequest event handler, or a tween. A tween is almost certainly not the right way to do this, so I won't show that. Here is the event handler version: ``` def add_cors_headers_response_callback(event): def cors_headers(request, response): response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Authorization', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) event.request.add_response_callback(cors_headers) from pyramid.events import NewRequest config.add_subscriber(add_cors_headers_response_callback, NewRequest) ```
I could send file with Ajax from a server to another server : ``` import uuid from pyramid.view import view_config from pyramid.response import Response class FManager: def __init__(self, request): self.request = request @view_config(route_name='f_manager', request_method='POST', renderer='json') def post(self): file_ = self.request.POST.items() content_type = str(file_[0][1].type).split('/') file_[0][1].filename = str(uuid.uuid4()) + '.' + content_type[1] file_id = self.request.storage.save(file_[0][1]) response = Response(body="{'data':'success'}") response.headers.update({ 'Access-Control-Allow-Origin': '*', }) return response ```
21,107,057
Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid?
2014/01/14
[ "https://Stackoverflow.com/questions/21107057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813758/" ]
There are several ways to do this: 1) a custom request factory like drnextgis showed, a NewRequest event handler, or a tween. A tween is almost certainly not the right way to do this, so I won't show that. Here is the event handler version: ``` def add_cors_headers_response_callback(event): def cors_headers(request, response): response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Authorization', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) event.request.add_response_callback(cors_headers) from pyramid.events import NewRequest config.add_subscriber(add_cors_headers_response_callback, NewRequest) ```
Here is another solution: ``` from pyramid.events import NewResponse, subscriber @subscriber(NewResponse) def add_cors_headers(event): if event.request.is_xhr: event.response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', }) ```
21,107,057
Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid?
2014/01/14
[ "https://Stackoverflow.com/questions/21107057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813758/" ]
There are several ways to do this: 1) a custom request factory like drnextgis showed, a NewRequest event handler, or a tween. A tween is almost certainly not the right way to do this, so I won't show that. Here is the event handler version: ``` def add_cors_headers_response_callback(event): def cors_headers(request, response): response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Authorization', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) event.request.add_response_callback(cors_headers) from pyramid.events import NewRequest config.add_subscriber(add_cors_headers_response_callback, NewRequest) ```
I fixed this with add some headers to response, by create a response callback: `pyramid.events.NewResponse` **cors.py** ``` from pyramid.security import NO_PERMISSION_REQUIRED def includeme(config): config.add_directive( 'add_cors_preflight_handler', add_cors_preflight_handler) config.add_route_predicate('cors_preflight', CorsPreflightPredicate) config.add_subscriber(add_cors_to_response, 'pyramid.events.NewResponse') class CorsPreflightPredicate(object): def __init__(self, val, config): self.val = val def text(self): return 'cors_preflight = %s' % bool(self.val) phash = text def __call__(self, context, request): if not self.val: return False return ( request.method == 'OPTIONS' and 'HTTP_ORIGIN' in request.headers.environ and 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.headers.environ ) def add_cors_preflight_handler(config): config.add_route( 'cors-options-preflight', '/{catch_all:.*}', cors_preflight=True, ) config.add_view( cors_options_view, route_name='cors-options-preflight', permission=NO_PERMISSION_REQUIRED, ) def add_cors_to_response(event): request = event.request response = event.response if 'HTTP_ORIGIN' in request.headers.environ: response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Content-Type,Date,Content-Length,Authorization,X-Request-ID', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Accept-Language, Authorization ,X-Request-ID', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) def cors_options_view(context, request): response = request.response if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.headers.environ: response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Content-Type,Date,Content-Length,Authorization,X-Request-ID', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Accept-Language, Authorization ,X-Request-ID', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) else: response.headers['HTTP_ACCESS_CONTROL_ALLOW_HEADERS'] = ( 'Origin,Content-Type,Accept,Accept-Language,Authorization,X-Request-ID') return response ``` At the end add this two line on your own Configurator object : ``` # cors config.include('FileManager.classes.cors') # make sure to add this before other routes to intercept OPTIONS config.add_cors_preflight_handler() ```
21,107,057
Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid?
2014/01/14
[ "https://Stackoverflow.com/questions/21107057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813758/" ]
I fixed this with add some headers to response, by create a response callback: `pyramid.events.NewResponse` **cors.py** ``` from pyramid.security import NO_PERMISSION_REQUIRED def includeme(config): config.add_directive( 'add_cors_preflight_handler', add_cors_preflight_handler) config.add_route_predicate('cors_preflight', CorsPreflightPredicate) config.add_subscriber(add_cors_to_response, 'pyramid.events.NewResponse') class CorsPreflightPredicate(object): def __init__(self, val, config): self.val = val def text(self): return 'cors_preflight = %s' % bool(self.val) phash = text def __call__(self, context, request): if not self.val: return False return ( request.method == 'OPTIONS' and 'HTTP_ORIGIN' in request.headers.environ and 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.headers.environ ) def add_cors_preflight_handler(config): config.add_route( 'cors-options-preflight', '/{catch_all:.*}', cors_preflight=True, ) config.add_view( cors_options_view, route_name='cors-options-preflight', permission=NO_PERMISSION_REQUIRED, ) def add_cors_to_response(event): request = event.request response = event.response if 'HTTP_ORIGIN' in request.headers.environ: response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Content-Type,Date,Content-Length,Authorization,X-Request-ID', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Accept-Language, Authorization ,X-Request-ID', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) def cors_options_view(context, request): response = request.response if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.headers.environ: response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Content-Type,Date,Content-Length,Authorization,X-Request-ID', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Accept-Language, Authorization ,X-Request-ID', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) else: response.headers['HTTP_ACCESS_CONTROL_ALLOW_HEADERS'] = ( 'Origin,Content-Type,Accept,Accept-Language,Authorization,X-Request-ID') return response ``` At the end add this two line on your own Configurator object : ``` # cors config.include('FileManager.classes.cors') # make sure to add this before other routes to intercept OPTIONS config.add_cors_preflight_handler() ```
I could send file with Ajax from a server to another server : ``` import uuid from pyramid.view import view_config from pyramid.response import Response class FManager: def __init__(self, request): self.request = request @view_config(route_name='f_manager', request_method='POST', renderer='json') def post(self): file_ = self.request.POST.items() content_type = str(file_[0][1].type).split('/') file_[0][1].filename = str(uuid.uuid4()) + '.' + content_type[1] file_id = self.request.storage.save(file_[0][1]) response = Response(body="{'data':'success'}") response.headers.update({ 'Access-Control-Allow-Origin': '*', }) return response ```
21,107,057
Is it possible automatically add `Access-Control-Allow-Origin` header to all responses which was initiated by ajax request (with header `X-Requested-With`) in Pyramid?
2014/01/14
[ "https://Stackoverflow.com/questions/21107057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813758/" ]
I fixed this with add some headers to response, by create a response callback: `pyramid.events.NewResponse` **cors.py** ``` from pyramid.security import NO_PERMISSION_REQUIRED def includeme(config): config.add_directive( 'add_cors_preflight_handler', add_cors_preflight_handler) config.add_route_predicate('cors_preflight', CorsPreflightPredicate) config.add_subscriber(add_cors_to_response, 'pyramid.events.NewResponse') class CorsPreflightPredicate(object): def __init__(self, val, config): self.val = val def text(self): return 'cors_preflight = %s' % bool(self.val) phash = text def __call__(self, context, request): if not self.val: return False return ( request.method == 'OPTIONS' and 'HTTP_ORIGIN' in request.headers.environ and 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.headers.environ ) def add_cors_preflight_handler(config): config.add_route( 'cors-options-preflight', '/{catch_all:.*}', cors_preflight=True, ) config.add_view( cors_options_view, route_name='cors-options-preflight', permission=NO_PERMISSION_REQUIRED, ) def add_cors_to_response(event): request = event.request response = event.response if 'HTTP_ORIGIN' in request.headers.environ: response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Content-Type,Date,Content-Length,Authorization,X-Request-ID', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Accept-Language, Authorization ,X-Request-ID', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) def cors_options_view(context, request): response = request.response if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.headers.environ: response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Expose-Headers': 'Content-Type,Date,Content-Length,Authorization,X-Request-ID', 'Access-Control-Allow-Methods': 'POST,GET,DELETE,PUT,OPTIONS', 'Access-Control-Allow-Headers': 'Origin, Content-Type, Accept, Accept-Language, Authorization ,X-Request-ID', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '1728000', }) else: response.headers['HTTP_ACCESS_CONTROL_ALLOW_HEADERS'] = ( 'Origin,Content-Type,Accept,Accept-Language,Authorization,X-Request-ID') return response ``` At the end add this two line on your own Configurator object : ``` # cors config.include('FileManager.classes.cors') # make sure to add this before other routes to intercept OPTIONS config.add_cors_preflight_handler() ```
Here is another solution: ``` from pyramid.events import NewResponse, subscriber @subscriber(NewResponse) def add_cors_headers(event): if event.request.is_xhr: event.response.headers.update({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', }) ```
811,624
I saw this definition in one of the computer science book but I am unable to recall the theorem name. Can someone please provide the reference? $$\lim\_{n \to \infty} \frac{f(n)}{g(n)} = c > 0$$ means there is some $n\_{0}$ beyond which the ratio is always between $\frac{1}{2}c$ and $2c$.
2014/05/27
[ "https://math.stackexchange.com/questions/811624", "https://math.stackexchange.com", "https://math.stackexchange.com/users/20411/" ]
Since $\|A\| = 1$, using the Neumann series we can indeed invert $A - \lambda I$ when $|\lambda|>1$. For $|\lambda|<1$, the sequence $x\_n = \lambda^n$ lies in the kernel of $A-\lambda I$ and it is not invertible. Then the conclusion follows by recalling that the spectrum of a bounded operator is always closed.
First note that $A$ is an isometry, so $\|A\| = 1$. Hence $\sigma(A)$ lies in the closed unit ball of the complex plane $C$. Define the adjoint of $A : X \rightarrow Y$ to be $A^\* : Y^\* \rightarrow X^\*$ such that $A^\*(\alpha)(x) = \alpha(Ax)$ where $\alpha \in Y^\*$ and $x \in X$ (here $X,Y$ are Banach spaces). Then $\sigma(A) = \sigma(A^\*)$. Then easy computation should give you the adjoint of left shift is the right shift (D'oh!). It is very easy to see that the spectrum of the right shift is all the closed unit disc by considering $x = (1,\lambda, \lambda^2, \lambda^3,...)$.
811,624
I saw this definition in one of the computer science book but I am unable to recall the theorem name. Can someone please provide the reference? $$\lim\_{n \to \infty} \frac{f(n)}{g(n)} = c > 0$$ means there is some $n\_{0}$ beyond which the ratio is always between $\frac{1}{2}c$ and $2c$.
2014/05/27
[ "https://math.stackexchange.com/questions/811624", "https://math.stackexchange.com", "https://math.stackexchange.com/users/20411/" ]
Notice that $\|Ax\| \le \|x\|$. So $\sigma(A)$ is contained in the closed unit disk $D^{c}$. To find the resolvent $(A-\lambda I)^{-1}$, try to solve $(A-\lambda I)x = y$ for $x$, and see if it can be done. First, see if there are any eigenfunctions $Ax=\lambda x$. If there were such an $x$, then $|\lambda| \le 1$ and $x=(x\_1,x\_2,x\_3,\cdots)$ would satisfy $$ (x\_2-\lambda x\_1,x\_3-\lambda x\_2,x\_4-\lambda x\_3,\cdots)=0,\\ x\_2=\lambda x\_1,\; x\_3=\lambda x\_2,\;x\_4=\lambda x\_3. $$ Assuming $x\_1=1$, there is a solution $(1,\lambda,\lambda^{2},\lambda^{3},\cdots)$. This solution is valid only for $|\lambda| < 1$ because, otherwise, $x \notin l^{2}$. In other words, $\sigma\_{P}(A)=\{ \lambda \in \mathbb{C} : |\lambda| < 1\}$ is the open unit disk. And $\sigma(A)=\{ \lambda \in\mathbb{C} : |\lambda|\le 1\}$ because $\sigma(A)$ is closed, contains the open unit disk, and is contained in the closed unit disk. The adjoint of $A$ is the shift $B(x\_1,x\_2,x\_3,\cdots)=(0,x\_1,x\_2,x\_3,\cdots)$. Notice that $\|Bx\|=\|x\|$ for all $x \in l^{2}$. $B$ has no point spectrum because $Bx=\lambda x$ implies $(x\_1,x\_2-\lambda x\_1,x\_3-\lambda x\_2,\dots)=0$, which forces $x\_1=0, x\_2=\lambda x\_1=0,etc.$. So the range of $(A-\lambda I)$ is dense for all $\lambda$, which puts the unit circle $\{ \lambda \in\mathbb{C} : |\lambda|=1\}$ in the continuous spectrum of $A$. $A$ has no residual spectrum.
Since $\|A\| = 1$, using the Neumann series we can indeed invert $A - \lambda I$ when $|\lambda|>1$. For $|\lambda|<1$, the sequence $x\_n = \lambda^n$ lies in the kernel of $A-\lambda I$ and it is not invertible. Then the conclusion follows by recalling that the spectrum of a bounded operator is always closed.
811,624
I saw this definition in one of the computer science book but I am unable to recall the theorem name. Can someone please provide the reference? $$\lim\_{n \to \infty} \frac{f(n)}{g(n)} = c > 0$$ means there is some $n\_{0}$ beyond which the ratio is always between $\frac{1}{2}c$ and $2c$.
2014/05/27
[ "https://math.stackexchange.com/questions/811624", "https://math.stackexchange.com", "https://math.stackexchange.com/users/20411/" ]
Notice that $\|Ax\| \le \|x\|$. So $\sigma(A)$ is contained in the closed unit disk $D^{c}$. To find the resolvent $(A-\lambda I)^{-1}$, try to solve $(A-\lambda I)x = y$ for $x$, and see if it can be done. First, see if there are any eigenfunctions $Ax=\lambda x$. If there were such an $x$, then $|\lambda| \le 1$ and $x=(x\_1,x\_2,x\_3,\cdots)$ would satisfy $$ (x\_2-\lambda x\_1,x\_3-\lambda x\_2,x\_4-\lambda x\_3,\cdots)=0,\\ x\_2=\lambda x\_1,\; x\_3=\lambda x\_2,\;x\_4=\lambda x\_3. $$ Assuming $x\_1=1$, there is a solution $(1,\lambda,\lambda^{2},\lambda^{3},\cdots)$. This solution is valid only for $|\lambda| < 1$ because, otherwise, $x \notin l^{2}$. In other words, $\sigma\_{P}(A)=\{ \lambda \in \mathbb{C} : |\lambda| < 1\}$ is the open unit disk. And $\sigma(A)=\{ \lambda \in\mathbb{C} : |\lambda|\le 1\}$ because $\sigma(A)$ is closed, contains the open unit disk, and is contained in the closed unit disk. The adjoint of $A$ is the shift $B(x\_1,x\_2,x\_3,\cdots)=(0,x\_1,x\_2,x\_3,\cdots)$. Notice that $\|Bx\|=\|x\|$ for all $x \in l^{2}$. $B$ has no point spectrum because $Bx=\lambda x$ implies $(x\_1,x\_2-\lambda x\_1,x\_3-\lambda x\_2,\dots)=0$, which forces $x\_1=0, x\_2=\lambda x\_1=0,etc.$. So the range of $(A-\lambda I)$ is dense for all $\lambda$, which puts the unit circle $\{ \lambda \in\mathbb{C} : |\lambda|=1\}$ in the continuous spectrum of $A$. $A$ has no residual spectrum.
First note that $A$ is an isometry, so $\|A\| = 1$. Hence $\sigma(A)$ lies in the closed unit ball of the complex plane $C$. Define the adjoint of $A : X \rightarrow Y$ to be $A^\* : Y^\* \rightarrow X^\*$ such that $A^\*(\alpha)(x) = \alpha(Ax)$ where $\alpha \in Y^\*$ and $x \in X$ (here $X,Y$ are Banach spaces). Then $\sigma(A) = \sigma(A^\*)$. Then easy computation should give you the adjoint of left shift is the right shift (D'oh!). It is very easy to see that the spectrum of the right shift is all the closed unit disc by considering $x = (1,\lambda, \lambda^2, \lambda^3,...)$.
44,702,855
We are trying to run rbenv on El-Capitan 10.11.6. When we try to run rbenv command in the terminal we got the following error message: ``` command not found ``` We googled how to solve that issue and one possible solution is to add the "rbenv" to the system PATH, we followed the steps stated in [this link](http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.WUvUPUX5yL9). When we run the "$PATH" to check whether or not the rbenv path was added properly into the system PATH, we got the the same result: ``` command not found ``` The result of "$PATH" command is: ``` qwe-Mac-mini:~ amrbakri$ rbenv -bash: rbenv: command not found qwe-Mac-mini:~ asd$ echo $PATH /Users/asd/.rbenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/MacGPG2/bin ``` Can you please tell me how to add the path of rbenv properly? And what did I do wrong in the previous steps so that I can fix it.
2017/06/22
[ "https://Stackoverflow.com/questions/44702855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3732958/" ]
Assuming your source is stored in `exampleScriptFile`: ```js // polyfill const fs = { readFileSync() { return 'console.log(`${EXAMPLE_3}`);'; } }; // CONSTANTS const EXAMPLE_1 = 'EXAMPLE_1'; const EXAMPLE_2 = 'EXAMPLE_2'; const EXAMPLE_3 = 'EXAMPLE_3'; const exampleScriptFile = fs.readFileSync('./exampleScriptFile.js'); // What I want is to just use a JS file because it is neater. eval(exampleScriptFile); ``` ### Update Perhaps I wasn't clear. The `./exampleScriptFile.js` should be: ``` console.log(`${EXAMPLE_3}`); ```
While what you're describing can be done with `eval` as @PatrickRoberts demonstrates, that doesn't extend to `executeJavaScript`. The former runs in the caller's context, while the latter triggers an IPC call to another process with the contents of the code. Presumably this process doesn't have any information on the caller's context, and therefore, the template strings can't be populated with variables defined in this context. ### Relevant snippets from [electron/lib/browsers/api/web-contents.js](https://github.com/electron/electron/blob/3abeb6e2bc5a300d9cc787b893584922f1e39e06/lib/browser/api/web-contents.js#L148): ``` WebContents.prototype.send = function (channel, ...args) { // ... return this._send(false, channel, args) } // ... WebContents.prototype.executeJavaScript = function (code, hasUserGesture, callback) { // ... return asyncWebFrameMethods.call(this, requestId, 'executeJavaScript', // ... } // ... const asyncWebFrameMethods = function (requestId, method, callback, ...args) { return new Promise((resolve, reject) => { this.send('ELECTRON_INTERNAL_RENDERER_ASYNC_WEB_FRAME_METHOD', requestId, method, args) // ... }) } ``` ### Relevant snippets from [electron/atom/browser/api/atom\_api\_web\_contents.cc](https://github.com/electron/electron/blob/3abeb6e2bc5a300d9cc787b893584922f1e39e06/atom/browser/api/atom_api_web_contents.cc) ``` //... void WebContents::BuildPrototype(v8::Isolate* isolate, v8::Local<v8::FunctionTemplate> prototype) { prototype->SetClassName(mate::StringToV8(isolate, "WebContents")); mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) // ... .SetMethod("_send", &WebContents::SendIPCMessage) // ... } ```
422,828
I need to make the word "Table" within paragraph clickable. I have tried this [When referencing a figure, make text and figure name clickable](https://tex.stackexchange.com/questions/230828/when-referencing-a-figure-make-text-and-figure-name-clickable). But I got "???" instead. [![enter image description here](https://i.stack.imgur.com/9Ia1y.jpg)](https://i.stack.imgur.com/9Ia1y.jpg)
2018/03/23
[ "https://tex.stackexchange.com/questions/422828", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/156895/" ]
Automatic way, see the `\autoref` feature of `hyperref`: ``` from the \autoref{tab:first} ``` Manually with `\hyperref`: ``` from the \hyperref[tab:first]{Table \ref*{tab:first}} ```
Thanks to @Heiko and @Christian I got what I want. ``` \documentclass{article} \usepackage[colorlinks]{hyperref} \usepackage[nameinlink,noabbrev]{cleveref} \usepackage{array} \usepackage{multirow} \usepackage{makecell} \begin{document} here text here text here text here text here \autoref{tab:Table1} text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text .... Similarly to the concluded idea from the \cref{tab:Table1} Table 1 .... here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text here text \begin{table}[h] \centering \begin{tabular}{lll} \hline \multirow{4}{*}{aaa} & \multicolumn{1}{l}{111} & \multicolumn{1}{l}{222} \\ \cline{2-3} & \multicolumn{1}{l}{333} & \multicolumn{1}{l}{444} \\ \cline{2-3} & \multicolumn{1}{l}{555} & \multicolumn{1}{l}{666} \\ \cline{2-3} & \multicolumn{1}{l}{777} & \multicolumn{1}{l}{888} \\ \hline \ttfamily aaa & \ttfamily bbb & \ttfamily ccc \\ \hline \end{tabular} \caption{Table 1} \label{tab:Table1} \end{table} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/XTw2S.jpg)](https://i.stack.imgur.com/XTw2S.jpg)
1,032,510
This is an exercise in *Naive Set Theory* by P. R. Halmos. > > If $\text{card }A=a$, what is the cardinal number of the set of all > one-to-one mappings of $A$ onto itself? What is the cardinal number of > the set of all countably infinite subsets of $A$? > > > It is easy to see that, for the first question, the cardinal number is less than or equal to $a^a$, and for any finite set the cardinal number is $a!$; for the second one, the cardinal number is less than or equal to $2^a$, and for any finite set the cardinal number is $0$. I guess for infinite sets the equality holds in both questions. Is that correct? Can anyone give some suggestions on what to do next? **Edit**: As is suggested by Arthur, the second cardinal number is at most $a^\omega$.
2014/11/21
[ "https://math.stackexchange.com/questions/1032510", "https://math.stackexchange.com", "https://math.stackexchange.com/users/119490/" ]
No. Counterexample: $c=1$ and $f(x)=k>0$ for all $x$.
Consider $f(x)=\frac{x^{\frac{1}{c}-1}}{c}$.
1,032,510
This is an exercise in *Naive Set Theory* by P. R. Halmos. > > If $\text{card }A=a$, what is the cardinal number of the set of all > one-to-one mappings of $A$ onto itself? What is the cardinal number of > the set of all countably infinite subsets of $A$? > > > It is easy to see that, for the first question, the cardinal number is less than or equal to $a^a$, and for any finite set the cardinal number is $a!$; for the second one, the cardinal number is less than or equal to $2^a$, and for any finite set the cardinal number is $0$. I guess for infinite sets the equality holds in both questions. Is that correct? Can anyone give some suggestions on what to do next? **Edit**: As is suggested by Arthur, the second cardinal number is at most $a^\omega$.
2014/11/21
[ "https://math.stackexchange.com/questions/1032510", "https://math.stackexchange.com", "https://math.stackexchange.com/users/119490/" ]
No. Counterexample: $c=1$ and $f(x)=k>0$ for all $x$.
@Eric, If your question is only : is it true that $f=0$ almost everywhere, you have get the counterexample. But if your question is what can we said about $f,$ follow me: From $\frac{1}{x}\int\_{0}^{x}f(t)dt=cf(x),$ for all $x>0,$ we get $$ \int\_{0}^{x}f(t)dt=cxf(x),\ x>0. $$ Assume that $f$ is continuous. By the Fundamental Theorem the left hand side is a differentiable function, so the right on should be too, that is $f$ is necessary differentiable and then \begin{eqnarray\*} \frac{d}{dx}\int\_{0}^{x}f(t)dt &=&cf(x)+cxf^{\prime }(x),\ for\ x>0. \\ f(x) &=&cf(x)+cxf^{\prime }(x),\ for\ x>0 \\ (1-c)f(x) &=&cxf^{\prime }(x),\ \ \ \ \ for\ x>0. \end{eqnarray\*} Discussion: If $c=1$ then $f^{\prime }(x)=0,$ for all $x>0,$ so $f$ is (any) constant including $f(x)=0$ everywhere. If $c=0$ then $f(x)=0,$ for all $x>0.$ If $c\neq 0,1.$ Assume there exists an interval $I$ where $f(x)>0.$ So on that interval one has $$ \frac{f^{\prime }(x)}{f(x)}=\frac{(1-c)}{c}\frac{1}{x},\ for\ all\ x\in I. $$ then% $$ \ln \left\vert f(x)\right\vert =\frac{1-c}{c}\ln x+d,\ for\ all\ x\in I\subset \left( 0,+\infty \right) $$ and so, let $(c-1)/c=k$ $$ \left\vert f(x)\right\vert =e^{k\ln x+d}=\alpha x^{k},\ for\ all\ x\in I,\ with\ \alpha >0. $$ But in your hypothesis, you said $f\geq 0,$ so $$ f(x)=\alpha x^{k},\ for\ all\ x\in I,\ with\ \alpha >0. $$ Take $I$ be the maximal interval possible, so either it is $\left( 0,+\infty \right) ,$ or $I\_{\max }=\left( a,b\right) $ for some $b>0$ and some $a\geq 0.$ From continuity arguments, it follows that $f(b)=0.$ So from $(1-c)f(x)=cxf^{\prime }(x),\ for\ x>0. $ it follows that $f^{\prime }(b)=0.$ But $f^{\prime }(x)=\alpha kx^{k-1}$ for all $x\in \left( a,b\right) $ then $\lim\_{x\rightarrow b^{-}}f^{\prime }(x)=\alpha kb^{k-1}=0$ implies $b=0$ which is impossible since $b>0.$ It follows that $I\_{\max }$ is unbounded from the right. We can show the same way that $a=0$ necessarily and then $I\_{\max }=\left( 0,+\infty \right) .$ It follows that either $f(x)=\alpha x^{k},\ for\ all\ x\in (0,+\infty ),\ with\ \alpha >0.$ or $f(x)=0$ for all $x\in (0,+\infty ).$ Conclusion: If $c\neq 0,1$ then either $f(x)=0$ for all $x>0$ or $f(x)=f(1) x^{k}$ for all $x>0$ with $k=\frac{c-1}{c}.$
56,565,986
I have a dataframe with full of ip addresses. I have a list of ip address that I want to remove from my dataframe. I wanted to have a new dataframe "filtered\_list" after all the ip addresses are removed according to "lista". I saw an example at [How to use NOT IN clause in filter condition in spark](https://stackoverflow.com/questions/44899392/how-to-use-not-in-clause-in-filter-condition-in-spark). But I can't seem to get it to work even before doing a "not" on the filter Please help. **Example:** ``` var df = Seq("119.73.148.227", "42.61.124.218", "42.61.66.174", "118.201.94.2","118.201.149.146", "119.73.234.82", "42.61.110.239", "58.185.72.118", "115.42.231.178").toDF("ipAddress") var lista = List("119.73.148.227", "118.201.94.2") var filtered_list = df.filter(col("ipAddress").isin(lista)) ``` I am encountering the following error message: ``` java.lang.RuntimeException: Unsupported literal type class scala.collection.immutable.$colon$colon List(119.73.148.227, 118.201.94.2) at org.apache.spark.sql.catalyst.expressions.Literal$.apply(literals.scala:77) at org.apache.spark.sql.catalyst.expressions.Literal$$anonfun$create$2.apply(literals.scala:163) at org.apache.spark.sql.catalyst.expressions.Literal$$anonfun$create$2.apply(literals.scala:163) at scala.util.Try.getOrElse(Try.scala:79) at org.apache.spark.sql.catalyst.expressions.Literal$.create(literals.scala:162) at org.apache.spark.sql.functions$.typedLit(functions.scala:113) at org.apache.spark.sql.functions$.lit(functions.scala:96) at org.apache.spark.sql.Column$$anonfun$isin$1.apply(Column.scala:787) at org.apache.spark.sql.Column$$anonfun$isin$1.apply(Column.scala:787) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234) at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33) at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:35) at scala.collection.TraversableLike$class.map(TraversableLike.scala:234) at scala.collection.AbstractTraversable.map(Traversable.scala:104) at org.apache.spark.sql.Column.isin(Column.scala:787) ... 52 elided ```
2019/06/12
[ "https://Stackoverflow.com/questions/56565986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9272452/" ]
You could use the except method on dataframe. ``` var df = Seq("119.73.148.227", "42.61.124.218", "42.61.66.174", "118.201.94.2","118.201.149.146", "119.73.234.82", "42.61.110.239", "58.185.72.118", "115.42.231.178").toDF("ipAddress") var lista = Seq("119.73.148.227", "118.201.94.2").toDF("ipAddress") var onlyWantedIp = df.except(lista) ```
`isin` takes varargs, not `List`. You'd have to spread your list into seperate elements using `:_*` ascription: ``` var filtered_list = df.filter(col("ipAddress").isin(lista: _*)) ```
316,791
I am getting the following error when I try to connect to a Minecraft server: [![Connection refused: no further information](https://i.stack.imgur.com/31C7S.jpg)](https://i.stack.imgur.com/31C7S.jpg) This is all servers, not just one. The error says: > > io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: > > > Version 1.12 > > > I've tried: * Restarting Minecraft * Restarting Computer * Uninstalling and Reinstalling Mincraft * Uninstalling and Reinstalling Java * Altering Firewall * Restarting Internet * I've messed with my port, made a second windows account, reset netsh winsock * Checked hosts * Made a new WINDOWS account The overlay in the bottom right is Geforce's Overlay for game capturing. I don't have any mods installed. A Mojang support ticket wouldn't help. Im desperate.
2017/08/23
[ "https://gaming.stackexchange.com/questions/316791", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/195593/" ]
I have the same error on my local network, it looks like a firewall issue on the host/server side. For me, to troubleshoot I used [nmap](https://nmap.org/). The LAN game showed up in multiplayer as 10.0.0.21:49299. nmap reported that port from that IP as closed/filtered; i.e. a firewall issue. To confirm it is a firewall issue, [turn off the firewall](https://www.howtogeek.com/242375/how-to-troubleshoot-minecraft-lan-game-problems/) (momentarily). See if you're able to connect while the firewall is disabled.
It looks like it has something to do with Firewall **not** allowing traffic to the 1.12.jar file located in C:\Users\user\AppData\Roaming.minecraft\versions(version). I assume that when you say you have "Altered the Firewall" you mean that you *only* allowed connections to the Java.exes but **NOT** the actual 1.12.jar file itself. > > **Important:** When creating the rule it is important to make sure these configurations are set: Set the program path to the 1.12.jar file, and make sure to > check "Allow the Connection" when configuring the rule. > > >
20,848,810
I've read many articles and posts about executing NAnt scripts using TFS build, none of which have satisfied my needs. I have a NAnt script that has been developed over the years to automatically build, test and deploy our websites to an internal staging and external demo environments. Usually, the team has been so small that builds have been a manual process. The intention had always been to integrate this script into a CI environment. Recently, we switched our source control to TFS 2012 with the aim of using TFS build with our existing NAnt script. From what I can see so far, it is possible to execute a NAnt script with TFS build, but it is not possible to not specify a .sln file for TFS build to build first when creating a new build definition. Ideally, I want NAnt to control the entire build/test/deploy process and for TFS Build to just butt out and just utilise the Checkin triggers TFS provides to trigger the NAnt build. I've played with the idea of writing my own TFS checkin interceptor. Has anyone else solved this problem already? Many thanks Could anyone answering please stick the specific question being asked and not deviate by suggesting alternate (paid for or not) CI tools such as CCNet or TeamCity. Cheers
2013/12/30
[ "https://Stackoverflow.com/questions/20848810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767428/" ]
Here is how you can do it: 1) Download Nant.exe from <http://sourceforge.net/projects/nant/files/> and check-in the bin directory which has Nant.exe. 2) Create a msbuild file (say msbuild.proj) with following code(change Path) and check-in the file. ``` <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="RunNant"> <Exec Command="bin\nant.exe; -buildfile:master.build build"/> </Target> </Project> ``` 3) Go to Process tab in your build definition and then go to "Items to Build" --> "Projects to Build" --> Select(icon on the right) --> Add --> Change "Items of type" to "MSBuild project files" and then select the .proj file you checked-in. ![enter image description here](https://i.stack.imgur.com/weDyk.png) 4) Run your build and it should work. See below log that shows that it ran the Nant build file. ``` Build started 12/31/2013 4:55:20 AM. Project "C:\a\src\F\Test Projects\TestProject\msbuild.proj" on node 1 (default targets). RunNant: bin\nant.exe; -buildfile:master.build build NAnt 0.92 (Build 0.92.4543.0; release; 6/9/2012) Copyright (C) 2001-2012 Gerry Shaw http://nant.sourceforge.net Buildfile: file:///C:/a/src/F/Test Projects/TestProject/master.build Target framework: Microsoft .NET Framework 4.0 Target(s) specified: ; build [solution] Starting solution build. ```
We have a similar problem. For one of our projects we just want to run a DOS command for the build. What I did was create a custom build template that just runs a DOS command. The template has Arguments for the App to Run, App Arguments, and App Working Directory. Here is what the whole template looks like in the designer. ![enter image description here](https://i.stack.imgur.com/ySlSg.png) Here is a list of our arguments ![enter image description here](https://i.stack.imgur.com/CxTNB.png) I have not used NAnt before but I am guessing you can run it from a DOS command. You should be able to pass in your .sln as one of the parameters to your DOS command.
36,294,466
UDF: ``` bigquery.defineFunction( 'newdate', // Name of the function exported to SQL [], // Names of input columns [ {name: 'date', type: 'timestamp'} , {name: 'datestr', type: 'string'} ], function newDate(row, emit) { var date = new Date(); // current date and time emit({ date: date , datestr: date + '' }); } ); ``` SQL: ``` SELECT date, datestr FROM (newDate(SELECT "ignored" AS inputA)) ``` Output: ``` 1459282876835809 Tue Mar 29 2016 13:21:16 GMT-0700 (PDT) ```
2016/03/29
[ "https://Stackoverflow.com/questions/36294466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2259571/" ]
That's an unfortunate oversight on our part. Many Google servers run using Pacific time (semi-jokingly referred to as "Google standard time"). When launching BigQuery, we tried to standardize on UTC instead, but we missed this case. We may try to find an opportunity to fix it, but unfortunately we risk breaking existing users if we do so, so no promises. Thanks for the heads up!
Don't know rationale for running in Pacific time zone, but you just ignore the system time zone, and use UTC time in your code. E.g. use `datestr: date.toUTCString()` instead of `datestr: date + ''`.
62,753,397
I write button.xml and qweb in **manifest**.py but it not worked. button.xml (static/src/xml/button.xml) ``` <?xml version="1.0" encoding="UTF-8"?> <templates> <t t-extend="ListView.buttons"> <t t-jquery="button.o_list_button_add" t-operation="after"> <button name="xxx" type="button" t-if='widget.modelName == "billing.info.functions"' class="btn btn-sm btn-default o_import_button o_import_import">Upload </button> </t> </t> </templates> ``` **manifest**.py ``` 'qweb': [ "static/src/xml/button.xml" ], ```
2020/07/06
[ "https://Stackoverflow.com/questions/62753397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13876116/" ]
The first thing I notice is that you are iterating through `i in range(0, int(pages))`, however, the pages only start on line 1 (line 0 consists of n & q). So your for loop should like more like (you also want to do +1 because you want to count the last page, otherwise python only goes 'uptil but not including'): ```py for i in range (1, pages + 1): words = int(file.readline().strip()) ``` Here, we are putting the .strip() function so that we don't get an error while converting this to an int. By default, text files have `\n` (enter characters) at the end of each line and python doesn't understand the meaning of `int("5\n")`. The strip() function helps get rid of the enter character and any trailing 'whitespaces'. Now, you would want to store the number of words per line somewhere, and for this you can either use a dictionary (<https://www.w3schools.com/python/python_dictionaries.asp>), or a list. List indices start at 0, but the line with the number of words per page starts at 1 and even though you could get away with using lists, dictionaries would be more intuitive. ```py words_per_page = {} ``` You can look at the link I have provided to understand how these work. We can then add the words to the dictionary: ```py for i in range (1, int(pages) + 1): number_of_words = int(file.readline().strip()) words_per_page[i] = number_of_words ``` Then, you can iterate through each line with the questions. Here, we start the for loop at the line just after the line where the number of words per page ends: ```py all_questions = [] for question_index in range(pages + 2, 1 + pages + questions): all_questions.append(file.readline().strip()) ``` From this, you will get 1 dictionary of the page number as the key and words per page as the value and a list with all the questions. Then you could iterate through these and get the number of words in the pages: ```py for page_number in all_questions: no_of_words = words_per_page[int(page_number)] # You can then store this variable somewhere or write to a text file ``` Now, I haven't tested any of this code, but the idea behind everything is the same. If you do get any errors, make sure to leave a comment.
Could you try this? ```py with open("encyin.txt") as f: parts = next(f).split() pages = int(parts[0]) questions = int(parts[1]) counts = [] # capture counts for _ in range(pages): num_pages = int(next(f)) counts.append(num_pages) # answer questions for _ in range(questions): book = int(next(f)) print(counts[book - 1]) ```
69,139,132
I'm using the weightloss dataset: ``` structure(list(id = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), .Label = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"), class = "factor"), diet = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("no", "yes"), class = "factor"), exercises = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("no", "yes" ), class = "factor"), t1 = c(10.43, 11.59, 11.35, 11.12, 9.5, 9.5, 11.12, 12.51, 11.35, 11.12, 11.12, 10.2, 11.12, 9.96, 12.05, 8.11, 12.05, 12.05, 12.28, 10.66, 11.35, 10.2, 10.2, 9.5, 10.2, 12.98, 13.21, 10.2, 11.59, 12.05, 11.59, 12.05, 11.82, 11.12, 12.51, 11.59, 10.43, 11.35, 11.82, 10.2, 13.67, 10.66, 10.2, 12.05, 11.82, 10.43, 12.74, 11.35), t2 = c(13.21, 10.66, 11.12, 9.5, 9.73, 12.74, 12.51, 12.28, 11.59, 10.66, 13.44, 11.35, 12.51, 12.74, 13.67, 14.37, 14.6, 12.98, 12.05, 14.37, 14.6, 11.82, 14.13, 13.21, 12.51, 12.98, 11.12, 9.73, 13.44, 13.67, 12.98, 11.35, 12.05, 15.29, 11.82, 12.05, 12.51, 14.83, 13.9, 13.21, 14.13, 15.06, 12.98, 11.35, 12.51, 14.13, 12.74, 11.35), t3 = c(11.59, 13.21, 11.35, 11.12, 12.28, 10.43, 11.59, 12.74, 9.96, 11.35, 10.66, 11.12, 15.76, 16.68, 17.84, 14.6, 17.84, 17.61, 18.54, 16.91, 15.52, 17.38, 19, 14.13, 14.6, 14.6, 12.05, 15.52, 13.9, 12.74, 13.21, 14.83, 14.6, 10.89, 15.52, 12.98, 14.37, 15.06, 13.44, 14.13, 15.29, 14.6, 15.06, 15.52, 13.9, 14.37, 15.06, 15.06)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -48L)) ``` So far it looks like at least here I can separate the scores: ``` weight <- weightloss summary <- weight %>% get_summary_stats(type = "mean_sd") summary ``` Which gives me this: ``` A tibble: 3 x 4 variable n mean sd <chr> <dbl> <dbl> <dbl> 1 t1 48 11.2 1.09 2 t2 48 12.7 1.42 3 t3 48 14.2 2.26 ``` I'm trying to run a RMANOVA on this, but I would like to get a boxplot for every one of the three groups, all in a single plot. However, I'm not sure how to plot the x and y in this case. I tried using this for the x: ``` trial_type <- c("t1","t2","t3") factor(trial_type) ``` But thats where I'm stuck...I'm not sure how you get the y in this case. The y is clearly the scores from each trial. I tried grouping by this factor to see if that would sort out the scores in some way, but I haven't figured that out either. I'm just not sure how you plot this into ggplot. Any help would be great! I can imagine this is a very useful skill to learn for any data that uses trials.
2021/09/11
[ "https://Stackoverflow.com/questions/69139132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16631565/" ]
``` Icon( Icons.add_circle_outline, color: Colors.white, size: 30, ), ``` You can use flutter built in icon.
try this: ``` Container( width: 24, height: 24, child: OutlinedButton( onPressed: () { print('xxx'); }, child: Icon( Icons.add, color: Colors.grey, ), style: OutlinedButton.styleFrom( padding: EdgeInsets.all(0), primary: Colors.grey, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), side: BorderSide(width: 2, color: Colors.grey), ), ), ), ```
39,559,845
I have the following transaction: ``` typedef enum {READ = 0, WRITE = 1} direction_enum; //Transaction class axi_transaction extends uvm_sequence_item(); bit id = 0; //const bit [31:0] addr; bit [2:0] size = 0'b100;//const direction_enum rw; bit [31:0] transfers [$]; //factory registration `uvm_object_utils_begin(axi_transaction) `uvm_field_int(id, UVM_ALL_ON) `uvm_field_int(addr, UVM_ALL_ON) `uvm_field_int(size, UVM_ALL_ON) `uvm_field_enum(rw, UVM_ALL_ON) `uvm_field_int(transfers, UVM_ALL_ON) `uvm_object_utils_end //constructor function new(string name = "axi_transaction"); super.new(name); endfunction: new endclass: axi_transaction ``` I want to extend the new function, so I can initializes the transaction in the sequence with arguments which initialize some of the transaction members (like addr, transfers) by: ``` ax_trx = axi_transaction::type_id::create(); ``` How to write the constructor of the transaction and how do I initialize the transaction from the sequencer?
2016/09/18
[ "https://Stackoverflow.com/questions/39559845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6465067/" ]
You cannot add arguments to the class constructor when using the UVM factory. In general this is not good OOP programing practice for re-use because if you do add arguments to either the base class or extended class, you have to modify every place where the class gets constructed. A better option is to use the uvm\_config\_db or set the individual fields you need to after constructing the object. ``` ax_trx = axi_transaction::type_id::create(); ax_trx.addr = some_address ax_trx.transfers = '{word1,word2,word3}; ```
You can use uvm\_config\_db class for initialisation. You can set the value using following syntax. And then you can get that value inside the constructor of that class. ``` uvm_config_db#(int)::set(this,“my_subblock_a”,“max_cycles”,max_cycles) uvm_config_db#(int)::get(this,“”, “max_cycles”,max_cycles) ``` For more information of "uvm\_config\_db", you can refer to the following paper. <https://www.synopsys.com/Services/Documents/hierarchical-testbench-configuration-using-uvm.pdf>