qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
293,885
Please note that I asked the same question on [stackoverflow](https://stackoverflow.com/questions/32049022/application-logic-vs-business-logic) but they directed me to ask here. While I am trying to discerne the difference between the application logic and business logic I have found set of articles but unfortunately there is a contradiction between them. [Here](http://encyclopedia2.thefreedictionary.com/application+logic) they say that they are the same but the answer [here](https://stackoverflow.com/questions/1456425/business-and-application-logic) is totally different. For me I understand it in the following way: If we look up for the definition of the `Logic` word in Google we will get > > system or set of principles underlying the arrangements of elements in > a computer or electronic device so as to perform a specified task. > > > So, if the logic is `set of principles underlying the arrangements of elements` then the business logic should be `set of principles underlying the arrangements of the business rules`, in other words it means the rules that should be followed to get a system reflects your business needs. And for me the application logic is `the principles that the application based on`, in other words, how to apply these rules to get a system reflects your business needs, for example should I use MVC or should not I use? should I use SQL or MSSQl?. So please could anybody help me to get rid of confusion about the difference between the application and the business logic.
2015/08/17
['https://softwareengineering.stackexchange.com/questions/293885', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/192185/']
As others have pointed out, these terms do not have one universally accepted meaning. I will describe the definitions I have encountered more often, i.e. in several projects with different companies. The **business logic** defines a normalized, general-purpose model of the business domain for which an application is written, e.g. * Classes like `Customer`, `Order`, `OrderLine`, and associations like `customer-order`, and so on. * General-purpose operations such as `registerCustomer`, `cancelOrder` Very often this class model is mapped to a database model and the mapping is implemented using ORM. The operations are normally performed each in their own transaction and provide the basic API for modifying the database, i.e. the persistent state of the application. The **application logic** is a layer built on top of the business logic and serves to implement specific use cases. Application logic modules may use ad-hoc data representation, e.g. a CustomerSummary class without any association to `Order` if you want to list customers only. Such ad-hoc data representation must be mapped to the underlying normalized representation provided by the business model. For example, `CustomerSummary` can be defined as a view on top of `Customer`. Note that the boundary between the two layers may not be so clearly-defined. E.g. after implementing several use cases one might notice similar data structures in the application logic and decide to unify (normalize) them and move them to the business logic.
Na, they're just different terms for the same thing - the "middle tier" of program code that does the things you want your program to perform. Like many things in software, there are no hard-and-fast terminology for pieces of a system, as there are no single formal definitions for building systems. So sometimes people will call it business logic, others application logic, others will call it program logic, its all much of a muchness. Don't bother trying to define this so rigidly, nearly every system varies in how its built so be glad there's only this minor level of vagueness in terminology!
293,885
Please note that I asked the same question on [stackoverflow](https://stackoverflow.com/questions/32049022/application-logic-vs-business-logic) but they directed me to ask here. While I am trying to discerne the difference between the application logic and business logic I have found set of articles but unfortunately there is a contradiction between them. [Here](http://encyclopedia2.thefreedictionary.com/application+logic) they say that they are the same but the answer [here](https://stackoverflow.com/questions/1456425/business-and-application-logic) is totally different. For me I understand it in the following way: If we look up for the definition of the `Logic` word in Google we will get > > system or set of principles underlying the arrangements of elements in > a computer or electronic device so as to perform a specified task. > > > So, if the logic is `set of principles underlying the arrangements of elements` then the business logic should be `set of principles underlying the arrangements of the business rules`, in other words it means the rules that should be followed to get a system reflects your business needs. And for me the application logic is `the principles that the application based on`, in other words, how to apply these rules to get a system reflects your business needs, for example should I use MVC or should not I use? should I use SQL or MSSQl?. So please could anybody help me to get rid of confusion about the difference between the application and the business logic.
2015/08/17
['https://softwareengineering.stackexchange.com/questions/293885', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/192185/']
Every system or application is going to have its own definitions of what is business logic and what is application logic. It will either be explicit or implicit. In my experience data driven applications (e.g. DBs etc.) tend to have a more formal definition of what the business logic is. The application logic tends to focus on getting information from point A to point B, the business logic centres around what the information is - and the language of the business logic is usually domain specific. Put another way, the application logic is focused on the question "how does it work?", the business logic on "what does it do?" - again, the distinction can be very fuzzy and is more often that not domain specific.
As others have pointed out, these terms do not have one universally accepted meaning. I will describe the definitions I have encountered more often, i.e. in several projects with different companies. The **business logic** defines a normalized, general-purpose model of the business domain for which an application is written, e.g. * Classes like `Customer`, `Order`, `OrderLine`, and associations like `customer-order`, and so on. * General-purpose operations such as `registerCustomer`, `cancelOrder` Very often this class model is mapped to a database model and the mapping is implemented using ORM. The operations are normally performed each in their own transaction and provide the basic API for modifying the database, i.e. the persistent state of the application. The **application logic** is a layer built on top of the business logic and serves to implement specific use cases. Application logic modules may use ad-hoc data representation, e.g. a CustomerSummary class without any association to `Order` if you want to list customers only. Such ad-hoc data representation must be mapped to the underlying normalized representation provided by the business model. For example, `CustomerSummary` can be defined as a view on top of `Customer`. Note that the boundary between the two layers may not be so clearly-defined. E.g. after implementing several use cases one might notice similar data structures in the application logic and decide to unify (normalize) them and move them to the business logic.
17,761,717
I tried to replace "-" character in a Java String but is doesn't work : ``` str.replace("\u2014", ""); ``` Could you help me ?
2013/07/20
['https://Stackoverflow.com/questions/17761717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1076026/']
String is Immutable in Java. You have to reassign it to get the result back: ``` String str ="your string with dashesh"; str= str.replace("\u2014", ""); ``` See the [API](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29) for details.
this simply works.. ``` String str = "String-with-dash-"; str=str.replace("-", ""); System.out.println(str); ``` output - Stringwithdash
17,761,717
I tried to replace "-" character in a Java String but is doesn't work : ``` str.replace("\u2014", ""); ``` Could you help me ?
2013/07/20
['https://Stackoverflow.com/questions/17761717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1076026/']
String is Immutable in Java. You have to reassign it to get the result back: ``` String str ="your string with dashesh"; str= str.replace("\u2014", ""); ``` See the [API](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29) for details.
It's quite easy. You can use an Apache library, that will be useful while you develop an application. This is apache-commons-lang. You can do the following: ``` public class Main { public static void main(String[] args) { String test = "Dash - string"; String withoutDash = StringUtils.replace(test, "-", ""); System.out.println(withoutDash); } } ```
17,761,717
I tried to replace "-" character in a Java String but is doesn't work : ``` str.replace("\u2014", ""); ``` Could you help me ?
2013/07/20
['https://Stackoverflow.com/questions/17761717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1076026/']
this simply works.. ``` String str = "String-with-dash-"; str=str.replace("-", ""); System.out.println(str); ``` output - Stringwithdash
It's quite easy. You can use an Apache library, that will be useful while you develop an application. This is apache-commons-lang. You can do the following: ``` public class Main { public static void main(String[] args) { String test = "Dash - string"; String withoutDash = StringUtils.replace(test, "-", ""); System.out.println(withoutDash); } } ```
12,206
How can start the VNC server to make my desktop accessible?
2010/11/08
['https://askubuntu.com/questions/12206', 'https://askubuntu.com', 'https://askubuntu.com/users/3999/']
Install vino: ``` sudo apt-get install vino ``` Configure vino: ``` vino-preferences ``` It open this windows : ![alt text](https://i.stack.imgur.com/2JSpB.png) You start the server with : ``` /usr/lib/vino/vino-server ``` Enter this command in your Autostarted Apps if you wish vino to start automatically.
For a bit more security, I don't leave VNC running the whole time. I SSH into the machine and then start the VNC server using the following command: x11vnc -safer -localhost -nopw -once -display :0 For ease I have the command in a shell script, so it is just a case of SSH to the server, followed by the command startvnc.sh. This way once you disconnect VNC is no longer available. For even more security you can tunnel VNC over the SSH connection. This [link](http://www.cyberciti.biz/tips/tunneling-vnc-connections-over-ssh-howto.html) provides details on how to forward the correct ports.
12,206
How can start the VNC server to make my desktop accessible?
2010/11/08
['https://askubuntu.com/questions/12206', 'https://askubuntu.com', 'https://askubuntu.com/users/3999/']
Install vino: ``` sudo apt-get install vino ``` Configure vino: ``` vino-preferences ``` It open this windows : ![alt text](https://i.stack.imgur.com/2JSpB.png) You start the server with : ``` /usr/lib/vino/vino-server ``` Enter this command in your Autostarted Apps if you wish vino to start automatically.
Here is the whole process I do to utilize VNC, simplified --- ONE. SETUP server install VNC: `sudo apt-get install vnc` install openssh-server: `sudo apt-get install openssh-server` --- TWO. SETUP remote access PC install PuTTY install VNC or VNC viewer --- THREE. Connect and Launch: From remote access PC: 1. Run PuTTY 2. Connect SSH into the servers IP 3. Log into the server with Login ID and Password 4. A Run: `sudo x11vnc -display :0 -auth guess` B Else if that doesn't work, run: `sudo x11vnc -display :0 -auth <insert your path to your .Xauthority>` C Else if that doesn't work, run the commands again but as root. Then once connection is established... 5. Launch VNC viewer 6. When prompted, enter the servers IP and connect You now have accessed your server via VNC and should be able to control and interact with that desktop. Good Luck and Enjoy!!
12,206
How can start the VNC server to make my desktop accessible?
2010/11/08
['https://askubuntu.com/questions/12206', 'https://askubuntu.com', 'https://askubuntu.com/users/3999/']
Install vino: ``` sudo apt-get install vino ``` Configure vino: ``` vino-preferences ``` It open this windows : ![alt text](https://i.stack.imgur.com/2JSpB.png) You start the server with : ``` /usr/lib/vino/vino-server ``` Enter this command in your Autostarted Apps if you wish vino to start automatically.
As root, run: ``` sudo apt-get install vino ``` As your user, run: ``` gsettings set org.gnome.Vino require-encryption false vino-preferences # replace eth0 in the following with your network interface gsettings set org.gnome.Vino network-interface eth0 /usr/lib/vino/vino-server ``` A script can be written to automaticly start `/usr/lib/vino/vino-server` or you can just have your window manager start it directly once it loads and your network is UP, this method worked for me because I was having security type 18 issues with windows VNC Viewer not connecting and I had to turn off encryption
12,206
How can start the VNC server to make my desktop accessible?
2010/11/08
['https://askubuntu.com/questions/12206', 'https://askubuntu.com', 'https://askubuntu.com/users/3999/']
Here is the whole process I do to utilize VNC, simplified --- ONE. SETUP server install VNC: `sudo apt-get install vnc` install openssh-server: `sudo apt-get install openssh-server` --- TWO. SETUP remote access PC install PuTTY install VNC or VNC viewer --- THREE. Connect and Launch: From remote access PC: 1. Run PuTTY 2. Connect SSH into the servers IP 3. Log into the server with Login ID and Password 4. A Run: `sudo x11vnc -display :0 -auth guess` B Else if that doesn't work, run: `sudo x11vnc -display :0 -auth <insert your path to your .Xauthority>` C Else if that doesn't work, run the commands again but as root. Then once connection is established... 5. Launch VNC viewer 6. When prompted, enter the servers IP and connect You now have accessed your server via VNC and should be able to control and interact with that desktop. Good Luck and Enjoy!!
For a bit more security, I don't leave VNC running the whole time. I SSH into the machine and then start the VNC server using the following command: x11vnc -safer -localhost -nopw -once -display :0 For ease I have the command in a shell script, so it is just a case of SSH to the server, followed by the command startvnc.sh. This way once you disconnect VNC is no longer available. For even more security you can tunnel VNC over the SSH connection. This [link](http://www.cyberciti.biz/tips/tunneling-vnc-connections-over-ssh-howto.html) provides details on how to forward the correct ports.
12,206
How can start the VNC server to make my desktop accessible?
2010/11/08
['https://askubuntu.com/questions/12206', 'https://askubuntu.com', 'https://askubuntu.com/users/3999/']
Here is the whole process I do to utilize VNC, simplified --- ONE. SETUP server install VNC: `sudo apt-get install vnc` install openssh-server: `sudo apt-get install openssh-server` --- TWO. SETUP remote access PC install PuTTY install VNC or VNC viewer --- THREE. Connect and Launch: From remote access PC: 1. Run PuTTY 2. Connect SSH into the servers IP 3. Log into the server with Login ID and Password 4. A Run: `sudo x11vnc -display :0 -auth guess` B Else if that doesn't work, run: `sudo x11vnc -display :0 -auth <insert your path to your .Xauthority>` C Else if that doesn't work, run the commands again but as root. Then once connection is established... 5. Launch VNC viewer 6. When prompted, enter the servers IP and connect You now have accessed your server via VNC and should be able to control and interact with that desktop. Good Luck and Enjoy!!
As root, run: ``` sudo apt-get install vino ``` As your user, run: ``` gsettings set org.gnome.Vino require-encryption false vino-preferences # replace eth0 in the following with your network interface gsettings set org.gnome.Vino network-interface eth0 /usr/lib/vino/vino-server ``` A script can be written to automaticly start `/usr/lib/vino/vino-server` or you can just have your window manager start it directly once it loads and your network is UP, this method worked for me because I was having security type 18 issues with windows VNC Viewer not connecting and I had to turn off encryption
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
You can directly make your Background Blur using "Visual Effect View with Blur" and "Visual Effect View with Blur and Vibrancy". All you have to do for making Blur Background in iOS Application is... 1. Go and search for "Visual Effect View with Blur" in Object Library [Step 1 Image](https://i.stack.imgur.com/Qy0Vf.png) 2. Drag the "Visual Effect View with Blur" in your Storyboard and setup it... [Step 2 Image](https://i.stack.imgur.com/hn3i2.png) 3. Finally... You make your App Background Blur! [Application Layout before clicking on any Button!](https://i.stack.imgur.com/uyO2w.png) [Application View After Clicking on Button which makes the whole application background Blur!](https://i.stack.imgur.com/DS7My.png)
Simple answer is Add a subview and change it's alpha. ``` UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; UIView *subView = [[UIView alloc] initWithFrame:popupView.frame]; UIColor * backImgColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue_Img.png"]]; subView.backgroundColor = backImgColor; subView.alpha = 0.5; [mainView addSubview:subView]; ```
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
I don't think I'm allowed to post the code, but the above post mentioning the WWDC sample code is correct. Here is the link: <https://developer.apple.com/downloads/index.action?name=WWDC%202013> The file you're looking for is the category on UIImage, and the method is applyLightEffect. As I noted above in a comment, the Apple Blur has saturation and other things going on besides blur. A simple blur will not do... if you are looking to emulate their style.
You can directly make your Background Blur using "Visual Effect View with Blur" and "Visual Effect View with Blur and Vibrancy". All you have to do for making Blur Background in iOS Application is... 1. Go and search for "Visual Effect View with Blur" in Object Library [Step 1 Image](https://i.stack.imgur.com/Qy0Vf.png) 2. Drag the "Visual Effect View with Blur" in your Storyboard and setup it... [Step 2 Image](https://i.stack.imgur.com/hn3i2.png) 3. Finally... You make your App Background Blur! [Application Layout before clicking on any Button!](https://i.stack.imgur.com/uyO2w.png) [Application View After Clicking on Button which makes the whole application background Blur!](https://i.stack.imgur.com/DS7My.png)
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
You can use `UIVisualEffectView` to achieve this effect. This is a native API that has been fine-tuned for performance and great battery life, plus it's easy to implement. **Swift:** ``` //only apply the blur if the user hasn't disabled transparency effects if !UIAccessibility.isReduceTransparencyEnabled { view.backgroundColor = .clear let blurEffect = UIBlurEffect(style: .dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) //always fill the view blurEffectView.frame = self.view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed } else { view.backgroundColor = .black } ``` **Objective-C:** ``` //only apply the blur if the user hasn't disabled transparency effects if (!UIAccessibilityIsReduceTransparencyEnabled()) { self.view.backgroundColor = [UIColor clearColor]; UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]; UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect]; //always fill the view blurEffectView.frame = self.view.bounds; blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [self.view addSubview:blurEffectView]; //if you have more UIViews, use an insertSubview API to place it where needed } else { self.view.backgroundColor = [UIColor blackColor]; } ``` If you are presenting this view controller modally to blur the underlying content, you'll need to set the modal presentation style to Over Current Context and set the background color to clear to ensure the underlying view controller will remain visible once this is presented overtop.
Apple has provided an extension for the UIImage class called UIImage+ImageEffects.h. In this class you have the desired methods for blurring your view
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
I decided to post a written Objective-C version from the accepted answer just to provide more options in this question.. ``` - (UIView *)applyBlurToView:(UIView *)view withEffectStyle:(UIBlurEffectStyle)style andConstraints:(BOOL)addConstraints { //only apply the blur if the user hasn't disabled transparency effects if(!UIAccessibilityIsReduceTransparencyEnabled()) { UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:style]; UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect]; blurEffectView.frame = view.bounds; [view addSubview:blurEffectView]; if(addConstraints) { //add auto layout constraints so that the blur fills the screen upon rotating device [blurEffectView setTranslatesAutoresizingMaskIntoConstraints:NO]; [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTop multiplier:1 constant:0]]; [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeBottom multiplier:1 constant:0]]; [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeLeading multiplier:1 constant:0]]; [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]]; } } else { view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7]; } return view; } ``` The constraints could be removed if you want incase if you only support portrait mode or I just add a flag to this function to use them or not..
Apple has provided an extension for the UIImage class called UIImage+ImageEffects.h. In this class you have the desired methods for blurring your view
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
Found this by accident, gives me really great (near duplicate with Apple's) results and uses the Acceleration framework. -- <http://pastebin.com/6cs6hsyQ> \*Not written by me
Here is the Swift 2.0 code for the solution that has been provided in **accepted answer**: ``` //only apply the blur if the user hasn't disabled transparency effects if !UIAccessibilityIsReduceTransparencyEnabled() { self.view.backgroundColor = UIColor.clearColor() let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) //always fill the view blurEffectView.frame = self.view.bounds blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.view.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed } else { self.view.backgroundColor = UIColor.blackColor() } ```
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
This answer is based on [Mitja Semolic's excellent earlier answer](https://stackoverflow.com/questions/29498884/less-blur-with-visual-effect-view-with-blur). I've converted it to swift 3, added an explanation to what's happening in coments, made it an extension of a UIViewController so any VC can call it at will, added an unblurred view to show selective application, and added a completion block so that the calling view controller can do whatever it wants at the completion of the blur. ``` import UIKit //This extension implements a blur to the entire screen, puts up a HUD and then waits and dismisses the view. extension UIViewController { func blurAndShowHUD(duration: Double, message: String, completion: @escaping () -> Void) { //with completion block //1. Create the blur effect & the view it will occupy let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light) let blurEffectView = UIVisualEffectView()//(effect: blurEffect) blurEffectView.frame = self.view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] //2. Add the effect view to the main view self.view.addSubview(blurEffectView) //3. Create the hud and add it to the main view let hud = HudView.getHUD(view: self.view, withMessage: message) self.view.addSubview(hud) //4. Begin applying the blur effect to the effect view UIView.animate(withDuration: 0.01, animations: { blurEffectView.effect = blurEffect }) //5. Halt the blur effects application to achieve the desired blur radius self.view.pauseAnimationsInThisView(delay: 0.004) //6. Remove the view (& the HUD) after the completion of the duration DispatchQueue.main.asyncAfter(deadline: .now() + duration) { blurEffectView.removeFromSuperview() hud.removeFromSuperview() self.view.resumeAnimationsInThisView() completion() } } } extension UIView { public func pauseAnimationsInThisView(delay: Double) { let time = delay + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, time, 0, 0, 0, { timer in let layer = self.layer let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil) layer.speed = 0.0 layer.timeOffset = pausedTime }) CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes) } public func resumeAnimationsInThisView() { let pausedTime = layer.timeOffset layer.speed = 1.0 layer.timeOffset = 0.0 layer.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime } } ``` I've confirmed that it works with both iOS 10.3.1 and iOS 11
Apple has provided an extension for the UIImage class called UIImage+ImageEffects.h. In this class you have the desired methods for blurring your view
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
In case this helps anyone, here is a swift extension I created based on the answer by Jordan H. It is written in Swift 5 and can be used from Objective C. ``` extension UIView { @objc func blurBackground(style: UIBlurEffect.Style, fallbackColor: UIColor) { if !UIAccessibility.isReduceTransparencyEnabled { self.backgroundColor = .clear let blurEffect = UIBlurEffect(style: style) let blurEffectView = UIVisualEffectView(effect: blurEffect) //always fill the view blurEffectView.frame = self.self.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.insertSubview(blurEffectView, at: 0) } else { self.backgroundColor = fallbackColor } } } ``` NOTE: If you want to blur the background of an UILabel without affecting the text, you should create a container UIView, add the UILabel to the container UIView as a subview, set the UILabel's backgroundColor to UIColor.clear, and then call blurBackground(style: UIBlurEffect.Style, fallbackColor: UIColor) on the container UIView. Here's a quick example of this written in Swift 5: ``` let frame = CGRect(x: 50, y: 200, width: 200, height: 50) let containerView = UIView(frame: frame) let label = UILabel(frame: frame) label.text = "Some Text" label.backgroundColor = UIColor.clear containerView.addSubview(label) containerView.blurBackground(style: .dark, fallbackColor: UIColor.black) ```
**An important supplement to @Joey's answer** This applies to a situation where you want to present a blurred-background `UIViewController` with `UINavigationController`. ``` // suppose you've done blur effect with your presented view controller UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController]; // this is very important, if you don't do this, the blur effect will darken after view did appeared // the reason is that you actually present navigation controller, not presented controller // please note it's "OverFullScreen", not "OverCurrentContext" nav.modalPresentationStyle = UIModalPresentationOverFullScreen; UIViewController *presentedViewController = [[UIViewController alloc] init]; // the presented view controller's modalPresentationStyle is "OverCurrentContext" presentedViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext; [presentingViewController presentViewController:nav animated:YES completion:nil]; ``` Enjoy!
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
Swift 3 Version of Kev's answer to return blurred image - ``` func blurBgImage(image: UIImage) -> UIImage? { let radius: CGFloat = 20; let context = CIContext(options: nil); let inputImage = CIImage(cgImage: image.cgImage!); let filter = CIFilter(name: "CIGaussianBlur"); filter?.setValue(inputImage, forKey: kCIInputImageKey); filter?.setValue("\(radius)", forKey:kCIInputRadiusKey); if let result = filter?.value(forKey: kCIOutputImageKey) as? CIImage{ let rect = CGRect(origin: CGPoint(x: radius * 2,y :radius * 2), size: CGSize(width: image.size.width - radius * 4, height: image.size.height - radius * 4)) if let cgImage = context.createCGImage(result, from: rect){ return UIImage(cgImage: cgImage); } } return nil; } ```
Apple has provided an extension for the UIImage class called UIImage+ImageEffects.h. In this class you have the desired methods for blurring your view
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
Swift 3 Version of Kev's answer to return blurred image - ``` func blurBgImage(image: UIImage) -> UIImage? { let radius: CGFloat = 20; let context = CIContext(options: nil); let inputImage = CIImage(cgImage: image.cgImage!); let filter = CIFilter(name: "CIGaussianBlur"); filter?.setValue(inputImage, forKey: kCIInputImageKey); filter?.setValue("\(radius)", forKey:kCIInputRadiusKey); if let result = filter?.value(forKey: kCIOutputImageKey) as? CIImage{ let rect = CGRect(origin: CGPoint(x: radius * 2,y :radius * 2), size: CGSize(width: image.size.width - radius * 4, height: image.size.height - radius * 4)) if let cgImage = context.createCGImage(result, from: rect){ return UIImage(cgImage: cgImage); } } return nil; } ```
If adds a dark blur view for tableView, this will beautifully make it: ``` tableView.backgroundColor = .clear let blurEffect = UIBlurEffect(style: .dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = tableView.bounds blurEffectView.autoresizingMask = [.flexibleHeight, .flexibleWidth] // Assigning blurEffectView to backgroundView instead of addSubview to tableView makes tableView cell not blocked by blurEffectView tableView.backgroundView = blurEffectView ```
17,041,685
I would like to change the value of a recursive array. One array provides the `path` to the variable to change: `$scopePath` represents the path to change. For example `if $scopePath==Array("owners","products","categories")` and $tag="price"; I would like to change `$value["owners"]["products"]["categories"]["tag"]` to `true` ``` $u=$value; foreach ($scopePath as $i => $s) { if (!isset($u[$s])) $u[$s]=Array(); $u=$u[$s]; } $u[$tag]=true; ``` I know the problem is because of the line $u=$u[$s] because this changes the reference to $u, but I don't know how to fix it.
2013/06/11
['https://Stackoverflow.com/questions/17041685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1993501/']
Core Image ---------- Since that image in the screenshot is static, you could use `CIGaussianBlur` from Core Image (requires iOS 6). Here is sample: <https://github.com/evanwdavis/Fun-with-Masks/blob/master/Fun%20with%20Masks/EWDBlurExampleVC.m> Mind you, this is slower than the other options on this page. ``` #import <QuartzCore/QuartzCore.h> - (UIImage*) blur:(UIImage*)theImage { // ***********If you need re-orienting (e.g. trying to blur a photo taken from the device camera front facing camera in portrait mode) // theImage = [self reOrientIfNeeded:theImage]; // create our blurred image CIContext *context = [CIContext contextWithOptions:nil]; CIImage *inputImage = [CIImage imageWithCGImage:theImage.CGImage]; // setting up Gaussian Blur (we could use one of many filters offered by Core Image) CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"]; [filter setValue:inputImage forKey:kCIInputImageKey]; [filter setValue:[NSNumber numberWithFloat:15.0f] forKey:@"inputRadius"]; CIImage *result = [filter valueForKey:kCIOutputImageKey]; // CIGaussianBlur has a tendency to shrink the image a little, // this ensures it matches up exactly to the bounds of our original image CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]]; UIImage *returnImage = [UIImage imageWithCGImage:cgImage];//create a UIImage for this function to "return" so that ARC can manage the memory of the blur... ARC can't manage CGImageRefs so we need to release it before this function "returns" and ends. CGImageRelease(cgImage);//release CGImageRef because ARC doesn't manage this on its own. return returnImage; // *************** if you need scaling // return [[self class] scaleIfNeeded:cgImage]; } +(UIImage*) scaleIfNeeded:(CGImageRef)cgimg { bool isRetina = [[[UIDevice currentDevice] systemVersion] intValue] >= 4 && [[UIScreen mainScreen] scale] == 2.0; if (isRetina) { return [UIImage imageWithCGImage:cgimg scale:2.0 orientation:UIImageOrientationUp]; } else { return [UIImage imageWithCGImage:cgimg]; } } - (UIImage*) reOrientIfNeeded:(UIImage*)theImage{ if (theImage.imageOrientation != UIImageOrientationUp) { CGAffineTransform reOrient = CGAffineTransformIdentity; switch (theImage.imageOrientation) { case UIImageOrientationDown: case UIImageOrientationDownMirrored: reOrient = CGAffineTransformTranslate(reOrient, theImage.size.width, theImage.size.height); reOrient = CGAffineTransformRotate(reOrient, M_PI); break; case UIImageOrientationLeft: case UIImageOrientationLeftMirrored: reOrient = CGAffineTransformTranslate(reOrient, theImage.size.width, 0); reOrient = CGAffineTransformRotate(reOrient, M_PI_2); break; case UIImageOrientationRight: case UIImageOrientationRightMirrored: reOrient = CGAffineTransformTranslate(reOrient, 0, theImage.size.height); reOrient = CGAffineTransformRotate(reOrient, -M_PI_2); break; case UIImageOrientationUp: case UIImageOrientationUpMirrored: break; } switch (theImage.imageOrientation) { case UIImageOrientationUpMirrored: case UIImageOrientationDownMirrored: reOrient = CGAffineTransformTranslate(reOrient, theImage.size.width, 0); reOrient = CGAffineTransformScale(reOrient, -1, 1); break; case UIImageOrientationLeftMirrored: case UIImageOrientationRightMirrored: reOrient = CGAffineTransformTranslate(reOrient, theImage.size.height, 0); reOrient = CGAffineTransformScale(reOrient, -1, 1); break; case UIImageOrientationUp: case UIImageOrientationDown: case UIImageOrientationLeft: case UIImageOrientationRight: break; } CGContextRef myContext = CGBitmapContextCreate(NULL, theImage.size.width, theImage.size.height, CGImageGetBitsPerComponent(theImage.CGImage), 0, CGImageGetColorSpace(theImage.CGImage), CGImageGetBitmapInfo(theImage.CGImage)); CGContextConcatCTM(myContext, reOrient); switch (theImage.imageOrientation) { case UIImageOrientationLeft: case UIImageOrientationLeftMirrored: case UIImageOrientationRight: case UIImageOrientationRightMirrored: CGContextDrawImage(myContext, CGRectMake(0,0,theImage.size.height,theImage.size.width), theImage.CGImage); break; default: CGContextDrawImage(myContext, CGRectMake(0,0,theImage.size.width,theImage.size.height), theImage.CGImage); break; } CGImageRef CGImg = CGBitmapContextCreateImage(myContext); theImage = [UIImage imageWithCGImage:CGImg]; CGImageRelease(CGImg); CGContextRelease(myContext); } return theImage; } ``` Stack blur (Box + Gaussian) --------------------------- * [StackBlur](https://github.com/tomsoft1/StackBluriOS) This implements a mix of Box and Gaussian blur. 7x faster than non accelerated gaussian, but not so ugly as box blur. See a demo in [here](http://incubator.quasimondo.com/processing/fast_blur_deluxe.php) (Java plugin version) or [here](http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html) (JavaScript version). This algorithm is used in KDE and Camera+ and others. It doesn't use the Accelerate Framework but it's fast. Accelerate Framework -------------------- * In the session “Implementing Engaging UI on iOS” from [WWDC 2013](https://developer.apple.com/wwdc/videos/) Apple explains how to create a blurred background (at 14:30), and mentions a method [`applyLightEffect`](https://developer.apple.com/downloads/download.action?path=wwdc_2013/wwdc_2013_sample_code/ios_uiimageeffects.zip) implemented in the sample code using Accelerate.framework. * [GPUImage](https://github.com/BradLarson/GPUImage) uses OpenGL shaders to create dynamic blurs. It has several types of blur: GPUImageBoxBlurFilter, GPUImageFastBlurFilter, GaussianSelectiveBlur, GPUImageGaussianBlurFilter. There is even a GPUImageiOSBlurFilter that “should fully replicate the blur effect provided by iOS 7's control panel” ([tweet](https://twitter.com/bradlarson/status/391684261369368576/), [article](http://www.sunsetlakesoftware.com/2013/10/21/optimizing-gaussian-blurs-mobile-gpu)). The article is detailed and informative. ``` -(UIImage *)blurryGPUImage:(UIImage *)image withBlurLevel:(NSInteger)blur { GPUImageFastBlurFilter *blurFilter = [GPUImageFastBlurFilter new]; blurFilter.blurSize = blur; UIImage *result = [blurFilter imageByFilteringImage:image]; return result; } ``` * From indieambitions.com: [Perform a blur using vImage](http://indieambitions.com/idevblogaday/perform-blur-vimage-accelerate-framework-tutorial/). The algorithm is also used in [iOS-RealTimeBlur](https://github.com/alexdrone/ios-realtimeblur). * From Nick Lockwood: <https://github.com/nicklockwood/FXBlurView> The example shows the blur over a scroll view. It blurs with dispatch\_async, then syncs to call updates with UITrackingRunLoopMode so the blur is not lagged when UIKit gives more priority to the scroll of the UIScrollView. This is explained in Nick's book [iOS Core Animation](http://www.informit.com/store/ios-core-animation-advanced-techniques-9780133440751), which btw it's great. * [iOS-blur](https://github.com/JagCesar/iOS-blur) This takes the blurring layer of the UIToolbar and puts it elsewhere. Apple will reject your app if you use this method. See <https://github.com/mochidev/MDBlurView/issues/4> * From Evadne blog: [LiveFrost: Fast, Synchronous UIView Snapshot Convolving](http://blog.radi.ws/post/61836396624/livefrost-fast-synchronous-uiview-snapshot-convolving). Great code and a great read. Some ideas from this post: + Use a serial queue to throttle updates from CADisplayLink. + Reuse bitmap contexts unless bounds change. + Draw smaller images using -[CALayer renderInContext:] with a 0.5f scale factor. Other stuff ----------- Andy Matuschak [said](http://twitter.com/andy_matuschak/status/345677479534542848) on Twitter: “you know, a lot of the places where it looks like we're doing it in real time, it's static with clever tricks.” At [doubleencore.com](http://www.doubleencore.com/2013/09/the-essential-ios-7-design-guide/) they say “we’ve found that a 10 pt blur radius plus a 10 pt increase in saturation best mimics iOS 7’s blur effect under most circumstances”. A peek at the private headers of Apple's [SBFProceduralWallpaperView](https://github.com/JaviSoto/iOS7-Runtime-Headers/blob/master/PrivateFrameworks/SpringBoardFoundation.framework/SBFProceduralWallpaperView.h). Finally, this isn't a real blur, but remember you can set rasterizationScale to get a pixelated image: <http://www.dimzzy.com/blog/2010/11/blur-effect-for-uiview/>
I think the easiest solution to this is to override UIToolbar, which blurs everything behind it in iOS 7. It's quite sneaky, but it's very simple for you to implement, and fast! You can do it with any view, just make it a subclass of `UIToolbar` instead of `UIView`. You can even do it with a `UIViewController`'s `view` property, for example... 1) create a new class that is a "Subclass of" `UIViewController` and check the box for "With XIB for user interface". 2) Select the View and go to the identity inspector in the right-hand panel (alt-command-3). Change the "Class" to `UIToolbar`. Now go to the attributes inspector (alt-command-4) and change the "Background" color to "Clear Color". 3) Add a subview to the main view and hook it up to an IBOutlet in your interface. Call it `backgroundColorView`. It will look something like this, as a private category in the implementation (`.m`) file. ``` @interface BlurExampleViewController () @property (weak, nonatomic) IBOutlet UIView *backgroundColorView; @end ``` 4) Go to the view controller implementation (`.m`) file and change the `-viewDidLoad` method, to look as follows: ``` - (void)viewDidLoad { [super viewDidLoad]; self.view.barStyle = UIBarStyleBlack; // this will give a black blur as in the original post self.backgroundColorView.opaque = NO; self.backgroundColorView.alpha = 0.5; self.backgroundColorView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1]; } ``` This will give you a dark gray view, which blurs everything behind it. No funny business, no slow core image blurring, using everything that is at your fingertips provided by the OS/SDK. You can add this view controller's view to another view, as follows: ``` [self addChildViewController:self.blurViewController]; [self.view addSubview:self.blurViewController.view]; [self.blurViewController didMoveToParentViewController:self]; // animate the self.blurViewController into view ``` Let me know if anything is unclear, I'll be happy to help! --- Edit ---- UIToolbar has been changed in 7.0.3 to give possibly-undesirable effect when using a coloured blur. We used to be able to set the colour using `barTintColor`, but if you were doing this before, you will need to set the alpha component to less than 1. Otherwise your UIToolbar will be completely opaque colour - with no blur. This can be achieved as follows: (bearing in mind `self` is a subclass of `UIToolbar`) ``` UIColor *color = [UIColor blueColor]; // for example self.barTintColor = [color colorWithAlphaComponent:0.5]; ``` This will give a blue-ish tint to the blurred view.
66,593,970
I am trying to implement consul-agent and proxy as sidecar container inside my ECS fargate service. So, inside the task, there will be 3 containers running: * core-business-service-container * consul-agent-container * core-business-consul-proxy-container All containers are up and running on ECS task. The node has registered in the consul UI as well. But, the service is not up in the consul UI. I dig in and found the log of 'consul-agent-container', Here is the error log: > > 2021/03/12 03:33:14 [ERR] http: Request PUT > /v1/agent/check/pass/greeting-fargate-proxy-ttl?note=, error: CheckID > "greeting-fargate-proxy-ttl" does not have associated TTL > from=127.0.0.1:43252 > > > Here are the commands I used to connect consul. 1. consul-agent-container: > > "exec consul agent -ui -data-dir /consul/data -client="127.0.0.1" > -bind="{{ GetPrivateIP }}" -retry-join "172.31.79.139"" > > > 2. core-business-consul-proxy-container: > > "exec consul connect proxy -register -service greeting-fargate > -http-addr 127.0.0.1:8500 -listen 127.0.0.1:8080 -service-addr 127.0.0.1:3000" > > >
2021/03/12
['https://Stackoverflow.com/questions/66593970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9923849/']
HashiCorp recently announced support for running Consul service mesh on ECS using Terraform to deploy the agent and sidecar components. You might want to consider this as an alternative solution to your existing workflow. This solution is currently in tech preview. You can find more information in the blog post <https://www.hashicorp.com/blog/announcing-consul-service-mesh-for-amazon-ecs>.
I did not manage to get my proxy to work using the same method as you were using. But I remember reading somewhere that you should declare your Connect proxy inside the service registration config ``` { "service": { "name": "web", "port": 8080, "connect": { "sidecar_service": {} } } } ``` After you have done that I think you could just launch your proxy using: ``` consul connect proxy -sidecar-for <service-id> ``` I did not verify this because the application I was using used Spring Cloud Consul to register the services and I did not find where to register a proxy, but maybe this can help you further.
3,550,591
We say a positive symmetric $n\times n$ matrix $M$ over $\mathbb{R}^n$ is semi-definite if $v^{\intercal}Mv\geq 0$ for all nonzero $v\in\mathbb{R}^n$. We say a function $f:\mathbb{T}^2\longrightarrow\mathbb{R}$ to be positive semi-definite if $\Big(f(t\_k, t\_j)\Big)\_{k,j=1}^n$ is a positive semi-definite matrix for all $(t\_k)\_{k=1}^n\in\mathbb{T}^n$ With this definition, I am working on an exercise asking me to show > > $(1)$ the function $f:(s,t)\mapsto t\wedge s$ defined for $s,t\geq 0$ is positive semi-definite; > > > $(2)$ the function $c:(s,t)\mapsto e^{-|t-s|}$ is positive semi-definite. > > > For the first one, I tried to use the fact that $$\int\_{\mathbb{R}^{+}}\mathbb{1}\_{[0,t]}\mathbb{1}\_{[0,s]} \,d\mu = t\wedge s,$$ so that each term in the matrix is of the form $b\_{i,j}:=f(t\_i,t\_j)=\int\_{\mathbb{R}^{+}}\mathbb{1}\_{[0,t\_{j}]} \mathbb{1}\_{[0,t\_{}} \, d\mu$, for $t,j=1,\cdots,n$. Let $v=(v\_1,\ldots, v\_n)\in\mathbb{R}^n$, then $$v^{\intercal} Mv=a\_1 \sum\_{i=1}^n a\_i b\_{i,1}+a\_2\sum\_{i=1}^n a\_i b\_{i,2} + a\_3 \sum\_{i=1}^n a\_i b\_{i,3}+\cdots+a\_n \sum\_{i=1}^n a\_i b\_{i,n}.$$ **But then I don't know what to do next..** For the second one, the exercise gives an hint: using an auxiliary Hilbert space $H$ and a $h\_t\in H$ such that $\langle h\_t, h\_s\rangle=c(s,t)\ldots$ I don't really know how to use this hint... I really need an answer with some details, since this is an exercise in Stochastic Process, instead of functional analysis and so forth, so I don't have enough background of this... Thank you so much! --- **Edit 1: (Proof of the first one)** Following **MaoWao**'s suggestion, I think I proved the first one. Firstly let me claim that if $H$ is a Hilbert space, then its corresponding inner product $\langle\cdot, \cdot\rangle\_H:H\times H\longrightarrow\mathbb{R}$ is positive semi-definite. Indeed, we have for any $n\in\mathbb{N}$, $x\_1,\ldots, x\_n \in H$ and $c\_1,\ldots, c\_n \in\mathbb{R}$ that $$\sum\_{i,j=1}^n c\_i c\_j \langle x\_i,x\_j\rangle\_H = \left<\sum\_{i=1}^n c\_i x\_i,\sum\_{j=1}^n c\_j x\_j \right>\_H =\Big\|\sum\_{i=1}^n c\_i x\_i\Big\|\_H^2\geq 0.$$ In fact, the above result also holds for pre-Hilbert space, since the notion of completeness was not involved in the above argument. Thus, we only need to find a specific (pre-)Hilbert Space $H$ and a $h\_{t}\in H$ such that $\langle h\_t, h\_s\rangle\_H = t\wedge s$. But this is easy, let's consider $H:=L^2(\mathbb{R}\_{+})$, and $h\_t:=\mathbb{1}\_{[0,t]}$. It is clear that $h\_t\in H$, and for any $t,s\geq 0$, we have $$\langle h\_t, h\_s\rangle\_{L^2(\mathbb{R}\_{+})} = \int\_{\mathbb{R}\_{+}}\mathbb{1}\_{[0,t]} \mathbb{1}\_{[0,s]} \, d\mu=t\wedge s,$$ and thus we are done. --- **Edit 2: (Proof of the second one)** I've searched all over the places. The function in $(2)$ is Abel kernel, but it is rarely discussed since Abel kernel is closely related to Poisson kernel, and most of the discussions are on the latter. Later, I found a really close one: the Gaussian kernel and here is a link about the proof of Gaussian kernel is really a kernel. That is, it is positive semidefinite. <https://stats.stackexchange.com/questions/35634/how-to-prove-that-the-radial-basis-function-is-a-kernel> In this link, one answer used the characteristic function. This greatly inspired me. I also found a characteristic function, which is the one for Cauchy distribution. Below is the proof: Recall the Cauchy Distribution $(x\_{0},\gamma)$ with $\gamma>0$ has the characteristic function $$\varphi(t)=e^{ix\_{0}t-\gamma|t|}.$$ Using this, we can write $c(s,t)=h(s-t)$ where $h(t):=e^{-|t|}=\mathbb{E}e^{itZ}$ is the characteristic function of a random variable $Z$ with Cauchy $(0,1)$ distribution. Then for real numbers $x\_{1},\cdots, x\_{n}$ and $a\_{1},\cdots, a\_{n}$, we have \begin{align\*} \sum\_{j,k=1}^{n}a\_{j}a\_{k}h(x\_{j}-x\_{k})&=\sum\_{j,k=1}^{n}a\_{j}a\_{k}\mathbb{E}e^{i(x\_{j}-x\_{k})Z}\\ &=\mathbb{E}\Big(\sum\_{j,k=1}^{n}a\_{j}e^{ix\_{j}Z}a\_{k}e^{-ix\_{k}Z}\Big)\\ &=\mathbb{E}\Big(\Big|\sum\_{j=1}^{n}a\_{j}e^{ix\_{j}Z}\Big|^{2}\Big)\geq 0. \end{align\*} Thus, $c$ is positive semi-definite. **It seems that I did not use the hint at all for part $(2)$, so I believe there must be another way.** **I do need someone to check if my proof in the edit 1 and edit 2 is correct. I am gonna open a bounty in 19 hours later, for proof checking and possible new proof. Thank you!**
2020/02/17
['https://math.stackexchange.com/questions/3550591', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/502975/']
As **MaoWao** suggested, I am gonna post my own proof here. --- *Proof of (1):* Firstly let me claim that if $H$ is a Hilbert space, then its corresponding inner product $\langle \cdot, \cdot\rangle\_{H}:H\times H\longrightarrow\mathbb{R}$ is positive semi-definite. Indeed, we have for any $n\in\mathbb{N}$, $x\_{1},\cdots, x\_{n}\in H$ and $c\_{1},\cdots, c\_{n}\in\mathbb{R}$ that $$\sum\_{i,j=1}^{n}c\_{i}c\_{j}\langle x\_{i}, x\_{j}\rangle\_{H}=\Big<\sum\_{i=1}^{n}c\_{i}x\_{i},\sum\_{j=1}^{n}c\_{j}x\_{j}\Big>\_{H}=\Big\|\sum\_{i=1}^{n}c\_{i}x\_{i}\Big\|\_{H}^{2}\geq 0.$$ In fact, the above result also holds for pre-Hilbert space, since the notion of completeness was not involved in the above argument. Thus, we only need to find a specific (pre-)Hilbert Space $H$ and a $h\_{t}\in H$ such that $\langle h\_{t}, h\_{s}\rangle\_{H}=t\wedge s$. But this is immediate. Let's consider $H:=L^{2}(\mathbb{R}\_{+})$, and $h\_{t}:=\mathbb{1}\_{[0,t]}$. It is clear that $h\_{t}\in H$, and for any $t,s\geq 0$, we have $$\langle h\_{t}, h\_{s}\rangle\_{L^{2}(\mathbb{R}\_{+})}=\int\_{\mathbb{R}\_{+}}\mathbb{1}\_{[0,t]}\mathbb{1}\_{[0,s]}d\mu=t\wedge s,$$ and thus we are done. --- *Proof of $(2)$:* Recall the Cauchy Distribution $(x\_{0},\gamma)$ with $\gamma>0$ has the characteristic function $$\varphi(t)=e^{ix\_{0}t-\gamma|t|}.$$ Using this, we can write $c(s,t)=h(s-t)$ where $h(t):=e^{-|t|}=\mathbb{E}e^{itZ}$ is the characteristic function of a random variable $Z$ with Cauchy $(0,1)$ distribution. Then for real numbers $x\_{1},\cdots, x\_{n}$ and $a\_{1},\cdots, a\_{n}$, we have \begin{align\*} \sum\_{j,k=1}^{n}a\_{j}a\_{k}h(x\_{j}-x\_{k})&=\sum\_{j,k=1}^{n}a\_{j}a\_{k}\mathbb{E}e^{i(x\_{j}-x\_{k})Z}\\ &=\mathbb{E}\Big(\sum\_{j,k=1}^{n}a\_{j}e^{ix\_{j}Z}a\_{k}e^{-ix\_{k}Z}\Big)\\ &=\mathbb{E}\Big(\Big|\sum\_{j=1}^{n}a\_{j}e^{ix\_{j}Z}\Big|^{2}\Big)\geq 0. \end{align\*} Thus, $c$ is positive semi-definite. --- Also, as **MaoWao** pointed out, the proof of $(2)$ can be equivalently written into something similar to what we did in the $(1)$, by taking the Hilbert space $L^{2}(\mathbb{P})$ and $h\_{t}=\exp(it\cdot)$ I am really grateful to the help, suggestion and proof verification from **MaoWao**. I'd like also to express my appreciation to **Michael Hardy**, for the discussion and help. Thank you guys :)
This will be a partial answer. The standard Wiener process $\{B(t)\}\_{t\,\ge\,0},$ also called the standard Brownian motion, assigns to each $t\ge0$ a random variable $B(t)$ in such a way that every increment $B(t)-B(s)$ for $0\le s\le t$ is distributed as $\operatorname N(0,t-s)$ (the standard normal distribution with expected value $0$ and variance $t-s,$ so standard deviation $\sqrt{t-s},$ and for **pairwise disjoint** intervals $(s\_i,t\_i),$ $i=1,\ldots,n,$ with $0\le s\_i\le t\_i,$ the increments $B(t\_i) - B(s\_i)$ are **independent** random variables. Then for $0\le s\le t$ one can show that $$ \operatorname{cov}(B(s), B(t)) = s = s\wedge t. $$ That is done by writing $$ \operatorname{cov}\Big(B(s), \Big(B(t) - B(s)\Big) + B(s)\Big) $$ and then using the independence of $B(t) - B(s)$ and $B(s).$ Since all the entries in the matrix of covariances of $B(t\_1),\ldots, B(t\_n)$ are of the form $t\_i\wedge t\_j,$ and since every matrix of covariances is positive-semi-definite, the function $(s,t)\mapsto s\wedge t$ must be positive-semi-definite.
28,478,191
Hi all I've a problem with include function in php: I have 4 file: ``` dir1/file1.php dir4/dir2/file2.php dir3/file3.php dir3/file4.php ``` In file1.php I have: ``` include_once('../dir3/file3.php'); ``` In file3.php I have: ``` required('../dir3/file4.php'); ``` In file2.php I want write: ``` include_once('../../dir3/file3.php'); ``` but the required function in file3 doesn't work because the path of file4 must be ``` ../../dir3/file4.php ``` and not ``` ../dir3/file4.php ``` How can I fix it?
2015/02/12
['https://Stackoverflow.com/questions/28478191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3297525/']
You can use only dot (.) before your filename which will find that file from root of dir..for eg `./dir3/file4.php` but it increase the overhead..Another way is to use ``` $base = __DIR__ . '/../'; require_once $base.'_include/file1.php'; ```
If you are calling file3 from file2 you will have to go back 2 directories. The best way is using the full path like : ``` home/mysite/public_html/dir3/file3.php ``` It maybe (is) troublesome but good uptill some level. Edit: **DIR** and rest is also handy, depending on your need
28,478,191
Hi all I've a problem with include function in php: I have 4 file: ``` dir1/file1.php dir4/dir2/file2.php dir3/file3.php dir3/file4.php ``` In file1.php I have: ``` include_once('../dir3/file3.php'); ``` In file3.php I have: ``` required('../dir3/file4.php'); ``` In file2.php I want write: ``` include_once('../../dir3/file3.php'); ``` but the required function in file3 doesn't work because the path of file4 must be ``` ../../dir3/file4.php ``` and not ``` ../dir3/file4.php ``` How can I fix it?
2015/02/12
['https://Stackoverflow.com/questions/28478191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3297525/']
You can use only dot (.) before your filename which will find that file from root of dir..for eg `./dir3/file4.php` but it increase the overhead..Another way is to use ``` $base = __DIR__ . '/../'; require_once $base.'_include/file1.php'; ```
**I FIX it with:** In file1.php I have: ``` $path = '..'; include_once($path.'/dir3/file3.php'); ``` In file3.php I have: ``` required($path.'/dir3/file4.php'); ``` In file2.php I want write: ``` $path = '../..' include_once($path.'/dir3/file3.php'); ``` **This work for me.**
31,021,553
I am trying to follow the redirect of a url using urllib2. ``` >>> import urllib2 >>> page=urllib2.urlopen('http://acer.com') >>> print page.geturl() http://www.acer.com/worldwide/selection.html >>>page=urllib2.urlopen('http://www.acer.com/worldwide/selection.html') >>> print page.geturl() http://www.acer.com/worldwide/selection.html ``` But when I open `http://www.acer.com/worldwide/selection.html` in my browser it redirects to `http://us.acer.com/ac/en/US/content/home#_ga=1.216787925.232352975.1435019296` How to detect this redirection using urllib.
2015/06/24
['https://Stackoverflow.com/questions/31021553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2350219/']
`get_url()` doesn't work for all re-directs (for example JavaScript redirects) What are you trying to achieve? Something like [Selenium](https://pypi.python.org/pypi/selenium) with [PhantomJS](http://phantomjs.org/) as the backend might be more suited to this. For screenshots you can then use [`save_screenshot()`](http://selenium-python.readthedocs.org/en/latest/api.html#selenium.webdriver.remote.webdriver.WebDriver.save_screenshot) which is part of Selenium Webdriver
Use `selenium` to get start. I'm using [chromedriver](https://sites.google.com/a/chromium.org/chromedriver/) as browser: `from selenium.webdriver import Chrome cr = Chrome() cr.get(url) cr.save_screenshot('IMAGE_NAME.png')`
2,570,174
If you have a function in the form of $f(kx)$, the graph is horizontally scaled by a factor of $k$ and the bigger the magnitude of $k$, the more compressed the graph gets, and the inverse is true. So by definition, $k$ should be called the horizontal compression factor of the function, meaning if $k = \frac{1}{2}$, the graph is horizontally compressed by a factor of $\frac{1}{2}$, and since stretching is the inverse of compressing you could also say the graph is horizontally stretched by a factor of $2$. and using the same logic, if $k = 2$ then the graph is horizontally compressed by a factor of $2$ or horizontally stretched by a factor of $\frac{1}{2}$ But this is not the case and the accepted practice is to say the graph is compressed by a factor of $k$ if $|k|>1$ and stretched by a factor of $k$ if $0<|k|<1$ This seems extremely unintuitive and to me it doesn't use the word factor correctly. So my question is why do we describe stretching and compressing transformations like this?
2017/12/17
['https://math.stackexchange.com/questions/2570174', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/444199/']
The inverse function: $$ g(y)\ :=\ \frac{\log\_2(y)+1}{\log\_2(y)-1} $$ **REMARK**   Domains: $$ f : \mathbb R\setminus\{1\}\ \rightarrow\ (0;\infty)\setminus\{2\} $$ and $$ g : (0;\infty)\setminus{2}\ \rightarrow\ \mathbb R\setminus\{1\} $$ > >   > > > **Explanation:** Function $\ f\ $ is a composition of two functions: $$ f = \psi\circ \phi $$ where $\ \phi(s)\ :=\ \frac{s+1}{s-1}\ $ and $\ \psi(t)\ :=\ 2^t.\ $ The inverse of $\ \phi\ $ is this function itself. The inverse of the exponential function $\ \psi\ $ is $\ \log\_2.\ $ Thus inverse of $\ f\ $ is $\ g\ :=\ \phi\circ\log\_2.$
Answer is : $$ x = {{\log(y) + \log(2)} \over {\log(y)-\log(2)}} $$ Demo : $$ y = f(x) \\ {{x+1} \over {x-1}} = {{\log y} \over {\log 2}} = P \\ x+1=P(x-1) \\ x+1=Px-P \\ x={{P+1} \over {P-1}} = {{{{\log y} \over {\log 2}}+1} \over {{\log y} \over {\log 2}}-1} $$
718,982
I found this observation in a book. "It is not possible to have an invariant definition of symmetry in one contravariant and one covariant index". That's all right, my problem is that to show how restrictive is to require symmetry on a mixed tensor $A^i\_j$ the authors ask to resolve the following problem: If a tensor $A$ of type $(1,1)$ is symmetric in its indices with respect to every basis, that is, $A^i\_j=A^j\_i$, then $A$ is a multiple of the identity tensor, $A^i\_j=\alpha\delta^i\_j$. I can prove that if $i\neq j\implies A^i\_j=0$, but when $i=j$ I obtain different values instead of a constant value, in other words, the matrix $A^i\_j$ is diagonal having different values along the diagonal. Can anybody comment on this?
2022/07/18
['https://physics.stackexchange.com/questions/718982', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/80627/']
*Sketched proof:* The mixed tensor components $A^i{}\_j$ transform (in matrix notation) as $A^{\prime}=SAS^{-1}$, where $S\in GL(n,\mathbb{R})$ is an arbitrary invertible matrix. Let $S$ be symmetric from now on. Then transposition yields $A^{\prime}=S^{-1}AS$ because all matrices are symmetric. Elimination of $A^{\prime}$ yields $S^2A=AS^2$. Now let $S=\exp(ts)$, where $t\in\mathbb{R}$, and $s$ is an arbitrary symmetric (not necessarily invertible) matrix. If follows that $sA=As$ commute. Let $e\_{ij}$ denote the matrix whose $(i,j)$th matrix entry is $1$, and all other entries are $0$. By picking $s=e\_{ii}$ we see that $A$ is diagonal. By picking $s=e\_{ij}+e\_{ji}$ we see that the diagonal elements of $A$ must be the same, i.e. $A$ is a multiple of the identity matrix. $\Box$
Thank you, guys. I think you both tackled special cases. However, your matrix approaches led me to a general solution I believe is also correct. From the general transformation $A'=S^{-1}AS$ we have $SA'=AS$. Assuming we already proved that $A$ is diagonal, let $A=diag\{\lambda\_1\ldots\lambda\_n\}$ and $A'=diag\{\lambda'\_1\ldots\lambda'\_n\}$, then we have $$(SA')\_{ik}=\sum\_j s\_{ij}a'\_{jk}=s\_{ik}\lambda'\_k$$ $$(AS)\_{ik}=\sum\_j a\_{ij}s\_{jk}=\lambda\_i s\_{ik}$$ Since the problem states the condition must hold for arbitrary bases, we can assume that for a given $k,\quad s\_{ik}\neq0$ for al $i$, then we have $$\lambda\_i=\lambda'\_k=\alpha,\qquad i=1,2,\ldots,n$$ Since $A^i\_j=0$ for $i\neq j$ we have $A^i\_j=\alpha\delta^i\_j$
718,982
I found this observation in a book. "It is not possible to have an invariant definition of symmetry in one contravariant and one covariant index". That's all right, my problem is that to show how restrictive is to require symmetry on a mixed tensor $A^i\_j$ the authors ask to resolve the following problem: If a tensor $A$ of type $(1,1)$ is symmetric in its indices with respect to every basis, that is, $A^i\_j=A^j\_i$, then $A$ is a multiple of the identity tensor, $A^i\_j=\alpha\delta^i\_j$. I can prove that if $i\neq j\implies A^i\_j=0$, but when $i=j$ I obtain different values instead of a constant value, in other words, the matrix $A^i\_j$ is diagonal having different values along the diagonal. Can anybody comment on this?
2022/07/18
['https://physics.stackexchange.com/questions/718982', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/80627/']
Consider the change of basis with the matrix $\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$. $$ \begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix} \begin{pmatrix} 1 & 0\\ 0 & a \end{pmatrix} \begin{pmatrix} 1 & -1\\ 0 & 1 \end{pmatrix} = \begin{pmatrix} 1 & a-1\\ 0 & a \end{pmatrix} $$ is symmetric if and only if $a=1$. In more than two dimensions just use this change of basis in a two-dimensional subspace and the identity in the normal space to it.
Thank you, guys. I think you both tackled special cases. However, your matrix approaches led me to a general solution I believe is also correct. From the general transformation $A'=S^{-1}AS$ we have $SA'=AS$. Assuming we already proved that $A$ is diagonal, let $A=diag\{\lambda\_1\ldots\lambda\_n\}$ and $A'=diag\{\lambda'\_1\ldots\lambda'\_n\}$, then we have $$(SA')\_{ik}=\sum\_j s\_{ij}a'\_{jk}=s\_{ik}\lambda'\_k$$ $$(AS)\_{ik}=\sum\_j a\_{ij}s\_{jk}=\lambda\_i s\_{ik}$$ Since the problem states the condition must hold for arbitrary bases, we can assume that for a given $k,\quad s\_{ik}\neq0$ for al $i$, then we have $$\lambda\_i=\lambda'\_k=\alpha,\qquad i=1,2,\ldots,n$$ Since $A^i\_j=0$ for $i\neq j$ we have $A^i\_j=\alpha\delta^i\_j$
13,690,372
Hey I have the following strings as input: ``` "abcol" "ab_col" "cold" "col_ab" "col.ab" ``` I have the string col to search from. I'm using regex to match ``` Match matchResults = Regex.Match(input , "col", RegexOptions.IgnoreCase); ``` I want to match only the string that has this pattern `[Any special character or nothing ] + col + [Any special character or nothing]` From the above inputs, I want to return only `ab_col, col_ab , col.ab` Any help is highly appreciated. Thanks [Any special character] = [^A-Za-z0-9]
2012/12/03
['https://Stackoverflow.com/questions/13690372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1178492/']
You can use this regex: - ``` (?:^.*[^a-zA-Z0-9]|^)col(?:[^a-zA-Z0-9].*$|$) ``` **Explanation : -** ``` (?: // non-capturing ^ // match at start of the string .*[^a-zA-Z0-9] // match anything followed by a non-alphanumeric before `col` | // or ^ // match the start itself (means nothing before col) ) col // match col (?: // non-capturing [^a-zA-Z0-9].* // match a non-alphanumeric after `col` followed by anything $ // match end of string | // or $ // just match the end itself (nothing after col) ) ```
`@"(^|.*[\W_])col([\W_].*|$)"` this is your pattern. `\w` is alphanumeric character and `\W` is non alphanumeric character. `^` means line start and `$` means line end. `|` is the or. so `(^|.*\W)` means line start or some characters and non alphanumeric after them. **EDIT:** yes, underline is alphanumeric too... so you should write `[\W_]` (non alphanumeric or underline) instead of `\W`
36,834,939
I have a Stored Procedure to get the details of Invoices Some occasions I get the list of invoices by sending only the InvoiceID But in some other occasions I need to get the list of invoices as per the search fields supplied by the user. To do this I send all the fields to the Stored Procedure and use those parameters as below. I included only 2 columns but there are more. ``` SELECT * FROM INVOICES I WHERE (@InvoiceNumber is null or I.InvoiceNumber = @InvoiceNumber) and (@PONo is null or I.PONo = @PONo) ``` Is there a way to send the condition for the WHERE clause as one parameter?
2016/04/25
['https://Stackoverflow.com/questions/36834939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4073943/']
Yes, it is possible with Dynamic SQL, but I highly discourage to do that. [SELECT \* FROM tbl WHERE @condition](http://www.sommarskog.se/dynamic_sql.html#Condition): > > If you are considering to write the procedure > > > > ``` > CREATE PROCEDURE search_sp @condition varchar(8000) AS > SELECT * FROM tbl WHERE @condition > > ``` > > **Just forget it. If you are doing this, you have not completed the transition to use stored procedure and you are still assembling your > SQL code in the client.** > > > It will also open your application to SQL Injection attacks.
You can use custom type to pass table as parameter <https://msdn.microsoft.com/pl-pl/library/bb510489(v=sql.110).aspx> or you can use default parameters
36,834,939
I have a Stored Procedure to get the details of Invoices Some occasions I get the list of invoices by sending only the InvoiceID But in some other occasions I need to get the list of invoices as per the search fields supplied by the user. To do this I send all the fields to the Stored Procedure and use those parameters as below. I included only 2 columns but there are more. ``` SELECT * FROM INVOICES I WHERE (@InvoiceNumber is null or I.InvoiceNumber = @InvoiceNumber) and (@PONo is null or I.PONo = @PONo) ``` Is there a way to send the condition for the WHERE clause as one parameter?
2016/04/25
['https://Stackoverflow.com/questions/36834939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4073943/']
Yes, it is possible with Dynamic SQL, but I highly discourage to do that. [SELECT \* FROM tbl WHERE @condition](http://www.sommarskog.se/dynamic_sql.html#Condition): > > If you are considering to write the procedure > > > > ``` > CREATE PROCEDURE search_sp @condition varchar(8000) AS > SELECT * FROM tbl WHERE @condition > > ``` > > **Just forget it. If you are doing this, you have not completed the transition to use stored procedure and you are still assembling your > SQL code in the client.** > > > It will also open your application to SQL Injection attacks.
If you're using SQL Server 2016 or similar (check by calling `select compatibility_level, name from sys.databases` and seeing that your DB is 130 or higher) then you can use the [string\_split](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql) builtin function. I found it works best like this (spread out for clarity) ``` CREATE PROCEDURE [dbo].[GetInvoices] @InvoiceNumber int = NULL @PONo nvarchar(1024) = NULL AS SELECT * from [Invoices] AS [i] WHERE i.InvoiceNumber = ISNULL(@InvoiceNunber, i.InvoiceNunber) AND CASE WHEN @PONo is null THEN 1 ELSE (CASE WHEN i.PONo IN (select value from string_split(@PONo, ',')) THEN 1 ELSE 0 END) END = 1 ``` So if you pass in a null to either parameter it gets translated as `where x = x` which is always true, and if you pass in a CSV value, it selects it from a split table of values that, if present, results in the where clause being `where 1=1`, which is true or `0=1` if the value is not present in the input list. So here you can pass in an invoice number, or PO number, or both, or neither and it should return what you expect.
36,834,939
I have a Stored Procedure to get the details of Invoices Some occasions I get the list of invoices by sending only the InvoiceID But in some other occasions I need to get the list of invoices as per the search fields supplied by the user. To do this I send all the fields to the Stored Procedure and use those parameters as below. I included only 2 columns but there are more. ``` SELECT * FROM INVOICES I WHERE (@InvoiceNumber is null or I.InvoiceNumber = @InvoiceNumber) and (@PONo is null or I.PONo = @PONo) ``` Is there a way to send the condition for the WHERE clause as one parameter?
2016/04/25
['https://Stackoverflow.com/questions/36834939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4073943/']
You can use custom type to pass table as parameter <https://msdn.microsoft.com/pl-pl/library/bb510489(v=sql.110).aspx> or you can use default parameters
If you're using SQL Server 2016 or similar (check by calling `select compatibility_level, name from sys.databases` and seeing that your DB is 130 or higher) then you can use the [string\_split](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql) builtin function. I found it works best like this (spread out for clarity) ``` CREATE PROCEDURE [dbo].[GetInvoices] @InvoiceNumber int = NULL @PONo nvarchar(1024) = NULL AS SELECT * from [Invoices] AS [i] WHERE i.InvoiceNumber = ISNULL(@InvoiceNunber, i.InvoiceNunber) AND CASE WHEN @PONo is null THEN 1 ELSE (CASE WHEN i.PONo IN (select value from string_split(@PONo, ',')) THEN 1 ELSE 0 END) END = 1 ``` So if you pass in a null to either parameter it gets translated as `where x = x` which is always true, and if you pass in a CSV value, it selects it from a split table of values that, if present, results in the where clause being `where 1=1`, which is true or `0=1` if the value is not present in the input list. So here you can pass in an invoice number, or PO number, or both, or neither and it should return what you expect.
6,039,356
I'm sort of stumbling around with an issue with Xcode 4, and Git. I'm a one man shop with multiple macs, and had my project working with Git and Xcode4, (stored on a dropbox folder), so I could share that folder across my MBP and iMac with minimal interaction. So, it was late one night and I accidentally committed my xcode project file, and then I started getting issues with UserInterfaceState.xuserstate constantly updating... Later learned that .gitignore would have been good to have in place. Back to the drawing board and I've been trying to take the new (old) project and enable git on it with the following: $cd path/to/project $git init $git add . $git commit -m "Initial commit of project" This works fine, now I'm back in XCODE, and add the repository, which it recognizes in Organizer. One Issue is XCODE doesn't recognize that I've modified a file, and the majority of the "Source Control" menu items are disabled, Ex: "Commit" I'm wondering if there are a recommended # of steps to: 1) Get Git running on a xcode project that wasn't set up this way initially 2) Steps to add the Gitignore file and when * Ultimately would like the "Source Control" menu items enabled again. I'm obviously learning some Git SCM related items with xcode 4, and I appreciate your feedback!
2011/05/18
['https://Stackoverflow.com/questions/6039356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415640/']
To add Git to the project 1. Go to the directory and in a terminal window ``` cat > .gitignore build/* *.pbxuser *.perspectivev3 *.mode1v3 javascripts/phonegap.*.js ``` Type Ctrl+D to close the file. 2. Initialize the Git repository ``` git init git add . git commit -m ``` 3. Add the repository in organizer. Use the full directory path. Caveat - this still does not enable Source Control menu items. But you can use git from the command line. See other related post: [Using Git with an existing XCode project](https://stackoverflow.com/questions/5383609/using-git-with-an-existing-xcode-project)
There are [three ways of setting up exclude files](http://365git.tumblr.com/post/519016351/three-ways-of-excluding-files) in git. Which is easiest depends on you. But, I find that when using git to share for myself amongst multiple machines, a global ignore file works best, and I can always add more specific excludes if you need to. Essentially 1. Globally, by setting up a per user or per machine exclude file 2. Per repository - by setting up a .gitignore file in the repo 3. Per clone - by setting up the `.git/info/excludes file I've got a my [global exclude file on Github](https://gist.github.com/708713) if you want to see an example, including Xcode4 specific exclusions.
6,039,356
I'm sort of stumbling around with an issue with Xcode 4, and Git. I'm a one man shop with multiple macs, and had my project working with Git and Xcode4, (stored on a dropbox folder), so I could share that folder across my MBP and iMac with minimal interaction. So, it was late one night and I accidentally committed my xcode project file, and then I started getting issues with UserInterfaceState.xuserstate constantly updating... Later learned that .gitignore would have been good to have in place. Back to the drawing board and I've been trying to take the new (old) project and enable git on it with the following: $cd path/to/project $git init $git add . $git commit -m "Initial commit of project" This works fine, now I'm back in XCODE, and add the repository, which it recognizes in Organizer. One Issue is XCODE doesn't recognize that I've modified a file, and the majority of the "Source Control" menu items are disabled, Ex: "Commit" I'm wondering if there are a recommended # of steps to: 1) Get Git running on a xcode project that wasn't set up this way initially 2) Steps to add the Gitignore file and when * Ultimately would like the "Source Control" menu items enabled again. I'm obviously learning some Git SCM related items with xcode 4, and I appreciate your feedback!
2011/05/18
['https://Stackoverflow.com/questions/6039356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415640/']
Maybe this isn't the answer you want but I gave up on getting Xcode4 to play well with git and just started using the excellent (and free) [SourceTree](http://www.sourcetreeapp.com/). It really made my life easier.
To add Git to the project 1. Go to the directory and in a terminal window ``` cat > .gitignore build/* *.pbxuser *.perspectivev3 *.mode1v3 javascripts/phonegap.*.js ``` Type Ctrl+D to close the file. 2. Initialize the Git repository ``` git init git add . git commit -m ``` 3. Add the repository in organizer. Use the full directory path. Caveat - this still does not enable Source Control menu items. But you can use git from the command line. See other related post: [Using Git with an existing XCode project](https://stackoverflow.com/questions/5383609/using-git-with-an-existing-xcode-project)
6,039,356
I'm sort of stumbling around with an issue with Xcode 4, and Git. I'm a one man shop with multiple macs, and had my project working with Git and Xcode4, (stored on a dropbox folder), so I could share that folder across my MBP and iMac with minimal interaction. So, it was late one night and I accidentally committed my xcode project file, and then I started getting issues with UserInterfaceState.xuserstate constantly updating... Later learned that .gitignore would have been good to have in place. Back to the drawing board and I've been trying to take the new (old) project and enable git on it with the following: $cd path/to/project $git init $git add . $git commit -m "Initial commit of project" This works fine, now I'm back in XCODE, and add the repository, which it recognizes in Organizer. One Issue is XCODE doesn't recognize that I've modified a file, and the majority of the "Source Control" menu items are disabled, Ex: "Commit" I'm wondering if there are a recommended # of steps to: 1) Get Git running on a xcode project that wasn't set up this way initially 2) Steps to add the Gitignore file and when * Ultimately would like the "Source Control" menu items enabled again. I'm obviously learning some Git SCM related items with xcode 4, and I appreciate your feedback!
2011/05/18
['https://Stackoverflow.com/questions/6039356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415640/']
Maybe this isn't the answer you want but I gave up on getting Xcode4 to play well with git and just started using the excellent (and free) [SourceTree](http://www.sourcetreeapp.com/). It really made my life easier.
There are [three ways of setting up exclude files](http://365git.tumblr.com/post/519016351/three-ways-of-excluding-files) in git. Which is easiest depends on you. But, I find that when using git to share for myself amongst multiple machines, a global ignore file works best, and I can always add more specific excludes if you need to. Essentially 1. Globally, by setting up a per user or per machine exclude file 2. Per repository - by setting up a .gitignore file in the repo 3. Per clone - by setting up the `.git/info/excludes file I've got a my [global exclude file on Github](https://gist.github.com/708713) if you want to see an example, including Xcode4 specific exclusions.
96,880
My company is a software vendor. We develop software that is later deployed on the customer's environment, on their own machines. Our software uses various DBMS, depending on what the customer has. We do it for PostgreSQL, MySQL and so on. Currently we have two new customers, which are using Oracle DB in their own production environments. We are obliged, however, to provide an user acceptance environments, which are ought to be 1:1 to the customer's production environment. Hence my question - do we need to buy an Oracle DB license for ourselves, provided we're never going to have a production environment with that product? In another words - since the customer has the Oracle DB license do we also need to buy one only for testing purposes?
2015/04/02
['https://dba.stackexchange.com/questions/96880', 'https://dba.stackexchange.com', 'https://dba.stackexchange.com/users/1172/']
If you want to shrink ibdata1, so that it should only contain the metadata, You may try these steps To shrink ibdata1 once and for all you must do the following: 1. MySQLDump all databases into a SQL text file (as bkp\_all\_db.sql) 2. Drop all databases (except mysql schema) 3. Stop MySQL `/etc/init.d/mysql stop` 4. Add the following lines to /etc/my.cnf ``` [mysqld] innodb_file_per_table innodb_flush_method=O_DIRECT innodb_log_file_size=1G innodb_buffer_pool_size=4G ``` 5. Now remove ibdata1, so that there should only be the mysql schema in /var/lib/mysql rm -f /var/lib/mysql/ibdata1 /var/lib/mysql/ib\_logfile 6. Start MySQL instance, This will recreate ibdata1, ib\_logfile0 and ib\_logfile1 at 1G each service mysqld start 7. Reload bkp\_all\_db.sql into mysql (import). ibdata1 will grow but only contain table metadata <http://mysqlrockstar.blogspot.in/2014/07/mysql-ibdata1-file-shrink.html>
The config items you added in should have little to no impact on the situation. n.b. you will probably also want `log-slave-updates`, ([details](https://dev.mysql.com/doc/refman/5.6/en/replication-options-slave.html#option_mysqld_log-slave-updates)) but leave that out until after you've imported the data, of you'll have 100's of GB's of binary logs created. I think the real question is whether your OS is happy with a single file that size, bearing in mind that it wont get smaller, but may get larger. If it's going to be an issue you may want to look at `innodb_file_per_table` ([details](https://dev.mysql.com/doc/refman/5.6/en/innodb-multiple-tablespaces.html)) which 'basically' splits the data between `ibdata1` and a file for each table. (This involves reloading the dumpfile to take affect) (this is on by default from MySQL 5.6.6) There are pros and cons for both options.
41,462,493
I have a PHP script that serves portions of a PDF file by byte ranges. If an HTTP HEAD request is received, it should send back headers (including the PDF file size) but not the actual file contents. I have tried this: ``` header('HTTP/1.1 200 OK'); header('Content-Type: application/pdf'); header('Accept-Ranges: bytes'); header('Content-Length: '.filesize($Pathname)); die; ``` The problem is that something (I assume the web server == LiteSpeed) replaces the Content-Length header with `Content-Length: 0` - which defeats the whole purpose. Can anyone suggest what I should be doing? Thanks
2017/01/04
['https://Stackoverflow.com/questions/41462493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7373028/']
From w3c Hypertext Transfer Protocol -- HTTP/1.1: > > When a Content-Length is given in a message where a message-body is > allowed, its field value MUST exactly match the number of OCTETs in > the message-body. HTTP/1.1 user agents MUST notify the user when an > invalid length is received and detected. > > > And: > > The Content-Length entity-header field indicates the size of the > entity-body, in decimal number of OCTETs, sent to the recipient or, in > the case of the HEAD method, the size of the entity-body that would > have been sent had the request been a GET. > > > So, I suppose, your code will properly work if you send real HEAD request to your server.
As Lurii mentioned, the content length is affected by your request type. With GET requests, a non-matching content length may result in a hanging client, so LiteSpeed will verify the content length before sending the header to the client. Using a HEAD request should return the content length as expected.
41,462,493
I have a PHP script that serves portions of a PDF file by byte ranges. If an HTTP HEAD request is received, it should send back headers (including the PDF file size) but not the actual file contents. I have tried this: ``` header('HTTP/1.1 200 OK'); header('Content-Type: application/pdf'); header('Accept-Ranges: bytes'); header('Content-Length: '.filesize($Pathname)); die; ``` The problem is that something (I assume the web server == LiteSpeed) replaces the Content-Length header with `Content-Length: 0` - which defeats the whole purpose. Can anyone suggest what I should be doing? Thanks
2017/01/04
['https://Stackoverflow.com/questions/41462493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7373028/']
From w3c Hypertext Transfer Protocol -- HTTP/1.1: > > When a Content-Length is given in a message where a message-body is > allowed, its field value MUST exactly match the number of OCTETs in > the message-body. HTTP/1.1 user agents MUST notify the user when an > invalid length is received and detected. > > > And: > > The Content-Length entity-header field indicates the size of the > entity-body, in decimal number of OCTETs, sent to the recipient or, in > the case of the HEAD method, the size of the entity-body that would > have been sent had the request been a GET. > > > So, I suppose, your code will properly work if you send real HEAD request to your server.
It's the webserver job, not yours. In my case I left everything to the Apache webserver and nothing changed in my php code except of how the requests is being parsed For example things like ``` if($_SERVER['REQUEST_METHOD'] === "GET"){ //ok }else{ //send 400 Bad Request } ``` are changed to ``` if($_SERVER['REQUEST_METHOD'] === "GET" || $_SERVER['REQUEST_METHOD'] === "HEAD"){ //ok }else{ //send 400 Bad Request } ``` and Apache did all the heavy lifting (striped the response body). *(don't try to `ob_clean()` or `die("")` or things like this).* **related resources:** <http://hc.apache.org/httpclient-3.x/methods/head.html> <https://security.stackexchange.com/questions/62811/should-i-disable-http-head-requests> [Apache 2.2.2 response on HEAD requests](https://stackoverflow.com/questions/21574062/apache-2-2-2-response-on-head-requests)
114,445
Let's create some sample data ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; ``` Now I want the following: create a list plot with the first element of the list as $x$ coordinate and the third element as the $y$ coordinate. ``` d0 = Table[{d00[[i, 1]], d00[[i, 3]]}, {i, 1, Length[d00]}]; ``` The color of each point is controlled by the corresponding second element. In particular, if the real number is between -2 and 2 the point should be green, while if it is lower/equal than -2 or greater/equal than 2 the point should be red. Any suggestions?
2016/05/05
['https://mathematica.stackexchange.com/questions/114445', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']
Basically a duplicate of [this question](https://mathematica.stackexchange.com/questions/105574/plotmarkers-shadows-the-settings-by-style). You can just style each point before you pass them to `ListPlot` for things like this. Define a color function: ``` cfun = Piecewise[{{White, # <= -2}, {Green, -2 < # < 2}, {Red, # > 2}}, Black] & ``` Then style by second element: ``` d0 = Table[Style[{d00[[i, 1]], d00[[i, 3]]}, cfun[d00[[i, 2]]]], {i, 1, Length[d00]}]; ListPlot[d0, Background -> Lighter[Gray, 0.5]] ``` [![enter image description here](https://i.stack.imgur.com/xf8ui.png)](https://i.stack.imgur.com/xf8ui.png) **Also Specifying PlotMarkers** Using the `PlotMarkers` option will mask the `Style` definitions, unless you specify the undocumented: ``` Method -> {"OptimizePlotMarkers" -> False} ``` Like so: ``` GraphicsRow[{ ListPlot[d0, PlotMarkers -> {Automatic, 5}], ListPlot[d0, PlotMarkers -> {Automatic, 5}, Method -> {"OptimizePlotMarkers" -> False}] }] ``` [![enter image description here](https://i.stack.imgur.com/JaHjx.png)](https://i.stack.imgur.com/JaHjx.png)
Just some variants: ``` l = RandomReal[{-4, 4}, {200, 3}]; With[{g = #[[All, {1, 3}]] & /@ GatherBy[l, #[[2]] < 2 &]}, ListPlot[g, PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}]] ListPlot[Last@Reap[Sow[{#1, #3}, #2 < 2] & @@@ l, _, #2 &], PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}] ListPlot[GroupBy[l, #[[2]] < 2 &, #[[All, {1, 3}]] &], PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}] ``` Outputs: [![enter image description here](https://i.stack.imgur.com/s8rcQ.png)](https://i.stack.imgur.com/s8rcQ.png)
114,445
Let's create some sample data ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; ``` Now I want the following: create a list plot with the first element of the list as $x$ coordinate and the third element as the $y$ coordinate. ``` d0 = Table[{d00[[i, 1]], d00[[i, 3]]}, {i, 1, Length[d00]}]; ``` The color of each point is controlled by the corresponding second element. In particular, if the real number is between -2 and 2 the point should be green, while if it is lower/equal than -2 or greater/equal than 2 the point should be red. Any suggestions?
2016/05/05
['https://mathematica.stackexchange.com/questions/114445', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']
Basically a duplicate of [this question](https://mathematica.stackexchange.com/questions/105574/plotmarkers-shadows-the-settings-by-style). You can just style each point before you pass them to `ListPlot` for things like this. Define a color function: ``` cfun = Piecewise[{{White, # <= -2}, {Green, -2 < # < 2}, {Red, # > 2}}, Black] & ``` Then style by second element: ``` d0 = Table[Style[{d00[[i, 1]], d00[[i, 3]]}, cfun[d00[[i, 2]]]], {i, 1, Length[d00]}]; ListPlot[d0, Background -> Lighter[Gray, 0.5]] ``` [![enter image description here](https://i.stack.imgur.com/xf8ui.png)](https://i.stack.imgur.com/xf8ui.png) **Also Specifying PlotMarkers** Using the `PlotMarkers` option will mask the `Style` definitions, unless you specify the undocumented: ``` Method -> {"OptimizePlotMarkers" -> False} ``` Like so: ``` GraphicsRow[{ ListPlot[d0, PlotMarkers -> {Automatic, 5}], ListPlot[d0, PlotMarkers -> {Automatic, 5}, Method -> {"OptimizePlotMarkers" -> False}] }] ``` [![enter image description here](https://i.stack.imgur.com/JaHjx.png)](https://i.stack.imgur.com/JaHjx.png)
Another way is to use `Graphics` which gives you more control over your plot. ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; {x1, x2} = {Min[#], Max[#]} &@d00[[All, 2]]; col[x_] := If[Abs[x] < 2, Green, Red] (*for color*) scale[x_] := (x - x1)/(x2 - x1)/20 (*for point size*) Graphics[{col[#[[2]]], Disk[#[[{1, 3}]], scale[#[[2]]]]} & /@ d00, Frame -> True] ``` [![enter image description here](https://i.stack.imgur.com/xcTVs.png)](https://i.stack.imgur.com/xcTVs.png)
114,445
Let's create some sample data ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; ``` Now I want the following: create a list plot with the first element of the list as $x$ coordinate and the third element as the $y$ coordinate. ``` d0 = Table[{d00[[i, 1]], d00[[i, 3]]}, {i, 1, Length[d00]}]; ``` The color of each point is controlled by the corresponding second element. In particular, if the real number is between -2 and 2 the point should be green, while if it is lower/equal than -2 or greater/equal than 2 the point should be red. Any suggestions?
2016/05/05
['https://mathematica.stackexchange.com/questions/114445', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']
Basically a duplicate of [this question](https://mathematica.stackexchange.com/questions/105574/plotmarkers-shadows-the-settings-by-style). You can just style each point before you pass them to `ListPlot` for things like this. Define a color function: ``` cfun = Piecewise[{{White, # <= -2}, {Green, -2 < # < 2}, {Red, # > 2}}, Black] & ``` Then style by second element: ``` d0 = Table[Style[{d00[[i, 1]], d00[[i, 3]]}, cfun[d00[[i, 2]]]], {i, 1, Length[d00]}]; ListPlot[d0, Background -> Lighter[Gray, 0.5]] ``` [![enter image description here](https://i.stack.imgur.com/xf8ui.png)](https://i.stack.imgur.com/xf8ui.png) **Also Specifying PlotMarkers** Using the `PlotMarkers` option will mask the `Style` definitions, unless you specify the undocumented: ``` Method -> {"OptimizePlotMarkers" -> False} ``` Like so: ``` GraphicsRow[{ ListPlot[d0, PlotMarkers -> {Automatic, 5}], ListPlot[d0, PlotMarkers -> {Automatic, 5}, Method -> {"OptimizePlotMarkers" -> False}] }] ``` [![enter image description here](https://i.stack.imgur.com/JaHjx.png)](https://i.stack.imgur.com/JaHjx.png)
**ListPlot with styled data** ``` styleddata1 = With[{ps = Rescale[#2, Through[{Min, Max}@d00[[All, 2]]], {5, 20}]}, Style[Tooltip[{#, #3}, #2], If[-2 <= #2 <= 2, Directive[Green, AbsolutePointSize[ps]], Directive[Red, AbsolutePointSize[ps]]]]] & @@@ d00; ListPlot[styleddata1, AspectRatio -> 1] ``` ![Mathematica graphics](https://i.stack.imgur.com/hC016.png) **BubbleChart with styled data** ``` styleddata2 = Style[Tooltip[{#, #3, Rescale[#2, Through[{Min, Max}@d00[[All, 2]]], {0.05, 1}]}, #2], If[-2 <= #2 <= 2, Green, Red]] & @@@ d00; BubbleChart[styleddata2] ``` ![Mathematica graphics](https://i.stack.imgur.com/xSnAO.png)
114,445
Let's create some sample data ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; ``` Now I want the following: create a list plot with the first element of the list as $x$ coordinate and the third element as the $y$ coordinate. ``` d0 = Table[{d00[[i, 1]], d00[[i, 3]]}, {i, 1, Length[d00]}]; ``` The color of each point is controlled by the corresponding second element. In particular, if the real number is between -2 and 2 the point should be green, while if it is lower/equal than -2 or greater/equal than 2 the point should be red. Any suggestions?
2016/05/05
['https://mathematica.stackexchange.com/questions/114445', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']
Here's another option: ``` l = RandomReal[{-4, 4}, {200, 3}]; ListPlot[ List /@ (l[[All, {1, 3}]]) , PlotStyle -> (If[Abs[#[[2]]] < 2, Green, Red] & /@ l) ] ``` Where you can use any function that returns a color in your styling. You might want have to rescale your data if it's not in the range {0,1}. [![enter image description here](https://i.stack.imgur.com/ojGxm.png)](https://i.stack.imgur.com/ojGxm.png) If you want to change point sizes you can use `Directive` ``` ListPlot[ List /@ (l[[All, {1, 3}]]) , PlotStyle -> (If[Abs[#[[2]]] < 2, Directive[Green, PointSize[0.04]], Red] & /@ l) ] ``` This gives: [![enter image description here](https://i.stack.imgur.com/1JL5N.png)](https://i.stack.imgur.com/1JL5N.png)
Just some variants: ``` l = RandomReal[{-4, 4}, {200, 3}]; With[{g = #[[All, {1, 3}]] & /@ GatherBy[l, #[[2]] < 2 &]}, ListPlot[g, PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}]] ListPlot[Last@Reap[Sow[{#1, #3}, #2 < 2] & @@@ l, _, #2 &], PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}] ListPlot[GroupBy[l, #[[2]] < 2 &, #[[All, {1, 3}]] &], PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}] ``` Outputs: [![enter image description here](https://i.stack.imgur.com/s8rcQ.png)](https://i.stack.imgur.com/s8rcQ.png)
114,445
Let's create some sample data ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; ``` Now I want the following: create a list plot with the first element of the list as $x$ coordinate and the third element as the $y$ coordinate. ``` d0 = Table[{d00[[i, 1]], d00[[i, 3]]}, {i, 1, Length[d00]}]; ``` The color of each point is controlled by the corresponding second element. In particular, if the real number is between -2 and 2 the point should be green, while if it is lower/equal than -2 or greater/equal than 2 the point should be red. Any suggestions?
2016/05/05
['https://mathematica.stackexchange.com/questions/114445', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']
Here's another option: ``` l = RandomReal[{-4, 4}, {200, 3}]; ListPlot[ List /@ (l[[All, {1, 3}]]) , PlotStyle -> (If[Abs[#[[2]]] < 2, Green, Red] & /@ l) ] ``` Where you can use any function that returns a color in your styling. You might want have to rescale your data if it's not in the range {0,1}. [![enter image description here](https://i.stack.imgur.com/ojGxm.png)](https://i.stack.imgur.com/ojGxm.png) If you want to change point sizes you can use `Directive` ``` ListPlot[ List /@ (l[[All, {1, 3}]]) , PlotStyle -> (If[Abs[#[[2]]] < 2, Directive[Green, PointSize[0.04]], Red] & /@ l) ] ``` This gives: [![enter image description here](https://i.stack.imgur.com/1JL5N.png)](https://i.stack.imgur.com/1JL5N.png)
Another way is to use `Graphics` which gives you more control over your plot. ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; {x1, x2} = {Min[#], Max[#]} &@d00[[All, 2]]; col[x_] := If[Abs[x] < 2, Green, Red] (*for color*) scale[x_] := (x - x1)/(x2 - x1)/20 (*for point size*) Graphics[{col[#[[2]]], Disk[#[[{1, 3}]], scale[#[[2]]]]} & /@ d00, Frame -> True] ``` [![enter image description here](https://i.stack.imgur.com/xcTVs.png)](https://i.stack.imgur.com/xcTVs.png)
114,445
Let's create some sample data ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; ``` Now I want the following: create a list plot with the first element of the list as $x$ coordinate and the third element as the $y$ coordinate. ``` d0 = Table[{d00[[i, 1]], d00[[i, 3]]}, {i, 1, Length[d00]}]; ``` The color of each point is controlled by the corresponding second element. In particular, if the real number is between -2 and 2 the point should be green, while if it is lower/equal than -2 or greater/equal than 2 the point should be red. Any suggestions?
2016/05/05
['https://mathematica.stackexchange.com/questions/114445', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']
Here's another option: ``` l = RandomReal[{-4, 4}, {200, 3}]; ListPlot[ List /@ (l[[All, {1, 3}]]) , PlotStyle -> (If[Abs[#[[2]]] < 2, Green, Red] & /@ l) ] ``` Where you can use any function that returns a color in your styling. You might want have to rescale your data if it's not in the range {0,1}. [![enter image description here](https://i.stack.imgur.com/ojGxm.png)](https://i.stack.imgur.com/ojGxm.png) If you want to change point sizes you can use `Directive` ``` ListPlot[ List /@ (l[[All, {1, 3}]]) , PlotStyle -> (If[Abs[#[[2]]] < 2, Directive[Green, PointSize[0.04]], Red] & /@ l) ] ``` This gives: [![enter image description here](https://i.stack.imgur.com/1JL5N.png)](https://i.stack.imgur.com/1JL5N.png)
**ListPlot with styled data** ``` styleddata1 = With[{ps = Rescale[#2, Through[{Min, Max}@d00[[All, 2]]], {5, 20}]}, Style[Tooltip[{#, #3}, #2], If[-2 <= #2 <= 2, Directive[Green, AbsolutePointSize[ps]], Directive[Red, AbsolutePointSize[ps]]]]] & @@@ d00; ListPlot[styleddata1, AspectRatio -> 1] ``` ![Mathematica graphics](https://i.stack.imgur.com/hC016.png) **BubbleChart with styled data** ``` styleddata2 = Style[Tooltip[{#, #3, Rescale[#2, Through[{Min, Max}@d00[[All, 2]]], {0.05, 1}]}, #2], If[-2 <= #2 <= 2, Green, Red]] & @@@ d00; BubbleChart[styleddata2] ``` ![Mathematica graphics](https://i.stack.imgur.com/xSnAO.png)
114,445
Let's create some sample data ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; ``` Now I want the following: create a list plot with the first element of the list as $x$ coordinate and the third element as the $y$ coordinate. ``` d0 = Table[{d00[[i, 1]], d00[[i, 3]]}, {i, 1, Length[d00]}]; ``` The color of each point is controlled by the corresponding second element. In particular, if the real number is between -2 and 2 the point should be green, while if it is lower/equal than -2 or greater/equal than 2 the point should be red. Any suggestions?
2016/05/05
['https://mathematica.stackexchange.com/questions/114445', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']
Just some variants: ``` l = RandomReal[{-4, 4}, {200, 3}]; With[{g = #[[All, {1, 3}]] & /@ GatherBy[l, #[[2]] < 2 &]}, ListPlot[g, PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}]] ListPlot[Last@Reap[Sow[{#1, #3}, #2 < 2] & @@@ l, _, #2 &], PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}] ListPlot[GroupBy[l, #[[2]] < 2 &, #[[All, {1, 3}]] &], PlotStyle -> {Red, Green}, PlotMarkers -> {Automatic, 8}] ``` Outputs: [![enter image description here](https://i.stack.imgur.com/s8rcQ.png)](https://i.stack.imgur.com/s8rcQ.png)
**ListPlot with styled data** ``` styleddata1 = With[{ps = Rescale[#2, Through[{Min, Max}@d00[[All, 2]]], {5, 20}]}, Style[Tooltip[{#, #3}, #2], If[-2 <= #2 <= 2, Directive[Green, AbsolutePointSize[ps]], Directive[Red, AbsolutePointSize[ps]]]]] & @@@ d00; ListPlot[styleddata1, AspectRatio -> 1] ``` ![Mathematica graphics](https://i.stack.imgur.com/hC016.png) **BubbleChart with styled data** ``` styleddata2 = Style[Tooltip[{#, #3, Rescale[#2, Through[{Min, Max}@d00[[All, 2]]], {0.05, 1}]}, #2], If[-2 <= #2 <= 2, Green, Red]] & @@@ d00; BubbleChart[styleddata2] ``` ![Mathematica graphics](https://i.stack.imgur.com/xSnAO.png)
114,445
Let's create some sample data ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; ``` Now I want the following: create a list plot with the first element of the list as $x$ coordinate and the third element as the $y$ coordinate. ``` d0 = Table[{d00[[i, 1]], d00[[i, 3]]}, {i, 1, Length[d00]}]; ``` The color of each point is controlled by the corresponding second element. In particular, if the real number is between -2 and 2 the point should be green, while if it is lower/equal than -2 or greater/equal than 2 the point should be red. Any suggestions?
2016/05/05
['https://mathematica.stackexchange.com/questions/114445', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5052/']
Another way is to use `Graphics` which gives you more control over your plot. ``` n = 100; d00 = Table[{RandomReal[{-1, 1}], RandomReal[{-4, 4}], RandomReal[{-1, 1}]}, {i, 1, n}]; {x1, x2} = {Min[#], Max[#]} &@d00[[All, 2]]; col[x_] := If[Abs[x] < 2, Green, Red] (*for color*) scale[x_] := (x - x1)/(x2 - x1)/20 (*for point size*) Graphics[{col[#[[2]]], Disk[#[[{1, 3}]], scale[#[[2]]]]} & /@ d00, Frame -> True] ``` [![enter image description here](https://i.stack.imgur.com/xcTVs.png)](https://i.stack.imgur.com/xcTVs.png)
**ListPlot with styled data** ``` styleddata1 = With[{ps = Rescale[#2, Through[{Min, Max}@d00[[All, 2]]], {5, 20}]}, Style[Tooltip[{#, #3}, #2], If[-2 <= #2 <= 2, Directive[Green, AbsolutePointSize[ps]], Directive[Red, AbsolutePointSize[ps]]]]] & @@@ d00; ListPlot[styleddata1, AspectRatio -> 1] ``` ![Mathematica graphics](https://i.stack.imgur.com/hC016.png) **BubbleChart with styled data** ``` styleddata2 = Style[Tooltip[{#, #3, Rescale[#2, Through[{Min, Max}@d00[[All, 2]]], {0.05, 1}]}, #2], If[-2 <= #2 <= 2, Green, Red]] & @@@ d00; BubbleChart[styleddata2] ``` ![Mathematica graphics](https://i.stack.imgur.com/xSnAO.png)
56,801,384
I have table pulled from sqlite3 using sqlalchemy. This table holds the date and time of each showing of the car: ``` Id Car Code ShowTime 1 Honda A 10/18/2017 14:45 1 Honda A 10/18/2017 17:10 3 Honda C 10/18/2017 19:35 4 Toyota B 10/18/2017 12:20 4 Toyota B 10/18/2017 14:45 ``` What would be the desired output is to seperate the date and put each timestamps on a list object: ``` "data":{ 'id': '1', 'schedule': { 'car': 'Honda', 'show_date': '10/18/2017', 'time_available': [ '14:45', '17:10', ], 'code': 'A' } },{ 'id': '3', 'schedule': { 'car': 'Honda', 'show_date': '10/18/2017', 'time_available': [ '19:35' ], 'code': 'C' } },{ 'id': '4', 'schedule': { 'car': 'Toyota', 'show_date': '10/18/2017', 'time_available': [ '12:20', '14:45' ], 'code': 'B' } } ``` Any help is greatly appreciated!
2019/06/28
['https://Stackoverflow.com/questions/56801384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2341389/']
You can use pandas to split the `ShowTime` column: ``` In [22]: import pandas as pd In [68]: df = pd.read_csv('test.csv') In [69]: df.rename(columns={'Id':'id','Car':'car', 'Code':'code'}, inplace=True) In [70]: df[['show_date', 'time_available']] = df.ShowTime.str.split(' ', expand=True) In [71]: df.drop('ShowTime', axis=1, inplace=True) In [72]: df Out[72]: id car code show_date time_available 0 1 Honda A 10/18/2017 14:45 1 1 Honda A 10/18/2017 17:10 2 3 Honda C 10/18/2017 19:35 3 4 Toyota B 10/18/2017 12:20 4 4 Toyota B 10/18/2017 14:45 ``` `groupby` columns with categorical values and convert 'time\_available' column to list on the grouped dataframe: ``` In [134]: df_grp = df.groupby(['id', 'car','code', 'show_date']) In [136]: df_grp_time_stacked = df_grp['time_available'].apply(list).reset_index() In [138]: df_grp_time_stacked Out[138]: id car code show_date time_available 0 1 Honda A 10/18/2017 [14:45, 17:10] 1 3 Honda C 10/18/2017 [19:35] 2 4 Toyota B 10/18/2017 [12:20, 14:45] In [139]: df_grp_time_stacked['time_available'] = df_grp_time_stacked['time_available'].apply(lambda x:x[0] if (len(x)= ...: =1) else x) In [140]: df_grp_time_stacked Out[140]: id car code show_date time_available 0 1 Honda A 10/18/2017 [14:45, 17:10] 1 3 Honda C 10/18/2017 19:35 2 4 Toyota B 10/18/2017 [12:20, 14:45] ``` Now convert the dataframe to dict: ``` In [165]: raw_dict = df_grp_time_stacked.to_dict(orient='records') In [166]: data = {'data':raw_dict} In [167]: data Out[167]: {'data': [{'id': 1, 'car': 'Honda', 'code': 'A', 'show_date': '10/18/2017', 'time_available': ['14:45', '17:10']}, {'id': 3, 'car': 'Honda', 'code': 'C', 'show_date': '10/18/2017', 'time_available': '19:35'}, {'id': 4, 'car': 'Toyota', 'code': 'B', 'show_date': '10/18/2017', 'time_available': ['12:20', '14:45']}]} ```
You could also try the json library. Its a bit hacky because you have to do some replaces. Changed it due to a mistake in the first version. ``` import json data = """your string""" data = data.replace("\n", "").replace("\t", "") data = data.replace(r"'",r'\"').replace(" ", "").replace(",]", "]").replace('"data":', "").replace("},", r"}},") outlist = list() for helper in data.split(r"},"): helper = '"'+helper+'"' with open(path, 'w') as f: f.write(helper) with open(path, 'r') as f: json_file = json.load(f) out_dict = json.loads(json_file) outlist.append(out_dict) print(outlist) ``` this produces a list of dicts: [{'id': '1', 'schedule': {'car': 'Honda', 'show\_date': '10/18/2017', 'time\_available': ['14:45', '17:10'], 'code': 'A'}}, {'id': '3', 'schedule': {'car': 'Honda', 'show\_date': '10/18/2017', 'time\_available': ['19:35'], 'code': 'C'}}, {'id': '4', 'schedule': {'car': 'Toyota', 'show\_date': '10/18/2017', 'time\_available': ['12:20', '14:45'], 'code': 'B'}}]
56,801,384
I have table pulled from sqlite3 using sqlalchemy. This table holds the date and time of each showing of the car: ``` Id Car Code ShowTime 1 Honda A 10/18/2017 14:45 1 Honda A 10/18/2017 17:10 3 Honda C 10/18/2017 19:35 4 Toyota B 10/18/2017 12:20 4 Toyota B 10/18/2017 14:45 ``` What would be the desired output is to seperate the date and put each timestamps on a list object: ``` "data":{ 'id': '1', 'schedule': { 'car': 'Honda', 'show_date': '10/18/2017', 'time_available': [ '14:45', '17:10', ], 'code': 'A' } },{ 'id': '3', 'schedule': { 'car': 'Honda', 'show_date': '10/18/2017', 'time_available': [ '19:35' ], 'code': 'C' } },{ 'id': '4', 'schedule': { 'car': 'Toyota', 'show_date': '10/18/2017', 'time_available': [ '12:20', '14:45' ], 'code': 'B' } } ``` Any help is greatly appreciated!
2019/06/28
['https://Stackoverflow.com/questions/56801384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2341389/']
You can use pandas to split the `ShowTime` column: ``` In [22]: import pandas as pd In [68]: df = pd.read_csv('test.csv') In [69]: df.rename(columns={'Id':'id','Car':'car', 'Code':'code'}, inplace=True) In [70]: df[['show_date', 'time_available']] = df.ShowTime.str.split(' ', expand=True) In [71]: df.drop('ShowTime', axis=1, inplace=True) In [72]: df Out[72]: id car code show_date time_available 0 1 Honda A 10/18/2017 14:45 1 1 Honda A 10/18/2017 17:10 2 3 Honda C 10/18/2017 19:35 3 4 Toyota B 10/18/2017 12:20 4 4 Toyota B 10/18/2017 14:45 ``` `groupby` columns with categorical values and convert 'time\_available' column to list on the grouped dataframe: ``` In [134]: df_grp = df.groupby(['id', 'car','code', 'show_date']) In [136]: df_grp_time_stacked = df_grp['time_available'].apply(list).reset_index() In [138]: df_grp_time_stacked Out[138]: id car code show_date time_available 0 1 Honda A 10/18/2017 [14:45, 17:10] 1 3 Honda C 10/18/2017 [19:35] 2 4 Toyota B 10/18/2017 [12:20, 14:45] In [139]: df_grp_time_stacked['time_available'] = df_grp_time_stacked['time_available'].apply(lambda x:x[0] if (len(x)= ...: =1) else x) In [140]: df_grp_time_stacked Out[140]: id car code show_date time_available 0 1 Honda A 10/18/2017 [14:45, 17:10] 1 3 Honda C 10/18/2017 19:35 2 4 Toyota B 10/18/2017 [12:20, 14:45] ``` Now convert the dataframe to dict: ``` In [165]: raw_dict = df_grp_time_stacked.to_dict(orient='records') In [166]: data = {'data':raw_dict} In [167]: data Out[167]: {'data': [{'id': 1, 'car': 'Honda', 'code': 'A', 'show_date': '10/18/2017', 'time_available': ['14:45', '17:10']}, {'id': 3, 'car': 'Honda', 'code': 'C', 'show_date': '10/18/2017', 'time_available': '19:35'}, {'id': 4, 'car': 'Toyota', 'code': 'B', 'show_date': '10/18/2017', 'time_available': ['12:20', '14:45']}]} ```
Here you go: ``` import pandas as pd from collections import defaultdict data = {'Id': [1,1,3,4,4], 'Car': ['Honda','Honda','Honda','Toyota','Toyota'], 'Code': ['A','A','C','B','B'], 'ShowTime': ['10/18/2017 14:45', '10/18/2017 17:10', '10/18/2017 19:35', '10/18/2017 12:20', '10/18/2017 14:45']} df = pd.DataFrame(data) # split time data into 2 columns df['Date'], df['Time'] = df['ShowTime'].str.split(' ', 1).str # drop unneeded column df = df.drop(['ShowTime'],axis=1) def create_dictionary(i): # select data selected_data = df.loc[df['Id'] == i] # get data id = selected_data['Id'].unique() car = selected_data['Car'].unique() code = selected_data['Code'].unique() date = selected_data['Date'].unique() time = selected_data['Time'].unique() # create dictionary dictionary_data = {'id': id[0], 'schedule': {'car': car[0], 'show_date': date[0], 'time_available': list(time), 'code': code[0]}} return dictionary_data # get id list id_list = list(df['Id'].unique()) # create data dictionary out_data = defaultdict(list) for i in id_list: one = create_dictionary(i) out_data["data"].append(one) ``` Output: ``` {'data': [ {'id': 1, 'schedule': {'car': 'Honda', 'show_date': '10/18/2017', 'time_available': ['14:45', '17:10'], 'code': 'A'}}, {'id': 3, 'schedule': {'car': 'Honda', 'show_date': '10/18/2017', 'time_available': ['19:35'], 'code': 'C'}}, {'id': 4, 'schedule': {'car': 'Toyota', 'show_date': '10/18/2017', 'time_available': ['12:20', '14:45'], 'code': 'B'}} ]}) ```
56,801,384
I have table pulled from sqlite3 using sqlalchemy. This table holds the date and time of each showing of the car: ``` Id Car Code ShowTime 1 Honda A 10/18/2017 14:45 1 Honda A 10/18/2017 17:10 3 Honda C 10/18/2017 19:35 4 Toyota B 10/18/2017 12:20 4 Toyota B 10/18/2017 14:45 ``` What would be the desired output is to seperate the date and put each timestamps on a list object: ``` "data":{ 'id': '1', 'schedule': { 'car': 'Honda', 'show_date': '10/18/2017', 'time_available': [ '14:45', '17:10', ], 'code': 'A' } },{ 'id': '3', 'schedule': { 'car': 'Honda', 'show_date': '10/18/2017', 'time_available': [ '19:35' ], 'code': 'C' } },{ 'id': '4', 'schedule': { 'car': 'Toyota', 'show_date': '10/18/2017', 'time_available': [ '12:20', '14:45' ], 'code': 'B' } } ``` Any help is greatly appreciated!
2019/06/28
['https://Stackoverflow.com/questions/56801384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2341389/']
You can use pandas to split the `ShowTime` column: ``` In [22]: import pandas as pd In [68]: df = pd.read_csv('test.csv') In [69]: df.rename(columns={'Id':'id','Car':'car', 'Code':'code'}, inplace=True) In [70]: df[['show_date', 'time_available']] = df.ShowTime.str.split(' ', expand=True) In [71]: df.drop('ShowTime', axis=1, inplace=True) In [72]: df Out[72]: id car code show_date time_available 0 1 Honda A 10/18/2017 14:45 1 1 Honda A 10/18/2017 17:10 2 3 Honda C 10/18/2017 19:35 3 4 Toyota B 10/18/2017 12:20 4 4 Toyota B 10/18/2017 14:45 ``` `groupby` columns with categorical values and convert 'time\_available' column to list on the grouped dataframe: ``` In [134]: df_grp = df.groupby(['id', 'car','code', 'show_date']) In [136]: df_grp_time_stacked = df_grp['time_available'].apply(list).reset_index() In [138]: df_grp_time_stacked Out[138]: id car code show_date time_available 0 1 Honda A 10/18/2017 [14:45, 17:10] 1 3 Honda C 10/18/2017 [19:35] 2 4 Toyota B 10/18/2017 [12:20, 14:45] In [139]: df_grp_time_stacked['time_available'] = df_grp_time_stacked['time_available'].apply(lambda x:x[0] if (len(x)= ...: =1) else x) In [140]: df_grp_time_stacked Out[140]: id car code show_date time_available 0 1 Honda A 10/18/2017 [14:45, 17:10] 1 3 Honda C 10/18/2017 19:35 2 4 Toyota B 10/18/2017 [12:20, 14:45] ``` Now convert the dataframe to dict: ``` In [165]: raw_dict = df_grp_time_stacked.to_dict(orient='records') In [166]: data = {'data':raw_dict} In [167]: data Out[167]: {'data': [{'id': 1, 'car': 'Honda', 'code': 'A', 'show_date': '10/18/2017', 'time_available': ['14:45', '17:10']}, {'id': 3, 'car': 'Honda', 'code': 'C', 'show_date': '10/18/2017', 'time_available': '19:35'}, {'id': 4, 'car': 'Toyota', 'code': 'B', 'show_date': '10/18/2017', 'time_available': ['12:20', '14:45']}]} ```
You can use the simple setdefault() dictionary method, too: ``` tbl=['1 Honda A 10/18/2017 14:45', '1 Honda A 10/18/2017 17:10', '3 Honda C 10/18/2017 19:35', '4 Toyota B 10/18/2017 12:20', '4 Toyota B 10/18/2017 14:45'] data={} for line in tbl: iden,car,code,show_date,time_available= line.split() data.setdefault( (iden,car,code), {'id':iden,'schedule': {'car':car,'show_date':show_date,'time_available':[],'code':code}})['schedule']['time_available'].append(time_available); ``` We use the (iden,car,code) tuple as dictionary key. The 'setdefault' gets the value of the key if it is exists in the dict, if not, then creates and puts a default value in it. We create the default structure with an empty "time\_available' list, and as 'setdefault' returns the existing or the newly created value, we address that list and append the time value to. The result: ``` data.values() dict_values([{'id': '1', 'schedule': {'car': 'Honda', 'show_date': '10/18/2017', 'time_available': ['14:45', '17:10'], 'code': 'A'}}, {'id': '3', 'schedule': {'car': 'Honda', 'show_date': '10/18/2017', 'time_available': ['19:35'], 'code': 'C'}}, {'id': '4', 'schedule': {'car': 'Toyota', 'show_date': '10/18/2017', 'time_available': ['12:20', '14:45'], 'code': 'B'}}]) ```
59,125,318
I have problem with this code: ``` function get_request($url,$header_array){ $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => $header_array, )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { return $response; } } ``` I've got this error: ``` cURL Error #:Could not resolve host: ``` I know there are a lot of questions like this, but the answer from those questions didn't help me, because its different code. Does anyone can help me how to fix this error:
2019/12/01
['https://Stackoverflow.com/questions/59125318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
There's a few things this could be; and generally its either a malformed URL or a networking issue outside the scope of cURL. First, save yourself some time and just double and triple check you've typed the URL correctly. I do this time and time again =D Next up, on the same machine and under the same user as your PHP code executes, run something like `curl -sS http://yoururl.com/example` from the command line. This will help you double check your code can actually make outbound HTTP requests. If your curl command fails in bash, then you can look at a few causes depending on the errors: * a networking issue (has your local/dev machine lost internet connectivity?) * a firewall issue; is your firewall configured to allow inbound HTTP(s) and not outbound? * is it a DNS issue (my favourite!). If the domain is new, perhaps it hasn't proposed to your server's upstream DNS yet. At this point, your question turns from curl to networking and DNS so I don't dive deeper into debugging... but this is, at least, where I'd start in looking into your error message.
reading the symptoms, it is possible the DNS resolver that you use is probably too busy (timeout) -or- limit the number of inquiry per IP address in a certain timespan. So, the same exact process will probably give a different error if run on a different day.
3,835,971
Assuming the Hudson job checks out 2 SVN directories: ``` https://foo.com/packages (root is https://foo.com/packages) -> "packages" in workspace https://bar.com/temp/Hudson (root is https://bar.com/temp) -> "Hudson" in workspace ``` I tried different things, browsed online for answers, but I still can't get these 2 things to work: 1) Prevent any commit in "Hudson" from triggering a build: I tried several path combinations in "Excluded Regions" without success. 2) Prevent any commit containing "CR:" in the message from triggering a build: I tried "\bCR:\b" and others in the "Excluded Commit Messages" field, but it doesn't work. Thanks!
2010/10/01
['https://Stackoverflow.com/questions/3835971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463432/']
Take a look at the [ADO.NET Performance Counters](http://msdn.microsoft.com/en-us/library/ms254503.aspx) related to pooling. Your described symptom is often an indication that you are leaking connections. Make sure all connections are disposed when you are finished with them, preferably by wrapping in an `using` statement.
here's some code to try the pool and then failover to unpooled: use this sub if a problem happens with the pool: ``` Public Sub OpenConn() Dim sTempCNString As String = cn.ConnectionString Try ' add a timeout to the cn string, following http://www.15seconds.com/issue/040830.htm Dim iTimeOut As Integer = utils_Configuration.Get_ConfigInt("DBConnectTimeout", 0) If (iTimeOut > 0 And Not cn.ConnectionString.ToLower.Contains("timeout")) Then Diagnostics.Debug.Print("<><><><><><><> SHORT CONNECT WITH POOLING <><><><><><><><><> ") cn.ConnectionString += ";Connect Timeout=" & iTimeOut.ToString() & ";" End If cn.Open() IsOperational = True Catch ex As Exception Diagnostics.Debug.Print("ERROR IN OPENING, try no pool") ' see http://www.15seconds.com/issue/040830.htm ' turn off pooling Diagnostics.Debug.Print("<><><><><><><> CONNECT WITHOUT POOLING <><><><><><><><><> ") Dim sAddOn As String = ";Pooling=false;Connect Timeout=45;" cn.ConnectionString = sTempCNString & sAddOn cn.ConnectionString = cn.ConnectionString.Replace(";;", ";") cn.Open() End Try End Sub ``` Here's some code to monitor the pool: ``` Option Explicit On Option Strict On Imports System.Data.SqlClient Imports System.Diagnostics Imports System.Runtime.InteropServices Imports Microsoft.VisualBasic ' ref: http://msdn2.microsoft.com/en-us/library/ms254503.aspx Public Class utils_SqlPerfMon Private PerfCounters(9) As PerformanceCounter Private connection As SqlConnection Public sConnectString As String = "" Public sResult As String = "" Public Sub New() sConnectString = Tools.GetMainDBConn().ConnectionString connection = New SqlConnection(sConnectString) Exec() End Sub Public Sub New(ByVal strC As String) sConnectString = strC connection = New SqlConnection(sConnectString) Exec() End Sub Public Sub Exec() Me.SetUpPerformanceCounters() Diagnostics.Debug.Print("Available Performance Counters:") ' Create the connections and display the results. Me.CreateConnectionsAndDisplayResults() End Sub Private Sub CreateConnectionsAndDisplayResults() ' List the Performance counters. WritePerformanceCounters() Dim connection1 As SqlConnection = New SqlConnection( _ Me.sConnectString) connection1.Open() Diagnostics.Debug.Print("Opened the 1st Connection:") WritePerformanceCounters() connection1.Close() Diagnostics.Debug.Print("Closed the 1st Connection:") WritePerformanceCounters() Return End Sub Private Enum ADO_Net_Performance_Counters NumberOfActiveConnectionPools NumberOfReclaimedConnections HardConnectsPerSecond HardDisconnectsPerSecond NumberOfActiveConnectionPoolGroups NumberOfInactiveConnectionPoolGroups NumberOfInactiveConnectionPools NumberOfNonPooledConnections NumberOfPooledConnections NumberOfStasisConnections ' The following performance counters are more expensive to track. ' Enable ConnectionPoolPerformanceCounterDetail in your config file. ' SoftConnectsPerSecond ' SoftDisconnectsPerSecond ' NumberOfActiveConnections ' NumberOfFreeConnections End Enum Private Sub SetUpPerformanceCounters() connection.Close() Me.PerfCounters(9) = New PerformanceCounter() Dim instanceName As String = GetInstanceName() Dim apc As Type = GetType(ADO_Net_Performance_Counters) Dim i As Integer = 0 Dim s As String = "" For Each s In [Enum].GetNames(apc) Me.PerfCounters(i) = New PerformanceCounter() Me.PerfCounters(i).CategoryName = ".NET Data Provider for SqlServer" Me.PerfCounters(i).CounterName = s Me.PerfCounters(i).InstanceName = instanceName i = (i + 1) Next End Sub Private Declare Function GetCurrentProcessId Lib "kernel32.dll" () As Integer Private Function GetInstanceName() As String 'This works for Winforms apps. 'Dim instanceName As String = _ ' System.Reflection.Assembly.GetEntryAssembly.GetName.Name ' Must replace special characters like (, ), #, /, \\ Dim instanceName As String = _ AppDomain.CurrentDomain.FriendlyName.ToString.Replace("(", "[") _ .Replace(")", "]").Replace("#", "_").Replace("/", "_").Replace("\\", "_") 'For ASP.NET applications your instanceName will be your CurrentDomain's 'FriendlyName. Replace the line above that sets the instanceName with this: 'instanceName = AppDomain.CurrentDomain.FriendlyName.ToString.Replace("(", "[") _ ' .Replace(")", "]").Replace("#", "_").Replace("/", "_").Replace("\\", "_") Dim pid As String = GetCurrentProcessId.ToString instanceName = (instanceName + ("[" & (pid & "]"))) Diagnostics.Debug.Print("Instance Name: {0}", instanceName) Diagnostics.Debug.Print("---------------------------") Return instanceName End Function Private Sub WritePerformanceCounters() Dim sdelim As String = vbCrLf ' "<br>" Diagnostics.Debug.Print("---------------------------") sResult += "---------------------------" sResult += sdelim Dim strTemp As String = "" For Each p As PerformanceCounter In Me.PerfCounters Try Diagnostics.Debug.Print("{0} = {1}", p.CounterName, p.NextValue) strTemp = p.CounterName & "=" & p.NextValue.ToString Catch ex As Exception strTemp = "" End Try sResult += strTemp sResult += sdelim Next Diagnostics.Debug.Print("---------------------------") sResult += "---------------------------" sResult += sdelim End Sub Private Shared Function GetSqlConnectionStringDifferent() As String ' To avoid storing the connection string in your code, ' you can retrive it from a configuration file. Return ("Initial Catalog=AdventureWorks;Data Source=.\SqlExpress;" & _ "User Id=LowPriv;Password=Data!05;") End Function End Class ```
54,559,793
I started a new laravel project yesterday. Followed the guide from a guy in YouTube. Everything works until I installed laravel auth and realised none of the bootstrap dropdown works, even when i create new one from their website. Firstly, I thought I messed something up in composer, because I wanted to get rid of the bootstrap and later I changed my mind and put it back. Then I created new Laravel project and started from scratch again. Even then my dropdowns are not working. I checked for similar problems in google, but none of them helped.
2019/02/06
['https://Stackoverflow.com/questions/54559793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9034591/']
I had the same problem, it is happening because bootstrap has not been loaded properly and I simply solved it by pasting this link in `<head>` tag ``` <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"> ``` and paste this in the lower region of `<body>` tag ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script> ```
It seems that your bootstrap has not been loaded at all. Make sure that you include the bootstrap library in your view. If you are using WebPack, check if you are mixing the external libraries into one, and include that one in your main blade file.
54,559,793
I started a new laravel project yesterday. Followed the guide from a guy in YouTube. Everything works until I installed laravel auth and realised none of the bootstrap dropdown works, even when i create new one from their website. Firstly, I thought I messed something up in composer, because I wanted to get rid of the bootstrap and later I changed my mind and put it back. Then I created new Laravel project and started from scratch again. Even then my dropdowns are not working. I checked for similar problems in google, but none of them helped.
2019/02/06
['https://Stackoverflow.com/questions/54559793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9034591/']
By default, bootstrap.bundle.js is not included inside your Laravel app. To add this: Open `'resources/js/bootstrap.js'` file and add the following code at the last line of this file. ``` require('bootstrap/dist/js/bootstrap.bundle'); ``` Hit save and run `npm run dev` and it will work finally!
It seems that your bootstrap has not been loaded at all. Make sure that you include the bootstrap library in your view. If you are using WebPack, check if you are mixing the external libraries into one, and include that one in your main blade file.
54,559,793
I started a new laravel project yesterday. Followed the guide from a guy in YouTube. Everything works until I installed laravel auth and realised none of the bootstrap dropdown works, even when i create new one from their website. Firstly, I thought I messed something up in composer, because I wanted to get rid of the bootstrap and later I changed my mind and put it back. Then I created new Laravel project and started from scratch again. Even then my dropdowns are not working. I checked for similar problems in google, but none of them helped.
2019/02/06
['https://Stackoverflow.com/questions/54559793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9034591/']
It seems that your bootstrap has not been loaded at all. Make sure that you include the bootstrap library in your view. If you are using WebPack, check if you are mixing the external libraries into one, and include that one in your main blade file.
Sometimes you should change order of script links for that to work
54,559,793
I started a new laravel project yesterday. Followed the guide from a guy in YouTube. Everything works until I installed laravel auth and realised none of the bootstrap dropdown works, even when i create new one from their website. Firstly, I thought I messed something up in composer, because I wanted to get rid of the bootstrap and later I changed my mind and put it back. Then I created new Laravel project and started from scratch again. Even then my dropdowns are not working. I checked for similar problems in google, but none of them helped.
2019/02/06
['https://Stackoverflow.com/questions/54559793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9034591/']
I had the same problem, it is happening because bootstrap has not been loaded properly and I simply solved it by pasting this link in `<head>` tag ``` <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"> ``` and paste this in the lower region of `<body>` tag ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script> ```
Sometimes you should change order of script links for that to work
54,559,793
I started a new laravel project yesterday. Followed the guide from a guy in YouTube. Everything works until I installed laravel auth and realised none of the bootstrap dropdown works, even when i create new one from their website. Firstly, I thought I messed something up in composer, because I wanted to get rid of the bootstrap and later I changed my mind and put it back. Then I created new Laravel project and started from scratch again. Even then my dropdowns are not working. I checked for similar problems in google, but none of them helped.
2019/02/06
['https://Stackoverflow.com/questions/54559793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9034591/']
By default, bootstrap.bundle.js is not included inside your Laravel app. To add this: Open `'resources/js/bootstrap.js'` file and add the following code at the last line of this file. ``` require('bootstrap/dist/js/bootstrap.bundle'); ``` Hit save and run `npm run dev` and it will work finally!
Sometimes you should change order of script links for that to work
52,653,776
I've been successfully running the local development server daily and have made no changes except that I called "gcloud components update" just before it stopped working. Now I get: ``` ..snip... <<PATH TO MY SDK>>/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 518, in _parse_configuration with open(configuration_path) as f: IOError: [Errno 2] No such file or directory: 'app.yaml' ``` Of course app.yaml hasn't moved. Any thoughts?
2018/10/04
['https://Stackoverflow.com/questions/52653776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10458445/']
It looks like there's [an active issue on Google's issue tracker](https://issuetracker.google.com/117145272) (opened on Oct 2, 2018) pertaining to this: > > After updating to the Python (2.7) extensions for GAE to version > 1.9.76, I am no longer able to run my code with dev\_appserver.py > > > As of Oct 3, a fix appears to be in the works, but for now they suggest downgrading Google Cloud SDK to version 218.0.0: > > It seems like you are affected by a known issue regarding ‘dev\_appserver.py’ breaks in Google Cloud SDK version [219.0.1]. App Engine specialists are currently working to resolve it. However > there is no ETA at this moment. As a workaround you can downgrade the > Google Cloud SDK version using this command: > > > ``` gcloud components update --version 218.0.0 ``` The assignee of the issue will post an update on that issue when it has been resolved. **UPDATE (OCT 9, 2018):** Cloud SDK version 220.0.0, which fixes the dev\_appserver.py issue, is now available. I updated (via `gcloud components update`) and verified that it works. (Note: there are already a couple of complaints on the Issue Tracker that dev\_appserver.py takes too long to load now. I didn't notice a significant difference from version 218, but I didn't compare timings.)
`cd` to the directory with `app.yaml` in it and try again
52,653,776
I've been successfully running the local development server daily and have made no changes except that I called "gcloud components update" just before it stopped working. Now I get: ``` ..snip... <<PATH TO MY SDK>>/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 518, in _parse_configuration with open(configuration_path) as f: IOError: [Errno 2] No such file or directory: 'app.yaml' ``` Of course app.yaml hasn't moved. Any thoughts?
2018/10/04
['https://Stackoverflow.com/questions/52653776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10458445/']
You may create `make` file and have something like this: ``` export SDK=dev_appserver.py export APP_PATH=${CURDIR} run: $(SDK) $(APP_PATH)/path-to/app.yaml ``` And just use it with: `make run` so you don't have to worry about paths.
`cd` to the directory with `app.yaml` in it and try again
52,653,776
I've been successfully running the local development server daily and have made no changes except that I called "gcloud components update" just before it stopped working. Now I get: ``` ..snip... <<PATH TO MY SDK>>/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 518, in _parse_configuration with open(configuration_path) as f: IOError: [Errno 2] No such file or directory: 'app.yaml' ``` Of course app.yaml hasn't moved. Any thoughts?
2018/10/04
['https://Stackoverflow.com/questions/52653776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10458445/']
It looks like there's [an active issue on Google's issue tracker](https://issuetracker.google.com/117145272) (opened on Oct 2, 2018) pertaining to this: > > After updating to the Python (2.7) extensions for GAE to version > 1.9.76, I am no longer able to run my code with dev\_appserver.py > > > As of Oct 3, a fix appears to be in the works, but for now they suggest downgrading Google Cloud SDK to version 218.0.0: > > It seems like you are affected by a known issue regarding ‘dev\_appserver.py’ breaks in Google Cloud SDK version [219.0.1]. App Engine specialists are currently working to resolve it. However > there is no ETA at this moment. As a workaround you can downgrade the > Google Cloud SDK version using this command: > > > ``` gcloud components update --version 218.0.0 ``` The assignee of the issue will post an update on that issue when it has been resolved. **UPDATE (OCT 9, 2018):** Cloud SDK version 220.0.0, which fixes the dev\_appserver.py issue, is now available. I updated (via `gcloud components update`) and verified that it works. (Note: there are already a couple of complaints on the Issue Tracker that dev\_appserver.py takes too long to load now. I didn't notice a significant difference from version 218, but I didn't compare timings.)
You may create `make` file and have something like this: ``` export SDK=dev_appserver.py export APP_PATH=${CURDIR} run: $(SDK) $(APP_PATH)/path-to/app.yaml ``` And just use it with: `make run` so you don't have to worry about paths.
52,653,776
I've been successfully running the local development server daily and have made no changes except that I called "gcloud components update" just before it stopped working. Now I get: ``` ..snip... <<PATH TO MY SDK>>/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 518, in _parse_configuration with open(configuration_path) as f: IOError: [Errno 2] No such file or directory: 'app.yaml' ``` Of course app.yaml hasn't moved. Any thoughts?
2018/10/04
['https://Stackoverflow.com/questions/52653776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10458445/']
It looks like there's [an active issue on Google's issue tracker](https://issuetracker.google.com/117145272) (opened on Oct 2, 2018) pertaining to this: > > After updating to the Python (2.7) extensions for GAE to version > 1.9.76, I am no longer able to run my code with dev\_appserver.py > > > As of Oct 3, a fix appears to be in the works, but for now they suggest downgrading Google Cloud SDK to version 218.0.0: > > It seems like you are affected by a known issue regarding ‘dev\_appserver.py’ breaks in Google Cloud SDK version [219.0.1]. App Engine specialists are currently working to resolve it. However > there is no ETA at this moment. As a workaround you can downgrade the > Google Cloud SDK version using this command: > > > ``` gcloud components update --version 218.0.0 ``` The assignee of the issue will post an update on that issue when it has been resolved. **UPDATE (OCT 9, 2018):** Cloud SDK version 220.0.0, which fixes the dev\_appserver.py issue, is now available. I updated (via `gcloud components update`) and verified that it works. (Note: there are already a couple of complaints on the Issue Tracker that dev\_appserver.py takes too long to load now. I didn't notice a significant difference from version 218, but I didn't compare timings.)
On Windows, `dev_appserver.py %CD%` is enough if your .yaml file has the default `app.yaml` name. Otherwise `dev_appserver.py %CD%/your-file-name.yaml`
52,653,776
I've been successfully running the local development server daily and have made no changes except that I called "gcloud components update" just before it stopped working. Now I get: ``` ..snip... <<PATH TO MY SDK>>/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 518, in _parse_configuration with open(configuration_path) as f: IOError: [Errno 2] No such file or directory: 'app.yaml' ``` Of course app.yaml hasn't moved. Any thoughts?
2018/10/04
['https://Stackoverflow.com/questions/52653776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10458445/']
It looks like there's [an active issue on Google's issue tracker](https://issuetracker.google.com/117145272) (opened on Oct 2, 2018) pertaining to this: > > After updating to the Python (2.7) extensions for GAE to version > 1.9.76, I am no longer able to run my code with dev\_appserver.py > > > As of Oct 3, a fix appears to be in the works, but for now they suggest downgrading Google Cloud SDK to version 218.0.0: > > It seems like you are affected by a known issue regarding ‘dev\_appserver.py’ breaks in Google Cloud SDK version [219.0.1]. App Engine specialists are currently working to resolve it. However > there is no ETA at this moment. As a workaround you can downgrade the > Google Cloud SDK version using this command: > > > ``` gcloud components update --version 218.0.0 ``` The assignee of the issue will post an update on that issue when it has been resolved. **UPDATE (OCT 9, 2018):** Cloud SDK version 220.0.0, which fixes the dev\_appserver.py issue, is now available. I updated (via `gcloud components update`) and verified that it works. (Note: there are already a couple of complaints on the Issue Tracker that dev\_appserver.py takes too long to load now. I didn't notice a significant difference from version 218, but I didn't compare timings.)
This worked for me: in `app.yaml`, change `runtime: go` to `runtime: go111`
52,653,776
I've been successfully running the local development server daily and have made no changes except that I called "gcloud components update" just before it stopped working. Now I get: ``` ..snip... <<PATH TO MY SDK>>/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 518, in _parse_configuration with open(configuration_path) as f: IOError: [Errno 2] No such file or directory: 'app.yaml' ``` Of course app.yaml hasn't moved. Any thoughts?
2018/10/04
['https://Stackoverflow.com/questions/52653776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10458445/']
You may create `make` file and have something like this: ``` export SDK=dev_appserver.py export APP_PATH=${CURDIR} run: $(SDK) $(APP_PATH)/path-to/app.yaml ``` And just use it with: `make run` so you don't have to worry about paths.
On Windows, `dev_appserver.py %CD%` is enough if your .yaml file has the default `app.yaml` name. Otherwise `dev_appserver.py %CD%/your-file-name.yaml`
52,653,776
I've been successfully running the local development server daily and have made no changes except that I called "gcloud components update" just before it stopped working. Now I get: ``` ..snip... <<PATH TO MY SDK>>/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/application_configuration.py", line 518, in _parse_configuration with open(configuration_path) as f: IOError: [Errno 2] No such file or directory: 'app.yaml' ``` Of course app.yaml hasn't moved. Any thoughts?
2018/10/04
['https://Stackoverflow.com/questions/52653776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10458445/']
You may create `make` file and have something like this: ``` export SDK=dev_appserver.py export APP_PATH=${CURDIR} run: $(SDK) $(APP_PATH)/path-to/app.yaml ``` And just use it with: `make run` so you don't have to worry about paths.
This worked for me: in `app.yaml`, change `runtime: go` to `runtime: go111`
6,756,099
**Ooops, fiddle updated now correct** In this fiddle, <http://jsfiddle.net/SySRb/118/> once you click `.start` an element from an array is randomly chosen and assigned to variable `ran` This random selection jquery has been checked <http://jsfiddle.net/urfXq/96/> and is working so I don't think that's the problem, although people have suggested ways to make it more elegant. Continuing on... After the element from the array is assigned to `ran`, an if- then structure begins. The `if` is definitely false in this fiddle, so the `else` code should run. My intent with the else code is to add the div hash tag, and then do ran.show so that one of the two divs (hidden with css) on the page becomes visible. The else isn't working. If the if statement were true, I assume it wouldn't work either... ``` else { ran = ('# + ran'); $('ran').show(); //one of the two divs should show but they don't } }); ``` Note, because this is just a piece of larger code, if you totally restructure everything, I may not be able to use it...
2011/07/20
['https://Stackoverflow.com/questions/6756099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/577455/']
You are doing the string concatenation wrong.. use ``` ran = '#' + ran; $(ran).show(); ``` and you need to call your `test` method on `document.ready` so use ``` $(test); ``` Demo at <http://jsfiddle.net/gaby/SySRb/129/>
A few things: 1. You're forgetting to use `$` to query the DOM with jQuery. You should replace: ``` ran = ('# + ran'); ``` with ``` ran = $("#" + ran"); ``` That is, build a jQuery selector by appending `#` to `ran`, then call jQuery with that selector. 2. Since the variable you're saving the results of the jQuery call is called `ran`, you should replace ``` $('ran').show(); ``` with ``` ran.show(); ``` 3. Does the function `test()` ever get called? Part of the reason you're code isn't working is because that function is not getting called, so the click event is never bound. Wrap the entire thing in `$(document).ready(function () { ... })` and call `test()`. 4. Be sure to use `var` with your variable declarations. Otherwise, you're creating a global variable. Here's your example fixed up: <http://jsfiddle.net/andrewwhitaker/9BcUP/>
30,220,156
At the moment I'm trying to create my own WordPress blog with an own theme. It works really good so far but I have one problem: I use the skel.js and this tryes to load a css file. which can't be found because it looks under: > > /wp-admin/css/style.css > > > I'm really new to WordPress soI have no idea how I can tell the JS file that it has to look in the specific theme folder and there in the subfolder css?
2015/05/13
['https://Stackoverflow.com/questions/30220156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2047987/']
The following code should go in your functions file. Then your css should go into your css folder in your theme ``` function enqueue_additional_stylesheets() { // Register the style like this for a theme: wp_register_style( 'css_file', get_template_directory_uri() . '/css/yourfile.css', array(), '20150505', 'all' ); wp_enqueue_style( 'css_file' ); } add_action( 'wp_enqueue_scripts', 'enqueue_additional_stylesheets' ); ```
You can either modify the JS file (which may pose a problem when you do version updates), or you can put the CSS file where it's expected. The latter seems like a simple approach. You could also use an `@import` statement in style.css (at the expected location) to include the other file (at its current location). ``` @import '../themes/theme/subfolder/file.css'; ``` <https://developer.mozilla.org/en-US/docs/Web/CSS/@import>
1,021,071
I hope you can help me. I have 5 Public IP's in an subnet `186.121.200.X/29` I have `example.com` addressed to one of those public IPs, and some subdomains that point to the rest of them. Now, I have other 5 Public IP's in another subnet `190.181.15.Y/29` **My question is:** *Can I configure `example.com` to also point to an IP of the subnet `190.181.15.Y/29` ?* *How can I do it?* I have these configuration files: ``` (named.conf.options) options { directory "/var/cache/bind"; forwarders { // Google Public DNS (IPv4) 8.8.8.8; 8.8.4.4; // Google Public DNS (IPv6) 2001:4860:4860::8888; 2001:4860:4860::8844; // ADSL router 186.121.200.X; }; dnssec-validation auto; auth-nxdomain no; # conform to RFC1035 listen-on-v6 { any; }; }; (named.conf.local) zone "example.com" { type master; file "/etc/bind/db.direct"; allow-query { any; }; }; zone "206.121.186.in-addr.arpa" { type master; file "/etc/bind/db.reverse"; allow-query { any; }; }; (db.direct) $TTL 604800 @ IN SOA example.com. root.example.com. ( 11 ; Serial 604800 ; Refresh 86400 ; Retry 2419200 ; Expire 604800 ) ; Negative Cache TTL ; @ IN NS example.com. @ IN MX 10 mail @ IN A 186.121.206.X1 www IN A 186.121.206.X1 mail IN A 186.121.206.X2 subdomain1 IN A 186.121.206.X3 subdomain2 IN A 186.121.206.X4 subdomain3 IN A 186.121.206.X5 (db.reverse) $TTL 604800 @ IN SOA example.com. root.example.com. ( 8 ; Serial 604800 ; Refresh 86400 ; Retry 2419200 ; Expire 604800 ) ; Negative Cache TTL ; @ IN NS example.com. X1 IN PTR ns.example.com. X1 IN PTR www.example.com. X2 IN PTR mail.example.com. X3 IN PTR subdomain1.example.com. X4 IN PTR subdomain2.example.com. X5 IN PTR subdomain3.example.com. ``` EDIT: I have tried doing the following: ``` (db.direct) ... subdomain4 IN A 190.181.15.Y1 ``` ``` (db.reverse) ... Y1 IN PTR subdomain4.example.com. ``` When saving files and restarting bind, the subdomain responds to a ping. `ping subdomain4.example.com` `PING subdomain4.example.com (190.181.15.Y1) 56(84) bytes of data.` But when accessing subdomain by browser, it redirects to Public IP. It is not kept with the name of the subdomain. What is the problem?
2020/06/11
['https://serverfault.com/questions/1021071', 'https://serverfault.com', 'https://serverfault.com/users/578810/']
You can have multiple entries for any A record. You'd just add another entry with whatever additional IP(s) you want to the zone file.
If I'm not mistaking, you are trying to do: ``` subdomain1 IN A 186.121.206.X3 ``` Then point the reverse IP of: ``` 190.181.15.Y IN PTR subdomain1.example.com. ``` Based on my experience, the organization who had received the direct IP allocation from ARIN, APNIC, AFRINIC, RIPE (regional IP registrant organization) is able to create a PTR record for the IP address that they received from their regional IP registrant. I do not believe any regional IP registrant ever provided IPs that are smaller than a class C (/24). So, you can do below (multiple A records for the same subdomain), but the result IP when looking up subdomain1.example.com is randomly selected ``` subdomain1 IN A 186.121.206.X3 subdomain1 IN A 190.181.15.Y3 ``` Unless you own 190.181.15.Y, even though you create PTR record like below for the IPs, those PTR records more likely won't be available publicly unless on a rare situation that the owner of the IPs provided you an option to create PTR records for their IP address: ``` 15.181.190.in-addr.arpa. IN SOA ns.example.com. Y3 IN PTR subdomain1.example.com. ```
1,021,071
I hope you can help me. I have 5 Public IP's in an subnet `186.121.200.X/29` I have `example.com` addressed to one of those public IPs, and some subdomains that point to the rest of them. Now, I have other 5 Public IP's in another subnet `190.181.15.Y/29` **My question is:** *Can I configure `example.com` to also point to an IP of the subnet `190.181.15.Y/29` ?* *How can I do it?* I have these configuration files: ``` (named.conf.options) options { directory "/var/cache/bind"; forwarders { // Google Public DNS (IPv4) 8.8.8.8; 8.8.4.4; // Google Public DNS (IPv6) 2001:4860:4860::8888; 2001:4860:4860::8844; // ADSL router 186.121.200.X; }; dnssec-validation auto; auth-nxdomain no; # conform to RFC1035 listen-on-v6 { any; }; }; (named.conf.local) zone "example.com" { type master; file "/etc/bind/db.direct"; allow-query { any; }; }; zone "206.121.186.in-addr.arpa" { type master; file "/etc/bind/db.reverse"; allow-query { any; }; }; (db.direct) $TTL 604800 @ IN SOA example.com. root.example.com. ( 11 ; Serial 604800 ; Refresh 86400 ; Retry 2419200 ; Expire 604800 ) ; Negative Cache TTL ; @ IN NS example.com. @ IN MX 10 mail @ IN A 186.121.206.X1 www IN A 186.121.206.X1 mail IN A 186.121.206.X2 subdomain1 IN A 186.121.206.X3 subdomain2 IN A 186.121.206.X4 subdomain3 IN A 186.121.206.X5 (db.reverse) $TTL 604800 @ IN SOA example.com. root.example.com. ( 8 ; Serial 604800 ; Refresh 86400 ; Retry 2419200 ; Expire 604800 ) ; Negative Cache TTL ; @ IN NS example.com. X1 IN PTR ns.example.com. X1 IN PTR www.example.com. X2 IN PTR mail.example.com. X3 IN PTR subdomain1.example.com. X4 IN PTR subdomain2.example.com. X5 IN PTR subdomain3.example.com. ``` EDIT: I have tried doing the following: ``` (db.direct) ... subdomain4 IN A 190.181.15.Y1 ``` ``` (db.reverse) ... Y1 IN PTR subdomain4.example.com. ``` When saving files and restarting bind, the subdomain responds to a ping. `ping subdomain4.example.com` `PING subdomain4.example.com (190.181.15.Y1) 56(84) bytes of data.` But when accessing subdomain by browser, it redirects to Public IP. It is not kept with the name of the subdomain. What is the problem?
2020/06/11
['https://serverfault.com/questions/1021071', 'https://serverfault.com', 'https://serverfault.com/users/578810/']
You can add multiple ip addresses for a single record in a zone, but you can't control (without additional resources) which ip will be resolved for each request, there'll be random resolutions (e: for two ip addresses, 50% of possibilities for each one)
If I'm not mistaking, you are trying to do: ``` subdomain1 IN A 186.121.206.X3 ``` Then point the reverse IP of: ``` 190.181.15.Y IN PTR subdomain1.example.com. ``` Based on my experience, the organization who had received the direct IP allocation from ARIN, APNIC, AFRINIC, RIPE (regional IP registrant organization) is able to create a PTR record for the IP address that they received from their regional IP registrant. I do not believe any regional IP registrant ever provided IPs that are smaller than a class C (/24). So, you can do below (multiple A records for the same subdomain), but the result IP when looking up subdomain1.example.com is randomly selected ``` subdomain1 IN A 186.121.206.X3 subdomain1 IN A 190.181.15.Y3 ``` Unless you own 190.181.15.Y, even though you create PTR record like below for the IPs, those PTR records more likely won't be available publicly unless on a rare situation that the owner of the IPs provided you an option to create PTR records for their IP address: ``` 15.181.190.in-addr.arpa. IN SOA ns.example.com. Y3 IN PTR subdomain1.example.com. ```
9,693,323
I have a lot of static IF statements that I need to use to build a page. How would I add this to the view itself (not the controller.) **Example:** view: test.chtml ``` @{ if (!Request.Browser.IsMobileDevice) { <p>Write this to html</p> } } ``` I am not sure which html helper I should use to make this write to the page.
2012/03/13
['https://Stackoverflow.com/questions/9693323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/719825/']
There is no such `HTML-Helper`, So your doing it the right way allready!(Ask for a salary raise...) Just remove the `{}` as this code isn't a *"code block"*: ``` @if (!Request.Browser.IsMobileDevice) { <p>Write this to html</p> } ``` [C# Razor Syntax Quick Reference](http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx)
Razor has a native if statement: `@if` does what you want. You might be interested in the following two links: [ASP.Net's basic guide to writing views with Razor](http://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax) [Phil Haack's concise syntax guide for Razor](http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx)
9,693,323
I have a lot of static IF statements that I need to use to build a page. How would I add this to the view itself (not the controller.) **Example:** view: test.chtml ``` @{ if (!Request.Browser.IsMobileDevice) { <p>Write this to html</p> } } ``` I am not sure which html helper I should use to make this write to the page.
2012/03/13
['https://Stackoverflow.com/questions/9693323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/719825/']
if you go ``` @:<p>Write this to html</p> ``` this may work Although instead of putting it in a code block i perfer ``` @if (!Request.Browser.IsMobileDevice) { <p>Write this to html</p> } ```
There is no such `HTML-Helper`, So your doing it the right way allready!(Ask for a salary raise...) Just remove the `{}` as this code isn't a *"code block"*: ``` @if (!Request.Browser.IsMobileDevice) { <p>Write this to html</p> } ``` [C# Razor Syntax Quick Reference](http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx)
9,693,323
I have a lot of static IF statements that I need to use to build a page. How would I add this to the view itself (not the controller.) **Example:** view: test.chtml ``` @{ if (!Request.Browser.IsMobileDevice) { <p>Write this to html</p> } } ``` I am not sure which html helper I should use to make this write to the page.
2012/03/13
['https://Stackoverflow.com/questions/9693323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/719825/']
if you go ``` @:<p>Write this to html</p> ``` this may work Although instead of putting it in a code block i perfer ``` @if (!Request.Browser.IsMobileDevice) { <p>Write this to html</p> } ```
Razor has a native if statement: `@if` does what you want. You might be interested in the following two links: [ASP.Net's basic guide to writing views with Razor](http://www.asp.net/web-pages/tutorials/basics/2-introduction-to-asp-net-web-programming-using-the-razor-syntax) [Phil Haack's concise syntax guide for Razor](http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx)
584,870
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected" ``` //import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.Vector; public class DataBase { public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } // 2.open a data source name by means of the jdbcodbcdriver. static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin"); Statement stmt = con.createStatement(); // Shut off autocommit con.setAutoCommit(false); System.out.println("1.Insert 2.Delete 3.Update 4.Select"); Scanner s = new Scanner(System.in); int x; x = s.nextInt(); String query; // SQL select string ResultSet rs; // SQL query results boolean more; // "more rows found" switch String v1, v2; // Temporary storage results Vector<Object> results = new Vector<Object>(10); if (x == 1) { try { stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) "); } catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();} } if (x == 2) { try { stmt.executeUpdate("DELETE from employee where emp_id='102' "); }catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } if (x == 3) { try { stmt .executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; "); } catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } query = "SELECT * FROM employee "; try { rs = stmt.executeQuery(query); // Check to see if any rows were read more = rs.next(); if (!more) { System.out.println("No rows found."); return; } // Loop through the rows retrieved from the query while (more) { v1 = "ID: " + rs.getInt("emp_id"); v2 = "Name: " + rs.getString("emp_name"); System.out.println(v1); System.out.println(v2); System.out.println(""); results.addElement(v1 + "\n" + v2 + "\n"); more = rs.next(); } rs.close(); } catch (SQLException e) { System.out.println("" + results.size() + "results where found."); } finally{stmt.close();} } public static void main(String[] args) throws SQLException { String str = "y"; do { DataBase s = new DataBase(); s.LoadDriver(); DataBase.connect(); Scanner sc = new Scanner(System.in); System.out.println("DO u Want to PROCEED TO QUERY : "); str = sc.next(); } while (str !="n"); } } ```
2009/02/25
['https://Stackoverflow.com/questions/584870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql. then ``` public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin"); Statement stmt = con.createStatement(); ... ```
Just from looking at the exception.. I would guess that you are not specifying the database. How can you do a select on a table without telling it which schema to select from ? This is typically set in the connection string..
584,870
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected" ``` //import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.Vector; public class DataBase { public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } // 2.open a data source name by means of the jdbcodbcdriver. static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin"); Statement stmt = con.createStatement(); // Shut off autocommit con.setAutoCommit(false); System.out.println("1.Insert 2.Delete 3.Update 4.Select"); Scanner s = new Scanner(System.in); int x; x = s.nextInt(); String query; // SQL select string ResultSet rs; // SQL query results boolean more; // "more rows found" switch String v1, v2; // Temporary storage results Vector<Object> results = new Vector<Object>(10); if (x == 1) { try { stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) "); } catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();} } if (x == 2) { try { stmt.executeUpdate("DELETE from employee where emp_id='102' "); }catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } if (x == 3) { try { stmt .executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; "); } catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } query = "SELECT * FROM employee "; try { rs = stmt.executeQuery(query); // Check to see if any rows were read more = rs.next(); if (!more) { System.out.println("No rows found."); return; } // Loop through the rows retrieved from the query while (more) { v1 = "ID: " + rs.getInt("emp_id"); v2 = "Name: " + rs.getString("emp_name"); System.out.println(v1); System.out.println(v2); System.out.println(""); results.addElement(v1 + "\n" + v2 + "\n"); more = rs.next(); } rs.close(); } catch (SQLException e) { System.out.println("" + results.size() + "results where found."); } finally{stmt.close();} } public static void main(String[] args) throws SQLException { String str = "y"; do { DataBase s = new DataBase(); s.LoadDriver(); DataBase.connect(); Scanner sc = new Scanner(System.in); System.out.println("DO u Want to PROCEED TO QUERY : "); str = sc.next(); } while (str !="n"); } } ```
2009/02/25
['https://Stackoverflow.com/questions/584870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Just from looking at the exception.. I would guess that you are not specifying the database. How can you do a select on a table without telling it which schema to select from ? This is typically set in the connection string..
Found a [bug listing at MySQL](http://bugs.mysql.com/bug.php?id=3920) that gives this error but with different technologies. However, in the description it indicates that it is related to reauthorization not sending the database information, so perhaps that is what you are encountering here as well. Some things that stick out as odd to me (although no clue if they will have any impact on your error) * You only need to load the Driver Manager once * You aren't closing your connection, so either close it or refactor to use the same one. Perhaps move these two lines to just before the `do` loop ``` DataBase s = new DataBase(); s.LoadDriver(); ```
584,870
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected" ``` //import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.Vector; public class DataBase { public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } // 2.open a data source name by means of the jdbcodbcdriver. static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin"); Statement stmt = con.createStatement(); // Shut off autocommit con.setAutoCommit(false); System.out.println("1.Insert 2.Delete 3.Update 4.Select"); Scanner s = new Scanner(System.in); int x; x = s.nextInt(); String query; // SQL select string ResultSet rs; // SQL query results boolean more; // "more rows found" switch String v1, v2; // Temporary storage results Vector<Object> results = new Vector<Object>(10); if (x == 1) { try { stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) "); } catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();} } if (x == 2) { try { stmt.executeUpdate("DELETE from employee where emp_id='102' "); }catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } if (x == 3) { try { stmt .executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; "); } catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } query = "SELECT * FROM employee "; try { rs = stmt.executeQuery(query); // Check to see if any rows were read more = rs.next(); if (!more) { System.out.println("No rows found."); return; } // Loop through the rows retrieved from the query while (more) { v1 = "ID: " + rs.getInt("emp_id"); v2 = "Name: " + rs.getString("emp_name"); System.out.println(v1); System.out.println(v2); System.out.println(""); results.addElement(v1 + "\n" + v2 + "\n"); more = rs.next(); } rs.close(); } catch (SQLException e) { System.out.println("" + results.size() + "results where found."); } finally{stmt.close();} } public static void main(String[] args) throws SQLException { String str = "y"; do { DataBase s = new DataBase(); s.LoadDriver(); DataBase.connect(); Scanner sc = new Scanner(System.in); System.out.println("DO u Want to PROCEED TO QUERY : "); str = sc.next(); } while (str !="n"); } } ```
2009/02/25
['https://Stackoverflow.com/questions/584870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Just from looking at the exception.. I would guess that you are not specifying the database. How can you do a select on a table without telling it which schema to select from ? This is typically set in the connection string..
Is the ODBC source actually set up to select a database? eg. can you access the database through another ODBC client tool? If you need to select a database explicitly in the JDBC string you can do that using the ‘database’ parameter. But having the database chosen in the ODBC setup would be more usual. And indeed, as Clint mentioned, using the normal MySQL JDBC driver instead of ODBC would be more usual still. > > while (str !="n") > > > [That's not how you compare strings in Java.](http://www.owasp.org/index.php/Java_gotchas#Equality)
584,870
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected" ``` //import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.Vector; public class DataBase { public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } // 2.open a data source name by means of the jdbcodbcdriver. static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin"); Statement stmt = con.createStatement(); // Shut off autocommit con.setAutoCommit(false); System.out.println("1.Insert 2.Delete 3.Update 4.Select"); Scanner s = new Scanner(System.in); int x; x = s.nextInt(); String query; // SQL select string ResultSet rs; // SQL query results boolean more; // "more rows found" switch String v1, v2; // Temporary storage results Vector<Object> results = new Vector<Object>(10); if (x == 1) { try { stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) "); } catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();} } if (x == 2) { try { stmt.executeUpdate("DELETE from employee where emp_id='102' "); }catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } if (x == 3) { try { stmt .executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; "); } catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } query = "SELECT * FROM employee "; try { rs = stmt.executeQuery(query); // Check to see if any rows were read more = rs.next(); if (!more) { System.out.println("No rows found."); return; } // Loop through the rows retrieved from the query while (more) { v1 = "ID: " + rs.getInt("emp_id"); v2 = "Name: " + rs.getString("emp_name"); System.out.println(v1); System.out.println(v2); System.out.println(""); results.addElement(v1 + "\n" + v2 + "\n"); more = rs.next(); } rs.close(); } catch (SQLException e) { System.out.println("" + results.size() + "results where found."); } finally{stmt.close();} } public static void main(String[] args) throws SQLException { String str = "y"; do { DataBase s = new DataBase(); s.LoadDriver(); DataBase.connect(); Scanner sc = new Scanner(System.in); System.out.println("DO u Want to PROCEED TO QUERY : "); str = sc.next(); } while (str !="n"); } } ```
2009/02/25
['https://Stackoverflow.com/questions/584870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql. then ``` public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin"); Statement stmt = con.createStatement(); ... ```
Found a [bug listing at MySQL](http://bugs.mysql.com/bug.php?id=3920) that gives this error but with different technologies. However, in the description it indicates that it is related to reauthorization not sending the database information, so perhaps that is what you are encountering here as well. Some things that stick out as odd to me (although no clue if they will have any impact on your error) * You only need to load the Driver Manager once * You aren't closing your connection, so either close it or refactor to use the same one. Perhaps move these two lines to just before the `do` loop ``` DataBase s = new DataBase(); s.LoadDriver(); ```
584,870
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected" ``` //import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.Vector; public class DataBase { public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } // 2.open a data source name by means of the jdbcodbcdriver. static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin"); Statement stmt = con.createStatement(); // Shut off autocommit con.setAutoCommit(false); System.out.println("1.Insert 2.Delete 3.Update 4.Select"); Scanner s = new Scanner(System.in); int x; x = s.nextInt(); String query; // SQL select string ResultSet rs; // SQL query results boolean more; // "more rows found" switch String v1, v2; // Temporary storage results Vector<Object> results = new Vector<Object>(10); if (x == 1) { try { stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) "); } catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();} } if (x == 2) { try { stmt.executeUpdate("DELETE from employee where emp_id='102' "); }catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } if (x == 3) { try { stmt .executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; "); } catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } query = "SELECT * FROM employee "; try { rs = stmt.executeQuery(query); // Check to see if any rows were read more = rs.next(); if (!more) { System.out.println("No rows found."); return; } // Loop through the rows retrieved from the query while (more) { v1 = "ID: " + rs.getInt("emp_id"); v2 = "Name: " + rs.getString("emp_name"); System.out.println(v1); System.out.println(v2); System.out.println(""); results.addElement(v1 + "\n" + v2 + "\n"); more = rs.next(); } rs.close(); } catch (SQLException e) { System.out.println("" + results.size() + "results where found."); } finally{stmt.close();} } public static void main(String[] args) throws SQLException { String str = "y"; do { DataBase s = new DataBase(); s.LoadDriver(); DataBase.connect(); Scanner sc = new Scanner(System.in); System.out.println("DO u Want to PROCEED TO QUERY : "); str = sc.next(); } while (str !="n"); } } ```
2009/02/25
['https://Stackoverflow.com/questions/584870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql. then ``` public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin"); Statement stmt = con.createStatement(); ... ```
Is the ODBC source actually set up to select a database? eg. can you access the database through another ODBC client tool? If you need to select a database explicitly in the JDBC string you can do that using the ‘database’ parameter. But having the database chosen in the ODBC setup would be more usual. And indeed, as Clint mentioned, using the normal MySQL JDBC driver instead of ODBC would be more usual still. > > while (str !="n") > > > [That's not how you compare strings in Java.](http://www.owasp.org/index.php/Java_gotchas#Equality)
584,870
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected" ``` //import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; import java.util.Vector; public class DataBase { public void LoadDriver() { // Load the JDBC-ODBC bridge driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ee) { ee.printStackTrace(); } } // 2.open a data source name by means of the jdbcodbcdriver. static void connect() throws SQLException { // Connect to the database Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin"); Statement stmt = con.createStatement(); // Shut off autocommit con.setAutoCommit(false); System.out.println("1.Insert 2.Delete 3.Update 4.Select"); Scanner s = new Scanner(System.in); int x; x = s.nextInt(); String query; // SQL select string ResultSet rs; // SQL query results boolean more; // "more rows found" switch String v1, v2; // Temporary storage results Vector<Object> results = new Vector<Object>(10); if (x == 1) { try { stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) "); } catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();} } if (x == 2) { try { stmt.executeUpdate("DELETE from employee where emp_id='102' "); }catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } if (x == 3) { try { stmt .executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; "); } catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();} } query = "SELECT * FROM employee "; try { rs = stmt.executeQuery(query); // Check to see if any rows were read more = rs.next(); if (!more) { System.out.println("No rows found."); return; } // Loop through the rows retrieved from the query while (more) { v1 = "ID: " + rs.getInt("emp_id"); v2 = "Name: " + rs.getString("emp_name"); System.out.println(v1); System.out.println(v2); System.out.println(""); results.addElement(v1 + "\n" + v2 + "\n"); more = rs.next(); } rs.close(); } catch (SQLException e) { System.out.println("" + results.size() + "results where found."); } finally{stmt.close();} } public static void main(String[] args) throws SQLException { String str = "y"; do { DataBase s = new DataBase(); s.LoadDriver(); DataBase.connect(); Scanner sc = new Scanner(System.in); System.out.println("DO u Want to PROCEED TO QUERY : "); str = sc.next(); } while (str !="n"); } } ```
2009/02/25
['https://Stackoverflow.com/questions/584870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Is the ODBC source actually set up to select a database? eg. can you access the database through another ODBC client tool? If you need to select a database explicitly in the JDBC string you can do that using the ‘database’ parameter. But having the database chosen in the ODBC setup would be more usual. And indeed, as Clint mentioned, using the normal MySQL JDBC driver instead of ODBC would be more usual still. > > while (str !="n") > > > [That's not how you compare strings in Java.](http://www.owasp.org/index.php/Java_gotchas#Equality)
Found a [bug listing at MySQL](http://bugs.mysql.com/bug.php?id=3920) that gives this error but with different technologies. However, in the description it indicates that it is related to reauthorization not sending the database information, so perhaps that is what you are encountering here as well. Some things that stick out as odd to me (although no clue if they will have any impact on your error) * You only need to load the Driver Manager once * You aren't closing your connection, so either close it or refactor to use the same one. Perhaps move these two lines to just before the `do` loop ``` DataBase s = new DataBase(); s.LoadDriver(); ```
10,143,140
The HTML5 spec allows [form-associated elements](http://dev.w3.org/html5/spec/forms.html#form-associated-element) to refer to their [associated `<form>` element](http://dev.w3.org/html5/spec/association-of-controls-and-forms.html#attr-fae-form) via the `[form]` attribute. Do any browsers support this natively?
2012/04/13
['https://Stackoverflow.com/questions/10143140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497418/']
See: * <http://www.impressivewebs.com/html5-form-attribute/> * <http://swatelier.info/at/forms/HTML5attrib.asp> The `form` attribute is supported since Firefox 4, Opera 9.5, Safari 5.1 and Chrome 10, but not on IE yet. Here's a test page: <http://www.impressivewebs.com/demo-files/html5-form-attribute/>
> > Opera 9.5+, Safari 5.1+, Firefox 4+, Chrome 10+ > > >
10,143,140
The HTML5 spec allows [form-associated elements](http://dev.w3.org/html5/spec/forms.html#form-associated-element) to refer to their [associated `<form>` element](http://dev.w3.org/html5/spec/association-of-controls-and-forms.html#attr-fae-form) via the `[form]` attribute. Do any browsers support this natively?
2012/04/13
['https://Stackoverflow.com/questions/10143140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497418/']
See: * <http://www.impressivewebs.com/html5-form-attribute/> * <http://swatelier.info/at/forms/HTML5attrib.asp> The `form` attribute is supported since Firefox 4, Opera 9.5, Safari 5.1 and Chrome 10, but not on IE yet. Here's a test page: <http://www.impressivewebs.com/demo-files/html5-form-attribute/>
Chrome v25 does not seem to recognize the use of the form attribute. A form that contains an element that has "form='xxx'" in it will not show up in that form's submitted content if the form name/id does not match the value of the form attrib. Also if the form attrib contains two form names, it will not show up at all, even if one of the names matches the form's name/id. Strange behavior.
10,143,140
The HTML5 spec allows [form-associated elements](http://dev.w3.org/html5/spec/forms.html#form-associated-element) to refer to their [associated `<form>` element](http://dev.w3.org/html5/spec/association-of-controls-and-forms.html#attr-fae-form) via the `[form]` attribute. Do any browsers support this natively?
2012/04/13
['https://Stackoverflow.com/questions/10143140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497418/']
> > Opera 9.5+, Safari 5.1+, Firefox 4+, Chrome 10+ > > >
Chrome v25 does not seem to recognize the use of the form attribute. A form that contains an element that has "form='xxx'" in it will not show up in that form's submitted content if the form name/id does not match the value of the form attrib. Also if the form attrib contains two form names, it will not show up at all, even if one of the names matches the form's name/id. Strange behavior.
1,890,332
Hi I have been working on this problem and I don't understand my textbook's solution to this problem. Here is my textbook's solution to the problem: We have 1001 = 7\*11\*13 and the condition of the problem says 7\*11\*13\*k = 10^j - 10^i = (10^i)(10^(j-I) - 1). This implies 10^j-i = 1 (mod 1001) (and also (mod 7)). Since phi(7) = 6, by Euler's totient theorem, j-I = 0 (mod 6). If j-I = 6 we have 94 possibilities for j-I: 6-0, 7-1, ..., 99-93. If j-I = 12 we have 94-6 = 88 possibilities for j-I: 12-0, 13-1, ... , 99-87. The last case is j-I = 96 where we have 4 possibilities: 96-0, 97-1, 98-2, and 99-3. In total we have 94+88+82+...+10+4 = 16 \* (98/2) = 784 possibilities. I don't get how (10^i)(10^(j-I) - 1) implies 10^(j-I) = 1 (mod 1001) and (mod 7), or why my textbook used the totient function on 7, instead of 1001. I also don't quite understand their method for finding the different possibilities for j-I.
2016/08/12
['https://math.stackexchange.com/questions/1890332', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/360993/']
You have $7 \cdot 11 \cdot 13 \cdot k$ is a multiple of $1001$. You know $10^I$ is not a multiple of $1001$, so the other factor $10^{j-I}-1$ must be a multiple of $1001$ and hence of all its factors. The rest of the proof is incorrect but results in the correct answer. Euler's totient theorem says that $a^{\phi(n)} \equiv 1 \pmod n$ for $a$ coprime to $n$. As $7$ is prime, $\phi(7)=6$, so if $j-I$ is a multiple of $6, 10^{j-I}\equiv 1 \pmod 7$ What they say is $10^{j-I}\equiv 1 \pmod 7$ proves that $j-I$ must be a multiple of $6$. The book is reading the implication in the wrong direction. We can see the problem by looking at another factor of $1001,$ which is $11$. The book argument would also claim that we must have $j-I$ a multiple of $10$, but in fact working $\bmod 11$ only tells us that $j-I$ is even, which we knew already. We know that $10^6 \equiv 3^6 \equiv 1 \pmod 7$ but nothing in the argument shows that no lower power of $10$ is also $\equiv 1 \pmod 7$. That is what happens for $11$ and $13$, so all cases where $6|(j-I)$ result in $10^j-10^I$ being a multiple of $1001$
"I don't get how $(10^i)(10^{(j-I)} - 1)$ implies $10^{(j-I)} = 1 (\mod 1001)$ $1001k = 10^j - 10^i \iff 10^j - 10^i \equiv 0 \mod 1001$ So $10^{i}(10^{j-i}-1) \equiv 0 \mod 1001$. $\gcd(10^i, 1001) = \gcd(2^i\*5^i, 7\*11\*13) = 1$. So $10^{i}(10^{j-i}-1) \equiv 0 \mod 1001 \iff 10^{j-i} - 1 \equiv 1001 \iff 10^{j-i} \equiv 1 \mod 1001$ so $10^{j-1} - 1001k = 1$ so $10^{j-i} - 7(11\*13\*k) = 1$ so $10^{j-i} \equiv 1 \mod 7$. " and (mod 7), or why my textbook used the totient function on 7, instead of 1001"$ Because it's easier. $\phi(7) =6$ and $\phi(1001) = 720$. $6$ is an easier number to work with " I also don't quite understand their method for finding the different possibilities for j-I. " By Fermat's Little Theorem $10^{\phi(7) = 6} \equiv 1 \mod 7$. So if $10^{j-1} = 1 \mod 7$ then $j - i$ must be a multiple of $6$ (i.e. $j-i \equiv 0 \mod 6$). As $0 \le i < j \le 99$ then $1 \le j-i \le 99$. So $j-1 = 6;12;18;24;....;96$. If $j-i = 6$ then $i = j - 6$ as $1 \le j \le 99$ then $0 = 6-6 \le i \le 99 -6 = 93$. That is 94 = 100 - 6 possibilities. If $j-i = 12 = 6\*2$ then $i = j - 12$ and $0 \le i \le 99 -12 = 87$. That is $88 = 100 - 12 = 100 - 2\*6$ possibilities. If $j-i = 6\*k$ then $i = j - 6k$ and $0 \le i \le 99 - 6k$. That is $99 - 6k + 1 = 100 - 6k$ possibilities. Add these possibilities up: (100 - 6) + (100 - 12) + ...... + (100 - 96) That is $\sum\_{k=1}^16 (100 - 6k) = \sum\_{k=1}^16 100 - \sum\_{k=1}^16 6k = 16\*100 -6 \sum\_{k=1}^16 k = 1600 - 6\*\frac{16\*(16+1)}2$. ===== Actually though. I think your text is wrong. Although $1001|10^j - 10^i \implies 10^{j-i} \equiv 1 \mod 7$ (and also $1 \mod 11$ and $1 \mod 13$). $ \implies j - i \equiv 0 \mod 6$ (and also $0 \mod 10$ and $0 \mod 12$). It doesn't follow that $j-i \equiv 0 \mod 6 \implies 1001|10^j - 10^i$ (nor do $0 \mod 10$ or $0 \mod 12$ imply $1001|10^j - 10^i$). As it turns out $j - i \equiv 0 \mod 6$ does actually imply $10^{j-1} - 1 = 999...9$ a multiple of six nines. = $999\*1001\*(1000001000001.......000001)$. But that was a coincidence that 1001 = $10^3 + 1$ and $3|6$. It wouldn't follow $j-i \equiv 0 \mod 10$ implies $1001|10^j - 10^i$ as $10^{10} -1 = 9999999999 = 9\*11\*101010101= 9\*11\*101\* 10001= 9\*11\*101\*73\*137$ . So the proof is invalid. ==== Can anyone double check my reasoning?
1,890,332
Hi I have been working on this problem and I don't understand my textbook's solution to this problem. Here is my textbook's solution to the problem: We have 1001 = 7\*11\*13 and the condition of the problem says 7\*11\*13\*k = 10^j - 10^i = (10^i)(10^(j-I) - 1). This implies 10^j-i = 1 (mod 1001) (and also (mod 7)). Since phi(7) = 6, by Euler's totient theorem, j-I = 0 (mod 6). If j-I = 6 we have 94 possibilities for j-I: 6-0, 7-1, ..., 99-93. If j-I = 12 we have 94-6 = 88 possibilities for j-I: 12-0, 13-1, ... , 99-87. The last case is j-I = 96 where we have 4 possibilities: 96-0, 97-1, 98-2, and 99-3. In total we have 94+88+82+...+10+4 = 16 \* (98/2) = 784 possibilities. I don't get how (10^i)(10^(j-I) - 1) implies 10^(j-I) = 1 (mod 1001) and (mod 7), or why my textbook used the totient function on 7, instead of 1001. I also don't quite understand their method for finding the different possibilities for j-I.
2016/08/12
['https://math.stackexchange.com/questions/1890332', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/360993/']
You have $7 \cdot 11 \cdot 13 \cdot k$ is a multiple of $1001$. You know $10^I$ is not a multiple of $1001$, so the other factor $10^{j-I}-1$ must be a multiple of $1001$ and hence of all its factors. The rest of the proof is incorrect but results in the correct answer. Euler's totient theorem says that $a^{\phi(n)} \equiv 1 \pmod n$ for $a$ coprime to $n$. As $7$ is prime, $\phi(7)=6$, so if $j-I$ is a multiple of $6, 10^{j-I}\equiv 1 \pmod 7$ What they say is $10^{j-I}\equiv 1 \pmod 7$ proves that $j-I$ must be a multiple of $6$. The book is reading the implication in the wrong direction. We can see the problem by looking at another factor of $1001,$ which is $11$. The book argument would also claim that we must have $j-I$ a multiple of $10$, but in fact working $\bmod 11$ only tells us that $j-I$ is even, which we knew already. We know that $10^6 \equiv 3^6 \equiv 1 \pmod 7$ but nothing in the argument shows that no lower power of $10$ is also $\equiv 1 \pmod 7$. That is what happens for $11$ and $13$, so all cases where $6|(j-I)$ result in $10^j-10^I$ being a multiple of $1001$
Forgive the second answer but you book just gives the wrong reason. Instead here's the "pretty picture" way: $10^j - 10^i = 100000..... - 1000.... = 99999999.....90000.....$ where there are $j-i$ 9's and $i$ zeros. This is divisble by $1001$ only if $999...9 = 10^{j-i} -1$ is. So take some pencil and paper and do the problem $99999.... \div 1001$. If you do long division (try it) you get: $999000999000.....$ and this only divides evenly if and only if $j - i$ is a multiple of $6$. But that's a very informal proof. More formally we can do what your text does. $10^j - 10^i = (10^{j-i} - 1)10^i$. As $\gcd(10^i, 1001) = 1$, $1001|10^j - 10^i \iff 1001|10^{j-i}-1$. Your text shows that $1001|10^{j-i} - 1 \implies 10^{j-i} \equiv 1 \mod (7|11|13)$ But that's not enough to go the other way. The text is dead wrong about that. But let $k = j-i$. If $6|k$ so $k = 6n$ then we have $10^{6n} - 1 = (10^3+1)(10^{6k -3} - 10^{6k - 6}+....+10^9 - 10^6 + 10^3 - 1)= (1001)\*\sum\_{l=0}^{2k-1}(-1)^{l+1}10^{3k}$. So $10^3 +1|10^{6n} -1$. But are these the *only* answers? Well, yes. If $6 \not \mid k$ then by Fermat's Little theoem if $k \equiv l \mod 6; l \ne 0$ then $10^k \equiv 10^l \not \equiv 1 \mod 7$. So $10^k \not \equiv 1 \mod 1001$ and $1001 \not \mid 10^k - 1$ and $1001 \not \mid 10^j - 10^i$. Thus the text did get the right answer for the wrong reasons.
363,876
How can I use file command to know which language my file is written? File command use language tests to get the language file is written, but it seems it do not execute when first two tests - file type and magic number execute properly. How to check only the language a file is written in?
2017/05/09
['https://unix.stackexchange.com/questions/363876', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/230526/']
Maybe not very smart solution: * sort files by name * loop through names * compare characters of last loop: ``` last="" ls -1 $1 | sort | while read file; do sub=${file:0:3} [ "$last" != "$sub" ] && { echo "NEW GROUP"; last="$sub"; } echo "[$sub] $file" done ``` Instead of echo-ing collect filenames inside an array ... Just an idea ... example output: ``` NEW GROUP [Hi8] Hi8-01-002.avi NEW GROUP [VHS] VHS-01-001.avi [VHS] VHS-01-002.avi [VHS] VHS-02-002.avi NEW GROUP [XZU] XZU ``` Edit 1: based on [Anthony Geoghegan](https://unix.stackexchange.com/users/22812/anthony-geoghegan) 's answer avoid the pipes at the beginning of the loop and use bash globbing. Take a look at his comment. Improved script: ``` last="" for file in *avi; do sub=${file:0:3} [ "$last" != "$sub" ] && { echo "NEW GROUP"; last="$sub"; } echo "[$sub] $file" done ``` Edit 2: as asked by @ [Tony Tan](https://unix.stackexchange.com/users/115678/tony-tan) in his third comment: here you find a straigt forward solution to parse the collected file names to a function. There are many ways to do so. And I don't have much experience in bash scripting ... ;) ``` #!/bin/bash SOURCE_DIR="$1" cd "$SOURCE_DIR" || { echo "could not read dir '$SOURCE_DIR'"; exit 1; } function parseFiles() { echo "parsing files:" echo "$1" } last="" declare -a fileGroup for file in *avi; do # first 3 chars of filename sub=${file:0:3} if test -z "$last"; then # last is empty. first loop last="$sub" elif test "$last" != "$sub"; then # new file group detected, parse collected parseFiles "${fileGroup[*]}" # reset array fileGroup=() last="$sub" fi # append name to array fileGroup[${#fileGroup[@]}]=$file done parseFiles "${fileGroup[*]}" ```
With `zsh`: ``` files=(???-??-*.avi) for prefix (${(Mu)files#???-??-}) encode $prefix*.avi ``` (or `encode ${(M)files:#$prefix*}`) The equivalent with the GNU shell (`bash`) and tools would be: ``` while IFS= read -u3 -rd '' prefix; do encode "$prefix-"*.avi 3<&- done 3< <(printf '%s\0' ???-??-*.avi | grep -oz '^...-..-' | sort -zu) ``` Same principle. We get the list of files matching the `???-??-*.avi` pattern in the current directory, extract the part that matches (`(M)`/`grep -o`) `???-??-` (regexp `...-..-`), unique them (`(u)`/`sort -u`), and then loop over that list of prefixes.
13,216,224
I am using Xilinx and trying to compile this code. I am getting this error: **ERROR:HDLParsers:808 - "C:/Users/Dell/digi/sm.vhd" Line xx. and can not have such operands in this context.** [code is here](http://pastebin.com/JSmaE5dj)
2012/11/04
['https://Stackoverflow.com/questions/13216224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1416136/']
The problem is you are mixing bit and std\_logic types. You should generally pick one or the other (no using both in the same file unless you *REALLY* know why you need to), most new work is usually done using std\_logic. To fix the problem you need to make everything consistent...either change your inputs to bit types, as you did, or change your internal declared signals to std\_logic: ``` signal Q1, Q2, Q3: std_logic; ```
Changing the declaration of ports from ``` port(X1,X2,CLK: in STD_LOGIC; ``` to ``` port(X1,X2,CLK: in bit; ``` made it work. [Difference between the two](http://vhdlguru.blogspot.in/2010/03/what-is-difference-between-stdlogic-and.html)
268,491
When this exchange happens during the final batter in *Return of the Jedi* (1983), how was “north” determined within the structure of the Death Star? > > **LANDO:** There it is. All right, Wedge, go for the power regulator on the **north tower**. > > > **WEDGE:** Copy, Gold Leader. I'm already on my way out. > > >
2022/10/11
['https://scifi.stackexchange.com/questions/268491', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/140601/']
From *Star Wars: Complete Locations* (2016): [![Image from Star Wars: Complete Locations showing the Death Star II's polar column](https://i.stack.imgur.com/cZoP0.jpg)](https://i.stack.imgur.com/cZoP0.jpg) > > **1** The primary stage focused on assembling components necessary for construction of the main reactor core—approximately one-tenth the diameter of the entire structure—**and the immense cylindrical polar column**, which served to distribute power and stabilize the Death Star's rotational capabilities. > > > *Star Wars: Complete Locations* (2016), page 166, "Death Star II", emphasis added > > > In *Return of the Jedi*, we see the Rebels making their attack at the center of the area marked "Reactor core" on the diagram (indicated by hand-drawn red circle). Since it's connected to the "Polar column", the north tower is the tower connected to the north pole, which in space is less ambiguous than "the upper tower". The asymmetry is made clear in the hologram of the Death Star II in the Rebel briefing: [![Image from Return of the Jedi showing a hologram of the Death Star II's reactor core](https://i.stack.imgur.com/XOu5I.jpg)](https://i.stack.imgur.com/XOu5I.jpg) [![Image from Return of the Jedi showing the Death Star II's central reactor core](https://i.stack.imgur.com/HMbKI.png)](https://i.stack.imgur.com/HMbKI.png)
Artificial gravity in *Star Wars* works weirdly, compared to real world artificial gravity which requires the spaceship to rotate. *Star Wars* artificial gravity just picks a direction as 'down' and makes it work. This might be hard to observe in a small fighter like an X-wing, where the pilot is strapped to a chair. And it is hard to observe in a large spherical Death Star. But you can easily see how *Star Wars* artificial gravity works in a ship such as the Falcon - people walk around normally and stuff falls in the direction nominated as 'down'. It's worth noting, Lando doesn't use the word 'North'. He uses a word, phrase or concept in the language 'Galactic Basic', which is dubbed for the movie into whatever language is appropriate for the region the movie is released into. English people in the real world think of the Earth rotating with North "at the top", because that's where England is (and USA and Canada). It's where people first started drawing maps of the world. This "north = top and Australian's live upside down" concept has persisted through the development of air and space travel. When translating the movie into English, it therefore makes sense to have North be the bit at the top of the map, the bit at the highest gravitational potential energy. That leaves the south on the bottom of the death sta. It's unclear whether people in the Star Wars universe have a similar concept of 'Northern Hemisphere is on top and Southern Hemisphere is upside down', so we don't know what word they would use if we could see the 'Galactic Basic' version of *Star Wars*.
268,491
When this exchange happens during the final batter in *Return of the Jedi* (1983), how was “north” determined within the structure of the Death Star? > > **LANDO:** There it is. All right, Wedge, go for the power regulator on the **north tower**. > > > **WEDGE:** Copy, Gold Leader. I'm already on my way out. > > >
2022/10/11
['https://scifi.stackexchange.com/questions/268491', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/140601/']
From *Star Wars: Complete Locations* (2016): [![Image from Star Wars: Complete Locations showing the Death Star II's polar column](https://i.stack.imgur.com/cZoP0.jpg)](https://i.stack.imgur.com/cZoP0.jpg) > > **1** The primary stage focused on assembling components necessary for construction of the main reactor core—approximately one-tenth the diameter of the entire structure—**and the immense cylindrical polar column**, which served to distribute power and stabilize the Death Star's rotational capabilities. > > > *Star Wars: Complete Locations* (2016), page 166, "Death Star II", emphasis added > > > In *Return of the Jedi*, we see the Rebels making their attack at the center of the area marked "Reactor core" on the diagram (indicated by hand-drawn red circle). Since it's connected to the "Polar column", the north tower is the tower connected to the north pole, which in space is less ambiguous than "the upper tower". The asymmetry is made clear in the hologram of the Death Star II in the Rebel briefing: [![Image from Return of the Jedi showing a hologram of the Death Star II's reactor core](https://i.stack.imgur.com/XOu5I.jpg)](https://i.stack.imgur.com/XOu5I.jpg) [![Image from Return of the Jedi showing the Death Star II's central reactor core](https://i.stack.imgur.com/HMbKI.png)](https://i.stack.imgur.com/HMbKI.png)
The same way as on Earth: it's defined by convention. Specifically, the direction of spin of a body relative to the celestial background is a vector found with the right hand rule (or cross-products). That vector is "celestial north". This actually matters a great deal if you want to do orbital mechanics calculations, because it also defines which direction is positive (which you need t get correct if you're trying to launch into orbit from a spinning body). Here on Earth, you might have heard that magnetic north is slightly off from "true" north. The "true" north referenced there is the celestial pole. There is also an orbital north, which is normal to the orbit instead of to the spin. That's convenient for some things, but less convenient for establishing a reference system on an object. Here, Lando was almost certainly referencing celestial north, not orbital north.
22,902,486
I am having trouble with getting the JavaScript to do what I need it to. I have a form with a country drop down list that has United States or Other; then I have a State field with a list of all 50 states in the US; then I have a text field for people to put what country they live in if they don't live in the United States. What I want to be able to do is if United Sates is selected in the country drop down list I want the "other" text field to be disabled and the state drop down list enabled; then vice versa, if they select other, then the state drop down list is disabled and the "other" text field is enabled. Here is the HTML code: ``` <!DOCTYPE html> <html> <head> <script src="countryValidation.js"></script> </head> <body> <div id="form2"> <form name="createForm" onsubmit="return createValidation();" method="get"> <p>Country: <select id="country"> <option value="0">United States</option> <option value="1">Other</option> </select>&nbsp;*&nbsp;&nbsp;&nbsp;</p> <p>State: <select id="state"> <option value="0">- -Select state- -</option> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> <option value="California">California</option> <option value="Colorado">Colorado</option> <option value="Connecticut">Connecticut</option> <option value="Delaware">Delaware</option> <option value="Florida">Florida</option> <option value="Georgia">Georgia</option> <option value="Hawaii">Hawaii</option> <option value="Idaho">Idaho</option> <option value="Illinois">Illinois</option> <option value="Indiana">Indiana</option> <option value="Iowa">Iowa</option> <option value="Kansas">Kansas</option> <option value="Kentucky">Kentucky</option> <option value="Louisiana">Louisiana</option> <option value="Maine">Maine</option> <option value="Maryland">Maryland</option> <option value="Massachusetts">Massachusetts</option> <option value="Michigan">Michigan</option> <option value="Minnesota">Minnesota</option> <option value="Mississippi">Mississippi</option> <option value="Missouri">Missouri</option> <option value="Montana">Montana</option> <option value="Nebraska">Nebraska</option> <option value="Nevada">Nevada</option> <option value="New Hampshire">New Hampshire</option> <option value="New Jersey">New Jersey</option> <option value="New Mexico">New Mexico</option> <option value="New York">New York</option> <option value="North Carolina">North Carolina</option> <option value="North Dakota">North Dakota</option> <option value="Ohio">Ohio</option> <option value="Oklahoma">Oklahoma</option> <option value="Oregon">Oregon</option> <option value="Pennsylvania">Pennsylvania</option> <option value="Rhode Island">Rhode Island</option> <option value="South Carolina">South Carolina</option> <option value="South Dakota">South Dakota</option> <option value="Tennessee">Tennessee</option> <option value="Texas">Texas</option> <option value="Utah">Utah</option> <option value="Vermont">Vermont</option> <option value="Virginia">virginia</option> <option value="Washington">Washington</option> <option value="West Virginia">West Virginia</option> <option value="Wisconsin">Wisconsin</option> <option value="Wyoming">Wyoming</option> </select>&nbsp;*&nbsp;&nbsp;&nbsp;</p> <p>Please type in what country you live in: <input type="text" id="countryOther" />&nbsp;*&nbsp;&nbsp;&nbsp;</p> ``` And here is what I am trying to do with JavaScript: ``` function countryValidation () { var country = document.forms["createForm"]["country"].value; var countryOther = document.forms["createForm"]["countryOther"]; var state = document.forms["createForm"]["state"]; if (country == 0) { countryOther.createAttribute("disabled","disabled"); } else if (country == 1) { state.createAttribute("disabled","disabled"); countryOther.removeAttribute("disabled"); } } ``` I do have another JavaScript function that Validates the whole form, because it is a form that I will be using to allow people to create an account. I haven't gotten to the point of having an SQL server, nor have I learned SQL, PHP or ASP.net... I am doing this for a project and could really use some help with this problem. Thanks!
2014/04/07
['https://Stackoverflow.com/questions/22902486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2810473/']
You need to understand what `include` does. Literally everything in the "included" file will be put where you call that function. So in this case, you're putting practically an entire HTML document inside the `<head>` of another. headertop.php should likely only be: ``` <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="description" content="Slide Down Box Menu with jQuery and CSS3" /> <meta name="keywords" content="jquery, css3, sliding, box, menu, cube, navigation, portfolio, thumbnails"/> <link rel="shortcut icon" href="images/art_favicon.png" type="image/x-icon"/> <link rel="stylesheet" href="css/headertop.css" type="text/css" media="screen"/> ``` And the `<header>` tag does not belong in there at all. That needs to go in the body of your document.
It looks like you should delete everything outside of `<header>...</header>` from your headertop.php file. You already define the html and head tags in index.php so you don't need to do it again in headertop.php. However I'm not sure you really want your header block to be inside the page's head section. Shouldn't it be in body?
22,902,486
I am having trouble with getting the JavaScript to do what I need it to. I have a form with a country drop down list that has United States or Other; then I have a State field with a list of all 50 states in the US; then I have a text field for people to put what country they live in if they don't live in the United States. What I want to be able to do is if United Sates is selected in the country drop down list I want the "other" text field to be disabled and the state drop down list enabled; then vice versa, if they select other, then the state drop down list is disabled and the "other" text field is enabled. Here is the HTML code: ``` <!DOCTYPE html> <html> <head> <script src="countryValidation.js"></script> </head> <body> <div id="form2"> <form name="createForm" onsubmit="return createValidation();" method="get"> <p>Country: <select id="country"> <option value="0">United States</option> <option value="1">Other</option> </select>&nbsp;*&nbsp;&nbsp;&nbsp;</p> <p>State: <select id="state"> <option value="0">- -Select state- -</option> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> <option value="California">California</option> <option value="Colorado">Colorado</option> <option value="Connecticut">Connecticut</option> <option value="Delaware">Delaware</option> <option value="Florida">Florida</option> <option value="Georgia">Georgia</option> <option value="Hawaii">Hawaii</option> <option value="Idaho">Idaho</option> <option value="Illinois">Illinois</option> <option value="Indiana">Indiana</option> <option value="Iowa">Iowa</option> <option value="Kansas">Kansas</option> <option value="Kentucky">Kentucky</option> <option value="Louisiana">Louisiana</option> <option value="Maine">Maine</option> <option value="Maryland">Maryland</option> <option value="Massachusetts">Massachusetts</option> <option value="Michigan">Michigan</option> <option value="Minnesota">Minnesota</option> <option value="Mississippi">Mississippi</option> <option value="Missouri">Missouri</option> <option value="Montana">Montana</option> <option value="Nebraska">Nebraska</option> <option value="Nevada">Nevada</option> <option value="New Hampshire">New Hampshire</option> <option value="New Jersey">New Jersey</option> <option value="New Mexico">New Mexico</option> <option value="New York">New York</option> <option value="North Carolina">North Carolina</option> <option value="North Dakota">North Dakota</option> <option value="Ohio">Ohio</option> <option value="Oklahoma">Oklahoma</option> <option value="Oregon">Oregon</option> <option value="Pennsylvania">Pennsylvania</option> <option value="Rhode Island">Rhode Island</option> <option value="South Carolina">South Carolina</option> <option value="South Dakota">South Dakota</option> <option value="Tennessee">Tennessee</option> <option value="Texas">Texas</option> <option value="Utah">Utah</option> <option value="Vermont">Vermont</option> <option value="Virginia">virginia</option> <option value="Washington">Washington</option> <option value="West Virginia">West Virginia</option> <option value="Wisconsin">Wisconsin</option> <option value="Wyoming">Wyoming</option> </select>&nbsp;*&nbsp;&nbsp;&nbsp;</p> <p>Please type in what country you live in: <input type="text" id="countryOther" />&nbsp;*&nbsp;&nbsp;&nbsp;</p> ``` And here is what I am trying to do with JavaScript: ``` function countryValidation () { var country = document.forms["createForm"]["country"].value; var countryOther = document.forms["createForm"]["countryOther"]; var state = document.forms["createForm"]["state"]; if (country == 0) { countryOther.createAttribute("disabled","disabled"); } else if (country == 1) { state.createAttribute("disabled","disabled"); countryOther.removeAttribute("disabled"); } } ``` I do have another JavaScript function that Validates the whole form, because it is a form that I will be using to allow people to create an account. I haven't gotten to the point of having an SQL server, nor have I learned SQL, PHP or ASP.net... I am doing this for a project and could really use some help with this problem. Thanks!
2014/04/07
['https://Stackoverflow.com/questions/22902486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2810473/']
It looks like you should delete everything outside of `<header>...</header>` from your headertop.php file. You already define the html and head tags in index.php so you don't need to do it again in headertop.php. However I'm not sure you really want your header block to be inside the page's head section. Shouldn't it be in body?
You can do it like this. index.php ``` <!DOCTYPE html> <html> <head> <title>HOME</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="description" content="Slide Down Box Menu with jQuery and CSS3" /> <meta name="keywords" content="jquery, css3, sliding, box, menu, cube, navigation, portfolio, thumbnails"/> <link rel="shortcut icon" href="images/art_favicon.png" type="image/x- icon"/> <link rel="stylesheet" href="css/body.css" type="text/css" media="screen"/> <link rel="stylesheet" href="css/headertop.css" type="text/css" media="screen"/> <style> body{ background-image: url(images/graphy.png); font-family:Arial, Helvetica, sans-serif; margin: 0; padding: 0; } </style> <?php require_once("headertop.php"); ?> </head> <body> <div id="contents"> </div> </body> </html> ``` headertop.php ``` <header> <div id="headertop"> <div id="adams"> <p> <span style="color: #F60;">A</span>ncajas <span style="color: #F60;">D</span>igital <span style="color: #F60;">A</span>rts &amp; <span style="color: #F60;">M</span>edia <span style="color: #F60;">S</span>olutions </p> </div> </div> </header> ``` You don't need to have two same meta-tags or declared Doctype, head or body tag. And for sure, I suggest to you using `require_once`instead of `include`.
22,902,486
I am having trouble with getting the JavaScript to do what I need it to. I have a form with a country drop down list that has United States or Other; then I have a State field with a list of all 50 states in the US; then I have a text field for people to put what country they live in if they don't live in the United States. What I want to be able to do is if United Sates is selected in the country drop down list I want the "other" text field to be disabled and the state drop down list enabled; then vice versa, if they select other, then the state drop down list is disabled and the "other" text field is enabled. Here is the HTML code: ``` <!DOCTYPE html> <html> <head> <script src="countryValidation.js"></script> </head> <body> <div id="form2"> <form name="createForm" onsubmit="return createValidation();" method="get"> <p>Country: <select id="country"> <option value="0">United States</option> <option value="1">Other</option> </select>&nbsp;*&nbsp;&nbsp;&nbsp;</p> <p>State: <select id="state"> <option value="0">- -Select state- -</option> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> <option value="California">California</option> <option value="Colorado">Colorado</option> <option value="Connecticut">Connecticut</option> <option value="Delaware">Delaware</option> <option value="Florida">Florida</option> <option value="Georgia">Georgia</option> <option value="Hawaii">Hawaii</option> <option value="Idaho">Idaho</option> <option value="Illinois">Illinois</option> <option value="Indiana">Indiana</option> <option value="Iowa">Iowa</option> <option value="Kansas">Kansas</option> <option value="Kentucky">Kentucky</option> <option value="Louisiana">Louisiana</option> <option value="Maine">Maine</option> <option value="Maryland">Maryland</option> <option value="Massachusetts">Massachusetts</option> <option value="Michigan">Michigan</option> <option value="Minnesota">Minnesota</option> <option value="Mississippi">Mississippi</option> <option value="Missouri">Missouri</option> <option value="Montana">Montana</option> <option value="Nebraska">Nebraska</option> <option value="Nevada">Nevada</option> <option value="New Hampshire">New Hampshire</option> <option value="New Jersey">New Jersey</option> <option value="New Mexico">New Mexico</option> <option value="New York">New York</option> <option value="North Carolina">North Carolina</option> <option value="North Dakota">North Dakota</option> <option value="Ohio">Ohio</option> <option value="Oklahoma">Oklahoma</option> <option value="Oregon">Oregon</option> <option value="Pennsylvania">Pennsylvania</option> <option value="Rhode Island">Rhode Island</option> <option value="South Carolina">South Carolina</option> <option value="South Dakota">South Dakota</option> <option value="Tennessee">Tennessee</option> <option value="Texas">Texas</option> <option value="Utah">Utah</option> <option value="Vermont">Vermont</option> <option value="Virginia">virginia</option> <option value="Washington">Washington</option> <option value="West Virginia">West Virginia</option> <option value="Wisconsin">Wisconsin</option> <option value="Wyoming">Wyoming</option> </select>&nbsp;*&nbsp;&nbsp;&nbsp;</p> <p>Please type in what country you live in: <input type="text" id="countryOther" />&nbsp;*&nbsp;&nbsp;&nbsp;</p> ``` And here is what I am trying to do with JavaScript: ``` function countryValidation () { var country = document.forms["createForm"]["country"].value; var countryOther = document.forms["createForm"]["countryOther"]; var state = document.forms["createForm"]["state"]; if (country == 0) { countryOther.createAttribute("disabled","disabled"); } else if (country == 1) { state.createAttribute("disabled","disabled"); countryOther.removeAttribute("disabled"); } } ``` I do have another JavaScript function that Validates the whole form, because it is a form that I will be using to allow people to create an account. I haven't gotten to the point of having an SQL server, nor have I learned SQL, PHP or ASP.net... I am doing this for a project and could really use some help with this problem. Thanks!
2014/04/07
['https://Stackoverflow.com/questions/22902486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2810473/']
You need to understand what `include` does. Literally everything in the "included" file will be put where you call that function. So in this case, you're putting practically an entire HTML document inside the `<head>` of another. headertop.php should likely only be: ``` <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="description" content="Slide Down Box Menu with jQuery and CSS3" /> <meta name="keywords" content="jquery, css3, sliding, box, menu, cube, navigation, portfolio, thumbnails"/> <link rel="shortcut icon" href="images/art_favicon.png" type="image/x-icon"/> <link rel="stylesheet" href="css/headertop.css" type="text/css" media="screen"/> ``` And the `<header>` tag does not belong in there at all. That needs to go in the body of your document.
You can do it like this. index.php ``` <!DOCTYPE html> <html> <head> <title>HOME</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="description" content="Slide Down Box Menu with jQuery and CSS3" /> <meta name="keywords" content="jquery, css3, sliding, box, menu, cube, navigation, portfolio, thumbnails"/> <link rel="shortcut icon" href="images/art_favicon.png" type="image/x- icon"/> <link rel="stylesheet" href="css/body.css" type="text/css" media="screen"/> <link rel="stylesheet" href="css/headertop.css" type="text/css" media="screen"/> <style> body{ background-image: url(images/graphy.png); font-family:Arial, Helvetica, sans-serif; margin: 0; padding: 0; } </style> <?php require_once("headertop.php"); ?> </head> <body> <div id="contents"> </div> </body> </html> ``` headertop.php ``` <header> <div id="headertop"> <div id="adams"> <p> <span style="color: #F60;">A</span>ncajas <span style="color: #F60;">D</span>igital <span style="color: #F60;">A</span>rts &amp; <span style="color: #F60;">M</span>edia <span style="color: #F60;">S</span>olutions </p> </div> </div> </header> ``` You don't need to have two same meta-tags or declared Doctype, head or body tag. And for sure, I suggest to you using `require_once`instead of `include`.
43,404,865
I'm making a login script which fetches data from two tables. I understand that this error occurs when the statement returns FALSE AKA a boolean, but why is it returning false??? I made a function which works up to a point ``` function loginall($username, $password) { $db_host="localhost"; $db_username="root"; $db_password=""; $db_name="name"; $con=mysqli_connect($db_host, $db_username,$db_password, $db_name); $mysqli = new mysqli("$db_host","$db_username","$db_password", "$db_name"); $qry = "SELECT username, password, level, active FROM businesses WHERE username=? AND password=? UNION SELECT username, password, level, active FROM employees WHERE username=? AND password=?"; $stmt = $mysqli->prepare($qry); $stmt->bind_param("ssss", $u,$p,$uu,$pp); $u = $username; $p = $password; $uu = $username; $pp = $password; $stmt->execute(); $result = $stmt->get_result(); while($row = $result->fetch_array(MYSQLI_ASSOC)) { return $row; } } ``` it works great until I try fetching more columns from the tables, or even trying to `SELECT *` from the tables. I read through other similar questions and found codes to get the error to appear, but no luck. Thank you!
2017/04/14
['https://Stackoverflow.com/questions/43404865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5990955/']
Your function will end/return as soon as it hits the first return statement in the loop (first iteration). You will need to build the complete array and then return it once. This ought to do it: ``` if(!($stmt=$mysqli->prepare($qry))){ return ["Prepare failed: ".mysqli_error($mysqli)]; // what does this say? }elseif(!$stmt->bind_param("ssss",$u,$p,$uu,$pp)){ return ["Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error]; }else{ $u = $username; $p = $password; $uu = $username; $pp = $password; if (!$stmt->execute()){ return ["Execute failed: (" . $stmt->errno . ") " . $stmt->error]; }else{ $result = $stmt->get_result(); while($row = $result->fetch_array(MYSQLI_ASSOC)){ $rows[]=$row; } return $rows; } } ``` Try backticking all of your column names. `LEVEL` is a MySQL KEYWORD.
Try this maybe `bind_result()` not `get_result()`: You might be wondering, why even use `bind_result()`? This is strictly due to preference, as the syntax is considered to be more readable. However, it should be noted that bind\_result() may not be used with the \* wildcard selector. It must contain explicit values Here in this code using `bind_result()`, the values `$usernameRow, $passwordRow, ....` are form the database tebles: ``` ..... ... . $stmt->bind_param("ssss", $username, $password, $username, $password); $stmt->execute(); $stmt->store_result(); $numRows = $stmt->num_rows; $stmt->bind_result($usernameRow, $passwordRow, $levelRow, $activeRow); if($numRows > 0) { while ($stmt->fetch()) { $u[] = $usernameRow; $p[] = $passwordRow; $uu[] = $levelRow; $pp[] = $activeRow; } } $stmt->close(); ```
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
This issue occurs when the main .class file moved or not found because you changed the directory for committed/shared the project into the git or another repository. To Resolve this issue --> Remove existing run configuration and new one. Find the parent pom.xml or project pom.xml and open cmd/command prompt and run the below commands, 1. mvn clean install package 2. mvn eclipse eclipse
I think .class files are deleted/missing from JavaProject/bin folder. To resolve this issue -> 1) Just cut paste and save the code contents of all the files that you are using then .class files will be regenerated. 2) Then run the code and you can see it works fine if there is no syntactical errors.
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
The solution to this was the following: * Close Eclipse/STS * Use a file explorer on your operating system to navigate to your workspace (In my case, I'm on Windows so I used Windows Explorer) * Delete the `.metadata` directory (or to be safe, copy the directory somewhere else to be safe, then delete it) * Restart Eclipse/STS Is there a more improved answer than this? I don't want to look like I'm trying to boost my own reputation points, so if someone can provide a better answer then please do so.
A quick and easy fix is to directly run your SpringBootApplication class (i.e. Right click, Run As -> Spring Boot App). This runs the app and creates a run configuration automatically.
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
Today I ran into the same problem and I tried a lot of answers. Nothing helped. Cleaning the project, build automatically is already checked, deleting `.metadata`, etc. Eventually I tried this and it worked perfectly: menu Project -> Properties Java Build Path, tab Libraries Remove the JRE System Library from there, press `Add Library`, take the JRE System Library and press `Next`. Workspace default `JRE` and press `Finish`.
I faced the same issue.. just do follow these steps: > > STS/Eclipse --> Project --> Enable "Build Automatically" > > > then refresh your project, it will resolve your issue. Still not refreshed your projects automatically, just restart your STS and check. Hope it will help you.
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
What worked for me: **Menu Project -> Properties** In **Java Build Path**, tab **Libraries** Delete all libraries with a red [x] next to them. In my case, problem happened when I switched from Kepler to STS IDE.
Project -> Clean... -> check project not working -> Clean I already had build automatically set, but forcing STS to rebuild it fixed it.
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
This issue occurs when the main .class file moved or not found because you changed the directory for committed/shared the project into the git or another repository. To Resolve this issue --> Remove existing run configuration and new one. Find the parent pom.xml or project pom.xml and open cmd/command prompt and run the below commands, 1. mvn clean install package 2. mvn eclipse eclipse
I tried all the answers but finally what worked for me was deleting the project from eclipse workspace and importing it again.
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
Today I ran into the same problem and I tried a lot of answers. Nothing helped. Cleaning the project, build automatically is already checked, deleting `.metadata`, etc. Eventually I tried this and it worked perfectly: menu Project -> Properties Java Build Path, tab Libraries Remove the JRE System Library from there, press `Add Library`, take the JRE System Library and press `Next`. Workspace default `JRE` and press `Finish`.
1. Remove project from STS/Eclipse 2. Close or Refresh the Eclipse/ STS Eclipse. 3. Run maven install on pom. 4. Run the project with your Run configuration. Tried above mentioned steps to resolved issue.
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
Today I ran into the same problem and I tried a lot of answers. Nothing helped. Cleaning the project, build automatically is already checked, deleting `.metadata`, etc. Eventually I tried this and it worked perfectly: menu Project -> Properties Java Build Path, tab Libraries Remove the JRE System Library from there, press `Add Library`, take the JRE System Library and press `Next`. Workspace default `JRE` and press `Finish`.
This worked for me to solve the error. (I got this error after removing AWS ToolKit) 1. **Close** the Eclipse/ STS Eclipse. 2. Go to the **WorkSpace** folder. 3. **Delete** the ***.metadata*** folder. 4. **Open** the eclipse. 5. Run ***maven install*** on pom. 6. **Run** the project with your Run configuration.
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
Project -> Clean **this is working**
I faced the same issue.. just do follow these steps: > > STS/Eclipse --> Project --> Enable "Build Automatically" > > > then refresh your project, it will resolve your issue. Still not refreshed your projects automatically, just restart your STS and check. Hope it will help you.
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
Today I ran into the same problem and I tried a lot of answers. Nothing helped. Cleaning the project, build automatically is already checked, deleting `.metadata`, etc. Eventually I tried this and it worked perfectly: menu Project -> Properties Java Build Path, tab Libraries Remove the JRE System Library from there, press `Add Library`, take the JRE System Library and press `Next`. Workspace default `JRE` and press `Finish`.
1 ) Clean the Project 2 ) Enable build automatically Option 3 ) Update the maven project by use the short cut `Alt` + `F5`
37,447,721
I have a main method in a package in one of my projects. Say, the package is `com.ant.car`. I am trying to run and/or debug this main method, and I keep getting the error `Could not find or load main class com.ant.car`. I've searched this problem, and it seems like I can't figure out what is wrong. 1) I've checked run configurations. In Run->Run Configurations, I've checked that the Main class is com.ant.car. 2) I've checked build path. If I right click on the project, I select Build->Build Path, and under the Libraries tab I make sure there are no missing folders with red Xs next to them. Not really sure what else to do. Any suggestions?
2016/05/25
['https://Stackoverflow.com/questions/37447721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664815/']
It worked for me: 1. Delete metadata from work-space directory. 2. Import the project again, but selected copy to work-space option. I think the cause for the error was Non-English characters in the original saved directory.
I spent several hours on this issue, finally it is fixed by doing this: Properties -> Java Compiler: uncheck the checkbox "use '--release' option"
8,389,278
I have a .NET 4 class library that contains an Entity Framework data model and a collection of classes that provide common functionality using those entities. These classes are used across different types of applications. So, my question is would it be considered good practice to expose entities contained within the class library to other applications?
2011/12/05
['https://Stackoverflow.com/questions/8389278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/667108/']
If your entities are advanced enough to meet your persistence needs *and* your domain needs (or external application needs) and there is not much or a low-likelihood of "cross-layer pollution", then I say yes it's a good practice. It can also be a good practice in the agile development sense: good-enough-for-now. Given a longer period of time and if being a purist is more your inclination, then it starts to become a bad practice because you're increasing the coupling, for example, if you start adding attributes to deal with persistence, validation, and serialization. Some ways to avoid that are to use something like [AutoMapper](https://github.com/AutoMapper/AutoMapper), generated code, or hand-coded facades, service layers, and/or adapters to minimize the effects.
Because entity framework changes whenever the database changes, I don't believe this would provide an adequate API. Instead, I would recommend creating a Data Transfer Object to act as an intermediary between external code and each entity that needs to be accessed. Furthermore, consider creating a Facade class (Service layer) that will mediate between the internals of your library and the external "client." Good article on DTOs: <http://msdn.microsoft.com/en-us/magazine/ee236638.aspx>