qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
65,257,848
I just started using timber for logging on android, we are trying to add filenames/class-names to log message. I was able to add filenames in debug build using debug tree, but I'm not finding a way to add filenames in the release tree. Is there a possibility to add the filename in the release tree with R8 enabled?
2020/12/11
[ "https://Stackoverflow.com/questions/65257848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657670/" ]
I got this error by having two different NavControllers in my compose hierarchy as a result of having a composable with a navController parameter: `navController: NavController = rememberNavController()` but not setting it to a common, single root navController.
i had ``` app:launchSingleTop="true" ``` in my action ``` <action android:id="@+id/action_confirmation_to_home_page" app:destination="@id/nav_graph_home" app:launchSingleTop="true" app:popUpTo="@id/home_page_fragment" app:popUpToInclusive="true" /> ``` i removed it, and problem fixed
10,683,216
Is there an easy way to pass an object from my controller to view to controller? I tried *ViewData["compaignId"]* but that didn't work. **Controller *"Content"* :** ``` ViewData["CompaignId"] = id; ``` **View *"Content"* :** ``` <div> @Html.ActionLink("Go To Team Creation", "Team", ViewData["CompaignId"]) </div> ``` **Controller *"Team"*:** ``` public ActionResult Team(long CompaignId) { .... } ``` Thanks,
2012/05/21
[ "https://Stackoverflow.com/questions/10683216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1395918/" ]
In general you should use a ViewModel for things like that. But you can use the `ViewBag` too. ``` ViewBag.CompaignId = id; ```
You should take a look at [this overload](http://msdn.microsoft.com/en-us/library/dd492936.aspx) ``` public static MvcHtmlString ActionLink( this HtmlHelper htmlHelper, string linkText, string actionName, Object routeValues ) ``` And you can pass [anonymous object](http://msdn.microsoft.com/en-us/library/bb397696.aspx) as last parameter ``` <div> @Html.ActionLink("Go To Team Creation", "Team", new { campaignId = (int)ViewData["CompaignId"] }) </div> ```
10,683,216
Is there an easy way to pass an object from my controller to view to controller? I tried *ViewData["compaignId"]* but that didn't work. **Controller *"Content"* :** ``` ViewData["CompaignId"] = id; ``` **View *"Content"* :** ``` <div> @Html.ActionLink("Go To Team Creation", "Team", ViewData["CompaignId"]) </div> ``` **Controller *"Team"*:** ``` public ActionResult Team(long CompaignId) { .... } ``` Thanks,
2012/05/21
[ "https://Stackoverflow.com/questions/10683216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1395918/" ]
U can use: **Controller "Content" :** ``` ViewBag.CompaignId = id; ``` **View "Content" :** ``` <div> @Html.ActionLink("Go To Team Creation", "Team", new { CompaignId = (long)ViewBag.CompaignId }) </div> ``` **Controller "Team":** ``` public ActionResult Team(long CompaignId) { .... } ```
You should take a look at [this overload](http://msdn.microsoft.com/en-us/library/dd492936.aspx) ``` public static MvcHtmlString ActionLink( this HtmlHelper htmlHelper, string linkText, string actionName, Object routeValues ) ``` And you can pass [anonymous object](http://msdn.microsoft.com/en-us/library/bb397696.aspx) as last parameter ``` <div> @Html.ActionLink("Go To Team Creation", "Team", new { campaignId = (int)ViewData["CompaignId"] }) </div> ```
47,074
Game Programming is fun and interesting. To develop games I have to learn several languages, game engines and should have sound knowledge in Math. But what I'm really looking is how to be a **master** in **Game Programming**. --- I have read a nice question and answer * <https://softwareengineering.stackexchange.com/questions/165380/how-can-i-really-master-a-programming-language> But here, in my question I want to know **specially regarding Game Programming from the Game Programmers.** Your suggestions would help me to be a master in game programming.
2013/01/09
[ "https://gamedev.stackexchange.com/questions/47074", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19664/" ]
Make games. ... that's all I've got. You want to master *anything*, you practice it until you have. That's all the other great game makers have done: make lots of games. The experienced people who frequent this site? Check their credentials, you'll see they've made a lot of games. That's it. Practice makes perfect.
Make lots of games. If you really want to focus on mastering, you need depth and breadth. This means: * Make different types of games. Pong has totally different challenges from a 2D RPG. * Challenge yourself. Try to solve "hard" problems or technical growth (eg. different architectures, like an entity/component system). Also, read widely in your field. Read GameDev.SE, read game development blogs, and implement things that look cool, fun, or interesting.
47,798,440
My gmail account I used to create my google cloud instance is johnsmith@gmail.com. When I tried to connect to instance with WinSCP using "johnsmith" it failed, but it worked with "JOHN.SMITH"? Where can I find out my exact username for google cloud instance? UPDATE. I tried web-based SSH and typed `whoami`, it returned "johnsmith". "john.smith" is my windows local username. It is all very confusing. ANOTHER UPDATE: My google cloud instance is Ubuntu 16.04 and I am connecting from Windows 7 local machine P.S. I made up the name, but preserved format for this question. P.S.S SO does not let me post because I don't meet their standard. Here is some bogus code to meet the standard: ``` print("Hello, World!") ```
2017/12/13
[ "https://Stackoverflow.com/questions/47798440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1700890/" ]
Just to clarify, I presume you are trying to connect to a Compute Engine Windows Instance in your Google Cloud Platform project, is that correct? In order to confirm the username of this instance I would recommend following these instructions: 1) Login to Google Cloud Platform Console at this link <https://console.cloud.google.com/> 2) In the Console main menu (the three horizontal stripes in the top left corner) navigate to 'Compute Engine' and then click on 'VM instances'. 3) You should now be able to see the name of your VM instance- click on it. 4) You will now be in the "VM instance details" screen. ### Windows 5) If you now click on "Set Windows Password" a new pane will open that contains your username to login to the instance. 6) If you now press "Set" in the same window, you will receive your Windows password (copy or make note of this). By using the username and password you retrieved in step 5 and 6 you will be able to access the instance. You now also have the option of pressing "RDP" in the "VM instance details" page to gain access to your instance via RDP and change your username/password to something more memorable once you have access to the operating system. ### Linux Alternatively, if you are trying to disover the username of a Linux VM Instance, you can confirm this by accessing the machine via SSH from the Console. You will then be able to set the password of the machine. To SSH into the machine, follow the same first 4 steps in the above instructions, then: * Click on "SSH". A new terminal window will open and you will gain access the machine. * You will be able to see your username in the shell, or alternatively you can type `whoami` in the shell and after pressing enter it will print out your username. * To set a password for the machine, type `sudo passwd` then press return. You will then be prompted to enter a new password.
In GCP, I created Ubuntu 18.04 disk/instance (and created a discourse forum in it). I found that when we create a new instance, there is a bar/panel on the right side of the screen, which showed our credentials to login into that instance/website. But I found no way to invoke that details screen again (I can remember that it listed all the software components went into my disk/instance installation). Anyway, I remembered the username was 'user', but didn't keep record of the auto generated long alphanumeric password. But at last, found the same passsword, when I clicked on the instance name and without clicking on any further, where custom data details start, first line showed the password, labelled: Bitnami-base-password. [If its still not clear where to find the pw, check out the SS](https://i.stack.imgur.com/GgCpE.png)
47,798,440
My gmail account I used to create my google cloud instance is johnsmith@gmail.com. When I tried to connect to instance with WinSCP using "johnsmith" it failed, but it worked with "JOHN.SMITH"? Where can I find out my exact username for google cloud instance? UPDATE. I tried web-based SSH and typed `whoami`, it returned "johnsmith". "john.smith" is my windows local username. It is all very confusing. ANOTHER UPDATE: My google cloud instance is Ubuntu 16.04 and I am connecting from Windows 7 local machine P.S. I made up the name, but preserved format for this question. P.S.S SO does not let me post because I don't meet their standard. Here is some bogus code to meet the standard: ``` print("Hello, World!") ```
2017/12/13
[ "https://Stackoverflow.com/questions/47798440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1700890/" ]
Just to clarify, I presume you are trying to connect to a Compute Engine Windows Instance in your Google Cloud Platform project, is that correct? In order to confirm the username of this instance I would recommend following these instructions: 1) Login to Google Cloud Platform Console at this link <https://console.cloud.google.com/> 2) In the Console main menu (the three horizontal stripes in the top left corner) navigate to 'Compute Engine' and then click on 'VM instances'. 3) You should now be able to see the name of your VM instance- click on it. 4) You will now be in the "VM instance details" screen. ### Windows 5) If you now click on "Set Windows Password" a new pane will open that contains your username to login to the instance. 6) If you now press "Set" in the same window, you will receive your Windows password (copy or make note of this). By using the username and password you retrieved in step 5 and 6 you will be able to access the instance. You now also have the option of pressing "RDP" in the "VM instance details" page to gain access to your instance via RDP and change your username/password to something more memorable once you have access to the operating system. ### Linux Alternatively, if you are trying to disover the username of a Linux VM Instance, you can confirm this by accessing the machine via SSH from the Console. You will then be able to set the password of the machine. To SSH into the machine, follow the same first 4 steps in the above instructions, then: * Click on "SSH". A new terminal window will open and you will gain access the machine. * You will be able to see your username in the shell, or alternatively you can type `whoami` in the shell and after pressing enter it will print out your username. * To set a password for the machine, type `sudo passwd` then press return. You will then be prompted to enter a new password.
Using google cloud SDK shell, type the following command: > > gcloud compute ssh --project PROJECT\_ID --zone ZONE VM\_NAME > > > Replace the following: ``` PROJECT_ID: the ID of the project that contains the instance ZONE: the name of the zone in which the instance is located VM_NAME: the name of the instance ``` <https://cloud.google.com/compute/docs/instances/connecting-to-instance>
47,798,440
My gmail account I used to create my google cloud instance is johnsmith@gmail.com. When I tried to connect to instance with WinSCP using "johnsmith" it failed, but it worked with "JOHN.SMITH"? Where can I find out my exact username for google cloud instance? UPDATE. I tried web-based SSH and typed `whoami`, it returned "johnsmith". "john.smith" is my windows local username. It is all very confusing. ANOTHER UPDATE: My google cloud instance is Ubuntu 16.04 and I am connecting from Windows 7 local machine P.S. I made up the name, but preserved format for this question. P.S.S SO does not let me post because I don't meet their standard. Here is some bogus code to meet the standard: ``` print("Hello, World!") ```
2017/12/13
[ "https://Stackoverflow.com/questions/47798440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1700890/" ]
Under Cloud Shell Session: gcloud compute os-login describe-profile You will see your username.
In GCP, I created Ubuntu 18.04 disk/instance (and created a discourse forum in it). I found that when we create a new instance, there is a bar/panel on the right side of the screen, which showed our credentials to login into that instance/website. But I found no way to invoke that details screen again (I can remember that it listed all the software components went into my disk/instance installation). Anyway, I remembered the username was 'user', but didn't keep record of the auto generated long alphanumeric password. But at last, found the same passsword, when I clicked on the instance name and without clicking on any further, where custom data details start, first line showed the password, labelled: Bitnami-base-password. [If its still not clear where to find the pw, check out the SS](https://i.stack.imgur.com/GgCpE.png)
47,798,440
My gmail account I used to create my google cloud instance is johnsmith@gmail.com. When I tried to connect to instance with WinSCP using "johnsmith" it failed, but it worked with "JOHN.SMITH"? Where can I find out my exact username for google cloud instance? UPDATE. I tried web-based SSH and typed `whoami`, it returned "johnsmith". "john.smith" is my windows local username. It is all very confusing. ANOTHER UPDATE: My google cloud instance is Ubuntu 16.04 and I am connecting from Windows 7 local machine P.S. I made up the name, but preserved format for this question. P.S.S SO does not let me post because I don't meet their standard. Here is some bogus code to meet the standard: ``` print("Hello, World!") ```
2017/12/13
[ "https://Stackoverflow.com/questions/47798440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1700890/" ]
Under Cloud Shell Session: gcloud compute os-login describe-profile You will see your username.
Using google cloud SDK shell, type the following command: > > gcloud compute ssh --project PROJECT\_ID --zone ZONE VM\_NAME > > > Replace the following: ``` PROJECT_ID: the ID of the project that contains the instance ZONE: the name of the zone in which the instance is located VM_NAME: the name of the instance ``` <https://cloud.google.com/compute/docs/instances/connecting-to-instance>
50,300,724
I am creating a normal ES6 class. The problem encountered is putting a variable inside the `class` encapsulation while keeping it outside of `constructor().` You can replicate this error when you use this code: ``` class Polygon { constructor() { this.name = "Polygon"; var goodboy = "I like pie...I can stay since I'm legal!"; } var badboy = "what're you gonna do when they come for you? delete me to get rid of all your problems!"; } var poly1 = new Polygon(); console.log(poly1.name); ``` You can try this code anywhere! Try deleting `badboy` and `goodboy` and see how it plays out. **How can I get around this?** Any explanation is welcome, Farouk *Aforementioned code was modified from MDN. This code has no intention and is meant for variable declaration example purposes.*
2018/05/11
[ "https://Stackoverflow.com/questions/50300724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8419634/" ]
You can declare class level variables like so ``` class Polygon { myVar = null; constructor(args){ this.myVar = args.myVar; } } let polygon = new Polygon({myVar:"some value"}); console.log(polygon.myVar); // "some value" ``` To accomplish this by transpiling with Babel you will need to use [transform-class-properties](https://babeljs.io/docs/plugins/transform-class-properties/) plugin.
> > Cannot define variables outside of a class's constructor function > > > Yes, that's not syntactically valid. > > I'm putting a variable inside the `class` encapsulation while keeping it outside of `constructor()`. > > > That's not possible. A `class` does not provide any such encapsulation, it does not create a block scope. Just put the variable outside of the `class` definition. Or don't make it a variable but a property instead.
50,300,724
I am creating a normal ES6 class. The problem encountered is putting a variable inside the `class` encapsulation while keeping it outside of `constructor().` You can replicate this error when you use this code: ``` class Polygon { constructor() { this.name = "Polygon"; var goodboy = "I like pie...I can stay since I'm legal!"; } var badboy = "what're you gonna do when they come for you? delete me to get rid of all your problems!"; } var poly1 = new Polygon(); console.log(poly1.name); ``` You can try this code anywhere! Try deleting `badboy` and `goodboy` and see how it plays out. **How can I get around this?** Any explanation is welcome, Farouk *Aforementioned code was modified from MDN. This code has no intention and is meant for variable declaration example purposes.*
2018/05/11
[ "https://Stackoverflow.com/questions/50300724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8419634/" ]
I think, inside a class you can not declare a member directly, you need to use getter and setter. Otherwise you will get an error: "Unexpected token. A constructor, method, accessor, or property was expected." Here is how you can get your badboy: ``` class Polygon { constructor() { this.name = "Polygon"; } get badboy(){ return "what're you gonna do when they come for you?"; } } var poly1 = new Polygon(); console.log(poly1.name); // Polygon console.log(poly1.badboy); // what're you gonna do when they come for you? ``` Intention of your code is not clear enough. If you will not use it as an instance property, why would you put it in a class? You know `poly1.badboy = "what're you gonna do when they come for you?"` does the same thing without all the hassle.
> > Cannot define variables outside of a class's constructor function > > > Yes, that's not syntactically valid. > > I'm putting a variable inside the `class` encapsulation while keeping it outside of `constructor()`. > > > That's not possible. A `class` does not provide any such encapsulation, it does not create a block scope. Just put the variable outside of the `class` definition. Or don't make it a variable but a property instead.
50,300,724
I am creating a normal ES6 class. The problem encountered is putting a variable inside the `class` encapsulation while keeping it outside of `constructor().` You can replicate this error when you use this code: ``` class Polygon { constructor() { this.name = "Polygon"; var goodboy = "I like pie...I can stay since I'm legal!"; } var badboy = "what're you gonna do when they come for you? delete me to get rid of all your problems!"; } var poly1 = new Polygon(); console.log(poly1.name); ``` You can try this code anywhere! Try deleting `badboy` and `goodboy` and see how it plays out. **How can I get around this?** Any explanation is welcome, Farouk *Aforementioned code was modified from MDN. This code has no intention and is meant for variable declaration example purposes.*
2018/05/11
[ "https://Stackoverflow.com/questions/50300724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8419634/" ]
You can declare class level variables like so ``` class Polygon { myVar = null; constructor(args){ this.myVar = args.myVar; } } let polygon = new Polygon({myVar:"some value"}); console.log(polygon.myVar); // "some value" ``` To accomplish this by transpiling with Babel you will need to use [transform-class-properties](https://babeljs.io/docs/plugins/transform-class-properties/) plugin.
``` // adjusted class Polygon { constructor() { this.name = "Polygon"; var goodboy = "I like pie...I can stay since I'm legal!"; } } var poly = new Polygon(); console.log(poly.name); // option 2 // This works also function Polygon2() { this.name = "Polygon"; class Poly { constructor(obj) { this.user = "Farouk"; this.name2 = obj.name; } } let poly2 = new Poly(this); this.user = poly2.user; this.name2 = poly2.name2; } var poly2 = new Polygon2(); console.log(poly2.name); console.log(poly2.user); console.log(poly2.name2); ```
50,300,724
I am creating a normal ES6 class. The problem encountered is putting a variable inside the `class` encapsulation while keeping it outside of `constructor().` You can replicate this error when you use this code: ``` class Polygon { constructor() { this.name = "Polygon"; var goodboy = "I like pie...I can stay since I'm legal!"; } var badboy = "what're you gonna do when they come for you? delete me to get rid of all your problems!"; } var poly1 = new Polygon(); console.log(poly1.name); ``` You can try this code anywhere! Try deleting `badboy` and `goodboy` and see how it plays out. **How can I get around this?** Any explanation is welcome, Farouk *Aforementioned code was modified from MDN. This code has no intention and is meant for variable declaration example purposes.*
2018/05/11
[ "https://Stackoverflow.com/questions/50300724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8419634/" ]
I think, inside a class you can not declare a member directly, you need to use getter and setter. Otherwise you will get an error: "Unexpected token. A constructor, method, accessor, or property was expected." Here is how you can get your badboy: ``` class Polygon { constructor() { this.name = "Polygon"; } get badboy(){ return "what're you gonna do when they come for you?"; } } var poly1 = new Polygon(); console.log(poly1.name); // Polygon console.log(poly1.badboy); // what're you gonna do when they come for you? ``` Intention of your code is not clear enough. If you will not use it as an instance property, why would you put it in a class? You know `poly1.badboy = "what're you gonna do when they come for you?"` does the same thing without all the hassle.
``` // adjusted class Polygon { constructor() { this.name = "Polygon"; var goodboy = "I like pie...I can stay since I'm legal!"; } } var poly = new Polygon(); console.log(poly.name); // option 2 // This works also function Polygon2() { this.name = "Polygon"; class Poly { constructor(obj) { this.user = "Farouk"; this.name2 = obj.name; } } let poly2 = new Poly(this); this.user = poly2.user; this.name2 = poly2.name2; } var poly2 = new Polygon2(); console.log(poly2.name); console.log(poly2.user); console.log(poly2.name2); ```
6,177,411
I want to autoplay my video on mouse over. Can anybody tell me how to make it play via media player or flash player? PS: Can I play WMV/ASF/MP4 in flash player?
2011/05/30
[ "https://Stackoverflow.com/questions/6177411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680297/" ]
No. Each request will spawn a new process. Nothing survives between them. You can retain state using sessions, which are essentially a disk-based serialization mechanism. Sessions them selves rely on cookies to identify the data between requests (But the data it self is stored in a file on the server). As such, they are local to the user and not suitable for your needs. The standard way to store that kind of data in a PHP application would be in a database.
`$visits` will be 1 in both case. Singletons are per request and not per machine / host. Each request will have its own instance. I don't think you can count the number of hits for one page without some kind of disk storage / database.
30,833,080
I am trying to create a simple alert dialogue and I am following the steps from this [link](http://developer.android.com/guide/topics/ui/dialogs.html) However,I am getting the error: `getActivity() can't be resolved` After some search I understood that `getActivity()` can be user defined, but I am not sure what should I make it do. Here is what I have: ``` public void about(View v1) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Add the buttons builder.setNeutralButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish();//go to the previous activity } }); // Set other dialog properties builder.setMessage(R.string.myName); // Create the AlertDialog AlertDialog dialog = builder.create();} ``` * What is wrong with this approach? * Is there any other better approach you can suggest? * oh, and what should `getActivity()` be used for?
2015/06/14
[ "https://Stackoverflow.com/questions/30833080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3551661/" ]
getActivity() is fragments method to get Activity. If u are in activity u just need to replace this by YourActivityClassName.this
``` // in a fragment new AlertDialog.Builder(getContext()) .setTitle("Alert title") .setMessage("Alert Message") .setCancelable(false) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); ```
62,408
As a graduate student, I have recently supervised an undergraduate with their thesis work in co-operation with my own supervisor. I took care of the daily in-detail supervision, and my supervisor had the "grand overview" of the project and where it should lead to. This went on for almost 7 months. Today, in roughly 3 hours, is the defense of the undergraduate. However, my supervisor hasn't asked me for my opinion on the thesis that was handed in. Actually, since it was handed in 2 weeks ago, I haven't been asked about it at all. The thesis will be evaluated by an external referee and the supervisor at a public defense today -- if it wasn't for the undergraduate student telling me, I wouldn't even know that the defense was today! I find this weird, and to some extent unprofessional. As the main leader and supervisor, they should, in my opinion, discuss the thesis with me to hear my opinion and include me in this process. After all, I did help with the "brute work". Part of me wants to let my supervisor know that I feel a little left out. On the other hand, I don't want to be difficult. What do you think I should do?
2016/01/28
[ "https://academia.stackexchange.com/questions/62408", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/6049/" ]
In general, supervisors should "acknowledge" their students more. We often forget to tell people when they are doing well and only point out mistakes. Your supervisor should have most definitely acknowledged your help with the student. He should have thanked you for helping out with the student and ideally given you feedback about your supervision. As for comments on the thesis, depending on your official role and the rules of the university/department, he may not be able to talk to you about the grades of other students. That said, he could acknowledge you to let you know that. If he is allowed to discuss the grades, it can be a learning opportunity to talk about the process. That said, grading is generally not a fun part of the job, and he may simply be "protecting" you from an aspect of work. It is not out of place to talk to him about the thesis (either the final product or grade). He will let you know if the conversation goes someplace it should not. The one place that he should most definitely try and acknowledge you is to the external referee. Something as little as "a lot of this project was managed by my PhD student Billy Jean" can help your networking.
I can think of three possibilities, in addition to StrongBad's "oversight" possibility, which are not necessarily exclusive of each other. * He doesn't want your opinion because he needs and wants to form his own, independent opinion of the work in order to execute his function at the defense. The (lead) supervisor bears the brunt of the responsibility and blame if poor, or outright bad, work is brought to a defense. Some people may simply be cautious that the opinions of others may confuse their own in such a situation, and so avoid them until they can process them more objectively. * University and/or department rules may specifically prohibit you from "being a part of this process." In my oral qualifying exams as a graduate student, it was specifically prohibited for anyone other than my committee from being in the room. No students, no friends, no other professors, no one at all. My Ph.D. defense was an open defense that anyone could attend, which is standard across universities and countries. You may wish to consult the policies of your university concerning the defense of an undergraduate thesis. * Either you were there for nothing more than to make sure the lab doesn't blow up—in which case there is no expectation that you have a substantive opinion on the work, and so no reason to ask you—, or you were there to monitor the quality of the work done (as well)—in which case it was part of your job to report significant issues, as well as just reporting on progress in general, bad or otherwise. As the saying goes: "No news is good news." If you said nothing bad about the work, or barely said anything at all, then he already has your opinion. If you'd been reporting good and bad things (if any) regularly, then your supervisor again already had your opinion. In any case, asking your supervisor about the matter in a calm, reasonable way should get you an answer.
42,354,122
``` #include<iostream> using namespace std; class emp { public: int en; char name[10],des[10]; void get() { cout<<"enter emp no."; cin>>en; cout<<"enter emp name"; cin>>name; cout<<"enter designation"; cin>>des; } }; class salary : public emp { public: float bp,hra,da,pf,np; void get1() { cout<<"enter basic pay"; cin>>bp; cout<<"enter domestic allowance"; cin>>da; cout<<"enter profit fund"; cin>>pf; cout<<"enter human resource admittance"; cin>>hra; } void calculate() { np=bp+da+hra-pf; } void display() { cout<<en<<"\t"<<name<<"\t"<<des<<"\t"<<da<<"\t"<<pf<<"\t"<<np<<"\n"; } }; int main() { salary s[10]; int i,n; char ch; cout<<"enter the no. of employees"; cin>>n; for(i=0;i<=n;i++) { s[i].get(); s[i].get1(); s[i].calculate(); } cout<<"\n eno. \t ename \t des \t bp \t hra \t da \t pf \t np \n"; for(i=0;i<=n;i++) { s[i].display(); } return 0; } ```
2017/02/20
[ "https://Stackoverflow.com/questions/42354122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7590114/" ]
`cin>>des[10];` reads *one* (single) character for standard input, and attempts to write it to `des[10]`. Unfortunately, you've defined `des` as having 10 characters, so only `des[0]` through `des[9]` are valid, so when it attempts to write to `des[10]`, you get undefined behavior. My guess is that you probably wanted something more like: ``` cin.getline(des, 10); ``` This attempts to read a maximum of 10 characters from `cin`, and write them to `des` (and assures that it's NUL terminated). The same, of course, applies to `name`. Once you're done with that, you probably want to forget all of the above, define both `name` and `des` as `std::string`s. Then you can use `std::getline(std::cin, name);`. With this you don't have to specify a maximum size; the string will expand to hold as much as the user enters.
instead of name[10] and des[10], use cin >> name and cin >> des
7,721,775
Is there a fatser way to xor every column of a matrix than this? ``` mod(sum(matrix),2) ``` It converts from logical to double and uses the expensive modulo. Update: According to [this source](http://www.mathworks.com/matlabcentral/newsreader/view_thread/246073), summing uint's is slower than summing doubles because it involves max clipping and other reasons. Also, note that summing logicals (with `'native'`) stops at 1.
2011/10/11
[ "https://Stackoverflow.com/questions/7721775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907578/" ]
I tried to avoid the cast to `double` but it's not better (often worse). ``` A = rand(2000000, 1) > 0.5; class(A) tic B = mod(sum(A),2) toc tic C = mod(sum(uint32(A),'native'),2) toc tic D = bitand(sum(uint32(A),'native'),1) toc ``` The `native` option of sum allow you to keep the type of the argument in the result.
In addition to what @ClementJ says, I tried ``` tic E = A(1) for i = 2:numel(A) E = xor(y, A(i)); end E toc ``` hoping the accelerator would help, but it doesn't (much), and ``` tic F = num2cell(A); F = xor(F{:}) toc ``` which doesn't actually work because XOR only allows 2 inputs. MATLAB's double precision vector arithmetic is about as fast as it gets, so you probably can't do better. If this is really driving your performance, then I suggest writing a C-MEX function: should be easy.
73,290,974
I feel like that question has been asked a few times already but I haven't been able to find an answer to that specific use case. Here's what I want: [![enter image description here](https://i.stack.imgur.com/WVgoU.png)](https://i.stack.imgur.com/WVgoU.png) I think the closest post/answer I've been able to find is [this one](https://stackoverflow.com/a/47661523/2398593). I understand and am able to repro it without any issue, see [stackblitz live demo](https://stackblitz.com/edit/web-platform-a6ks6n?file=index.html). But as soon as I try to split the main panel into 2 different panels with a left menu and the content, I get a scrollbar on the right and the footer is being pushed right below. I have to scroll to see the footer whereas I only want to be able to scroll in both the left menu and the content but always want to see the header and footer. Here's my attempt on [stackblitz as a minimal repro](https://stackblitz.com/edit/web-platform-macyby?file=styles.css) to show the issue. About the code: ```css html, body { display: block; width: 100%; height: 100%; margin: 0; padding: 0; } .wrapper { width: 100%; height: 100%; display: flex; flex-direction: column; } .body { flex: 1; width: 100%; height: 100%; display: flex; } .body .menu { height: 100%; display: flex; overflow: auto; } .body .content { flex: 1; overflow: auto; } ``` ```html <div class="wrapper"> <div class="header">header</div> <div class="body"> <div class="menu"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li>Menu Item</li> </ul> </div> <div class="content"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li>Content Item</li> </ul> </div> </div> <div class="footer">footer</div> </div> ``` Thanks for any help.
2022/08/09
[ "https://Stackoverflow.com/questions/73290974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2398593/" ]
If you can fix the width of your left column then you can use absolute positioning on your middle divs to get the overflow you want: ```css html, body { display: block; width: 100%; height: 100%; margin: 0; padding: 0; } .wrapper { width: 100%; height: 100%; display: flex; flex-direction: column; } .body { flex-grow: 1; width: 100%; display: flex; } .body .menu { width: 200px; } .body .content { flex: 1; } .scroll-holder { position: relative; } .scroll { position: absolute; top: 0; left: 0; right: 0; bottom: 0; overflow-y: auto; } .test { height: 1000px; } ``` ```html <div class="wrapper"> <div class="header">header</div> <div class="body"> <div class="menu scroll-holder"> <div class="scroll"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li class="test">Menu Item</li> <li>Menu Item</li> </ul> </div> </div> <div class="content scroll-holder"> <div class="scroll"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li class="test">Content Item</li> <li>Content Item</li> </ul> </div> </div> </div> <div class="footer">footer</div> </div> ``` With a fluid left column: ```css html, body { display: block; width: 100%; height: 100%; margin: 0; padding: 0; } .wrapper { width: 100%; height: 100%; display: flex; flex-direction: column; } .body { flex-grow: 1; width: 100%; position: relative; } .body .content { flex: 1; } .absolute-flex { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; } .scroll { max-height: 100%; overflow: auto; } .test { height: 1000px; } ``` ```html <div class="wrapper"> <div class="header">header</div> <div class="body"> <div class="absolute-flex"> <div class="menu scroll"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li class="test">Menu Item</li> <li>Menu Item</li> </ul> </div> <div class="content scroll"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li class="test">Content Item</li> <li>Content Item</li> </ul> </div> </div> </div> <div class="footer">footer</div> </div> ```
I think this demo should solve the issue. [stackblitz-demo](https://stackblitz.com/edit/web-platform-z26z9p?file=index.html) The trick is to hide the overflow on the body, but only make it to auto on the div you want to scroll in. Then you have to define the height you want that div to be and you should be able to scroll when an overflow occurs. :)
73,290,974
I feel like that question has been asked a few times already but I haven't been able to find an answer to that specific use case. Here's what I want: [![enter image description here](https://i.stack.imgur.com/WVgoU.png)](https://i.stack.imgur.com/WVgoU.png) I think the closest post/answer I've been able to find is [this one](https://stackoverflow.com/a/47661523/2398593). I understand and am able to repro it without any issue, see [stackblitz live demo](https://stackblitz.com/edit/web-platform-a6ks6n?file=index.html). But as soon as I try to split the main panel into 2 different panels with a left menu and the content, I get a scrollbar on the right and the footer is being pushed right below. I have to scroll to see the footer whereas I only want to be able to scroll in both the left menu and the content but always want to see the header and footer. Here's my attempt on [stackblitz as a minimal repro](https://stackblitz.com/edit/web-platform-macyby?file=styles.css) to show the issue. About the code: ```css html, body { display: block; width: 100%; height: 100%; margin: 0; padding: 0; } .wrapper { width: 100%; height: 100%; display: flex; flex-direction: column; } .body { flex: 1; width: 100%; height: 100%; display: flex; } .body .menu { height: 100%; display: flex; overflow: auto; } .body .content { flex: 1; overflow: auto; } ``` ```html <div class="wrapper"> <div class="header">header</div> <div class="body"> <div class="menu"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li>Menu Item</li> </ul> </div> <div class="content"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li>Content Item</li> </ul> </div> </div> <div class="footer">footer</div> </div> ``` Thanks for any help.
2022/08/09
[ "https://Stackoverflow.com/questions/73290974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2398593/" ]
If you can fix the width of your left column then you can use absolute positioning on your middle divs to get the overflow you want: ```css html, body { display: block; width: 100%; height: 100%; margin: 0; padding: 0; } .wrapper { width: 100%; height: 100%; display: flex; flex-direction: column; } .body { flex-grow: 1; width: 100%; display: flex; } .body .menu { width: 200px; } .body .content { flex: 1; } .scroll-holder { position: relative; } .scroll { position: absolute; top: 0; left: 0; right: 0; bottom: 0; overflow-y: auto; } .test { height: 1000px; } ``` ```html <div class="wrapper"> <div class="header">header</div> <div class="body"> <div class="menu scroll-holder"> <div class="scroll"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li class="test">Menu Item</li> <li>Menu Item</li> </ul> </div> </div> <div class="content scroll-holder"> <div class="scroll"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li class="test">Content Item</li> <li>Content Item</li> </ul> </div> </div> </div> <div class="footer">footer</div> </div> ``` With a fluid left column: ```css html, body { display: block; width: 100%; height: 100%; margin: 0; padding: 0; } .wrapper { width: 100%; height: 100%; display: flex; flex-direction: column; } .body { flex-grow: 1; width: 100%; position: relative; } .body .content { flex: 1; } .absolute-flex { position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; } .scroll { max-height: 100%; overflow: auto; } .test { height: 1000px; } ``` ```html <div class="wrapper"> <div class="header">header</div> <div class="body"> <div class="absolute-flex"> <div class="menu scroll"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li class="test">Menu Item</li> <li>Menu Item</li> </ul> </div> <div class="content scroll"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li class="test">Content Item</li> <li>Content Item</li> </ul> </div> </div> </div> <div class="footer">footer</div> </div> ```
The height and position attributes are the main things you should play around with. ```css html, body { display: block; width: 100%; height: 100%; max-height: 100vh; margin: 0; padding: 0; } .wrapper { width: 100%; height: 80%; display: flex; flex-direction: column; } .body { flex: 1; width: 100%; height: 100%; display: flex; } .body .menu { height: 100%; display: flex; overflow: auto; } .body .content { max-height: 100%; flex: 50%; justify-content: space-around; overflow: auto; } ``` ```html <div class="wrapper"> <div class="header">header</div> <div class="body"> <div class="menu"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> <li>Menu Item</li> </ul> </div> <div class="content"> <ul> <!-- duplicate this as many times as needed to verify scrolling behavior --> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> <li>Content Item</li> </ul> </div> </div> <div class="footer">footer</div> </div> ``` you might still need to play around to get the result you want.
59,053,764
I want to do something like this (similar to the Accordion in react bootstrap): ``` class Foo extends React.Component{ static Button; static Content; render(){ return( <div> <Foo.Button/> <Foo.Content/> </div> ); } } ``` so that I can use it like this: ``` function App() { return ( <Foo> <Foo.Button> <p>this is in the button</p> </Foo.Button> <Foo.Content> <p>this is content</p> </Foo.Content> </Foo> ); } ``` How can I get this or what do I have to search for an example?
2019/11/26
[ "https://Stackoverflow.com/questions/59053764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8634687/" ]
Have you tried adding: ``` var chromeOptions = new ChromeOptions(); chromeOptions.AddArguments("headless"); ```
Ok, after some investigation, it should be: ``` using System.Linq; using OpenQA.Selenium.Chrome; using Scripting; using System.IO; namespace WebDriverTest { class Program { static void Main(string[] args) { var chromeOptions = new ChromeOptions(); chromeOptions.AddArguments("headless"); // Initialize the Chrome Driver using (var driver = new ChromeDriver(chromeOptions)) { // Go to the home page driver.Navigate().GoToUrl("xxx.com"); driver.Manage().Timeouts().ImplicitWait = System.TimeSpan.FromSeconds(15); // Get the page elements var userNameField = driver.FindElementById("loginForm:username"); var userPasswordField = driver.FindElementById("loginForm:password"); var loginButton = driver.FindElementById("loginForm:loginButton"); // Type user name and password userNameField.SendKeys("username"); userPasswordField.SendKeys("password"); // and click the login button loginButton.Click(); // Extract the text and save it into result.txt // var result = driver.FindElementByXPath("//div[@id='case_login']/h3").Text; // File.WriteAllText("result.txt", result); // Take a screenshot and save it into screen.png driver.GetScreenshot().SaveAsFile(@"screen.png", OpenQA.Selenium.ScreenshotImageFormat.Png); } } } } ```
12,366,716
``` <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><script> <script> $(document).ready(function() { $('.sss').filter(':nth-child(n+2)').hide(); $('.sss').on('mouseenter', '.question', function() { $(this).next().slideDown(200).siblings('.answer').slideUp(200); }); }); </script> </head> <div class="sss"> <div class="question">Question</div> <div class="answer">Answer</div> <div class="question">Question</div> <div class="answer">Answer</div> <div class="question">Question</div> <div class="answer">Answer</div> <div class="question">Question</div> <div class="answer">Answer</div> </div> ``` Divs doesn't have parent-child relation or am I doing a mistake here?
2012/09/11
[ "https://Stackoverflow.com/questions/12366716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043575/" ]
Try this: ``` $('.sss').children().filter(':nth-child(n+2)').hide(); ``` If you need all `question` div then try: ``` $('.sss').children(':nth-child(2n)').hide(); ``` ***OR*** ``` $('.sss .question').hide(); ``` and for all `answer`: ``` $('.sss').children(':nth-child(2n+1)').hide(); ``` ***OR*** ``` $('.sss .answer').hide(); ```
Here is an alternative not using filter: ``` $('.sss').children(':nth-child(n+2)').hide(); ```
9,543
Does the nature of the assortment of virtual particles depend upon the warping of spacetime in a direct manner ?
2011/05/06
[ "https://physics.stackexchange.com/questions/9543", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/14207/" ]
EAMann, I know this is a physics site, and you are looking for a physics answer; but I noticed that you are in Portland, Oregon. It seems amazing to me that you can not find a site reasonably close. If nothing is closer, it seems to me that one of your beautiful beaches would make a nice launch site. That is (IIRC) more than an hour away, but you could combine it with a camping trip. My high school biology professor used to take us out to the Gingko petrified forest in eastern WA. Along the way we would stop and jump down the sand dunes on the WA side of the Columbia River, not too far (a few hours) from where you are. There is a lot of desert in eastern WA and eastern OR. Can't imagine not being able to find a launch site out there. The other thing I would do is network through your own organization, BSA, to find out where other nearby scout troops are going. I hope this helps.
I found [this water rocket video](http://www.youtube.com/watch?v=CAAhQ6xcAnw), which appears to attain sufficient altitude. The group that makes them has a nice website and [tutorial](http://www.aircommandrockets.com/). Perhaps launching black powder based rockets from a boat might be an alternative solution.
9,543
Does the nature of the assortment of virtual particles depend upon the warping of spacetime in a direct manner ?
2011/05/06
[ "https://physics.stackexchange.com/questions/9543", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/14207/" ]
I found [this water rocket video](http://www.youtube.com/watch?v=CAAhQ6xcAnw), which appears to attain sufficient altitude. The group that makes them has a nice website and [tutorial](http://www.aircommandrockets.com/). Perhaps launching black powder based rockets from a boat might be an alternative solution.
This doesn't answer the question, but it does solve the problem. Do it on the 4th of July along side your neighbors who (I assume) will also be launching bottle rockets etc. Here in South Carolina it sounds like a war zone on the 4th from about 8-12pm. It that doesn't work, maybe ask to do it before/after a fireworks display?
9,543
Does the nature of the assortment of virtual particles depend upon the warping of spacetime in a direct manner ?
2011/05/06
[ "https://physics.stackexchange.com/questions/9543", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/14207/" ]
I found [this water rocket video](http://www.youtube.com/watch?v=CAAhQ6xcAnw), which appears to attain sufficient altitude. The group that makes them has a nice website and [tutorial](http://www.aircommandrockets.com/). Perhaps launching black powder based rockets from a boat might be an alternative solution.
You can also take a look at the line of model rockets called the Micro Maxx series and similar. They are made by the [Model Aerospace Company](http://www.modelaerospace.com/macmicro.php), and have a max launch height of 80 feet. These could be launched in just about any large, empty parking lot or baseball field (Barring local ordinances of course).
9,543
Does the nature of the assortment of virtual particles depend upon the warping of spacetime in a direct manner ?
2011/05/06
[ "https://physics.stackexchange.com/questions/9543", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/14207/" ]
EAMann, I know this is a physics site, and you are looking for a physics answer; but I noticed that you are in Portland, Oregon. It seems amazing to me that you can not find a site reasonably close. If nothing is closer, it seems to me that one of your beautiful beaches would make a nice launch site. That is (IIRC) more than an hour away, but you could combine it with a camping trip. My high school biology professor used to take us out to the Gingko petrified forest in eastern WA. Along the way we would stop and jump down the sand dunes on the WA side of the Columbia River, not too far (a few hours) from where you are. There is a lot of desert in eastern WA and eastern OR. Can't imagine not being able to find a launch site out there. The other thing I would do is network through your own organization, BSA, to find out where other nearby scout troops are going. I hope this helps.
This doesn't answer the question, but it does solve the problem. Do it on the 4th of July along side your neighbors who (I assume) will also be launching bottle rockets etc. Here in South Carolina it sounds like a war zone on the 4th from about 8-12pm. It that doesn't work, maybe ask to do it before/after a fireworks display?
9,543
Does the nature of the assortment of virtual particles depend upon the warping of spacetime in a direct manner ?
2011/05/06
[ "https://physics.stackexchange.com/questions/9543", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/14207/" ]
EAMann, I know this is a physics site, and you are looking for a physics answer; but I noticed that you are in Portland, Oregon. It seems amazing to me that you can not find a site reasonably close. If nothing is closer, it seems to me that one of your beautiful beaches would make a nice launch site. That is (IIRC) more than an hour away, but you could combine it with a camping trip. My high school biology professor used to take us out to the Gingko petrified forest in eastern WA. Along the way we would stop and jump down the sand dunes on the WA side of the Columbia River, not too far (a few hours) from where you are. There is a lot of desert in eastern WA and eastern OR. Can't imagine not being able to find a launch site out there. The other thing I would do is network through your own organization, BSA, to find out where other nearby scout troops are going. I hope this helps.
You really need to look into Water Rockets as the ideal solution to your problem. In addition to being cold and the opposite of flame/fire, they are dirt cheap and very easy to make. The coolest thing about them is that they can be a lot more powerful than the little pyro rockets you have been using, so you can put some really impressive payloads onboard and conduct real science you would otherwise be unable to do (unless you have deep pockets and special high power certifications for pyro rockets). I found [this cool website](http://www.uswaterrockets.com "U.S. Water Rockets Home Page") where these guys show how to make different water rockets, and different launchers for them. Some of their experiments are interesting. They load multiple cameras on their rockets and they even have free instructions for making some kind of servo motorized parachute ejection system they invented. These guys seem to be like the NASA of Water Rockets, and hold the world record for altitude (over 2000 feet!) Water rockets have come a long way since those silly plastic pump toys!
9,543
Does the nature of the assortment of virtual particles depend upon the warping of spacetime in a direct manner ?
2011/05/06
[ "https://physics.stackexchange.com/questions/9543", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/14207/" ]
EAMann, I know this is a physics site, and you are looking for a physics answer; but I noticed that you are in Portland, Oregon. It seems amazing to me that you can not find a site reasonably close. If nothing is closer, it seems to me that one of your beautiful beaches would make a nice launch site. That is (IIRC) more than an hour away, but you could combine it with a camping trip. My high school biology professor used to take us out to the Gingko petrified forest in eastern WA. Along the way we would stop and jump down the sand dunes on the WA side of the Columbia River, not too far (a few hours) from where you are. There is a lot of desert in eastern WA and eastern OR. Can't imagine not being able to find a launch site out there. The other thing I would do is network through your own organization, BSA, to find out where other nearby scout troops are going. I hope this helps.
You can also take a look at the line of model rockets called the Micro Maxx series and similar. They are made by the [Model Aerospace Company](http://www.modelaerospace.com/macmicro.php), and have a max launch height of 80 feet. These could be launched in just about any large, empty parking lot or baseball field (Barring local ordinances of course).
9,543
Does the nature of the assortment of virtual particles depend upon the warping of spacetime in a direct manner ?
2011/05/06
[ "https://physics.stackexchange.com/questions/9543", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/14207/" ]
You really need to look into Water Rockets as the ideal solution to your problem. In addition to being cold and the opposite of flame/fire, they are dirt cheap and very easy to make. The coolest thing about them is that they can be a lot more powerful than the little pyro rockets you have been using, so you can put some really impressive payloads onboard and conduct real science you would otherwise be unable to do (unless you have deep pockets and special high power certifications for pyro rockets). I found [this cool website](http://www.uswaterrockets.com "U.S. Water Rockets Home Page") where these guys show how to make different water rockets, and different launchers for them. Some of their experiments are interesting. They load multiple cameras on their rockets and they even have free instructions for making some kind of servo motorized parachute ejection system they invented. These guys seem to be like the NASA of Water Rockets, and hold the world record for altitude (over 2000 feet!) Water rockets have come a long way since those silly plastic pump toys!
This doesn't answer the question, but it does solve the problem. Do it on the 4th of July along side your neighbors who (I assume) will also be launching bottle rockets etc. Here in South Carolina it sounds like a war zone on the 4th from about 8-12pm. It that doesn't work, maybe ask to do it before/after a fireworks display?
9,543
Does the nature of the assortment of virtual particles depend upon the warping of spacetime in a direct manner ?
2011/05/06
[ "https://physics.stackexchange.com/questions/9543", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/14207/" ]
You really need to look into Water Rockets as the ideal solution to your problem. In addition to being cold and the opposite of flame/fire, they are dirt cheap and very easy to make. The coolest thing about them is that they can be a lot more powerful than the little pyro rockets you have been using, so you can put some really impressive payloads onboard and conduct real science you would otherwise be unable to do (unless you have deep pockets and special high power certifications for pyro rockets). I found [this cool website](http://www.uswaterrockets.com "U.S. Water Rockets Home Page") where these guys show how to make different water rockets, and different launchers for them. Some of their experiments are interesting. They load multiple cameras on their rockets and they even have free instructions for making some kind of servo motorized parachute ejection system they invented. These guys seem to be like the NASA of Water Rockets, and hold the world record for altitude (over 2000 feet!) Water rockets have come a long way since those silly plastic pump toys!
You can also take a look at the line of model rockets called the Micro Maxx series and similar. They are made by the [Model Aerospace Company](http://www.modelaerospace.com/macmicro.php), and have a max launch height of 80 feet. These could be launched in just about any large, empty parking lot or baseball field (Barring local ordinances of course).
8,638,775
I have a problem I'm hoping someone has come across and can help. I had a similar question posted (solved), but have had no further help with a new issue, so I thought I'd post with that question (sorry if this is taboo). ``` <table border="1" class="autoTable"> <tr> <td>Description</td><td>Stocked</td><td>Quantity</td><td>Part Price</td> <td>Hours</td> <td>Rate Class</td><td>Total</td><td>Approved</td><td>Add New Row</td> <td>Remove Row</td></tr> <tr> <td><input name="description[]" id="description" value="<?php echo $description; ?>" size="55" class="numeric add_to_total" onKeyPress="return disableEnterKey(event)" /> </td><td align="center"><input type="checkbox" name="stocked[]" id="stocked" value="<?php echo $stocked; ?>" size="5" class="numeric add_to_total" onKeyPress="return disableEnterKey(event)" /> </td><td><input name="quantity[]" id="quantity" value="<?php echo $quantity; ?>" size="5" class="numeric add_to_total quantity" onKeyPress="return disableEnterKey(event)" /> </td><td><input name="partPrice[]" id="partPrice" value="<?php echo $partPrice; ?>" size="10" class="numeric add_to_total part" onKeyPress="return disableEnterKey(event)" /> </td><td><input name="hours[]" id="hours" value="<?php echo $hours; ?>" size="10" class="numeric add_to_total hours" onKeyPress="return disableEnterKey(event)" /> </td><td><select name="rate[]" id="rate" class="numeric add_to_total rate" onKeyPress="return disableEnterKey(event)"> <?php //php code here for rates ?> </select> </td><td><input name="total[]" id="total" size="10" class="numeric is_total" onKeyPress="return disableEnterKey(event)" /> </td><td align="center"><input type="checkbox" name="approved[]" id="approved" value="<?php echo $approved; ?>" size="10" onKeyPress="return disableEnterKey(event)" /> </td><td align="center"><img src="img/plus.png" width="25" height="25" id="addButton" title="Add New Row" class="addRow" /> </td><td align="center"><img src="img/x.png" width="25" height="25" id="removeButton" title="Remove Row" class="delRow" /> </td></tr> </table> ``` I use the following code to add up the total row, but it doesn't work for the second and subsequent dynamic rows. ``` $(".add_to_total").change(function() { var total = 0; $(".add_to_total").each(function() { var quantity = parseFloat($(".quantity").val()) || 0; var part = parseFloat($(".part").val()) || 0; var hours = parseFloat($(".hours").val()) || 0; var rate = parseFloat($(".rate").val()) || 0; total = (Number(quantity) * Number(part)) + (Number(rate) * Number(hours)); }); $(".is_total").val(total); }); ``` I'm hoping someone can help me...I've tried everything I can think of, and I really want to get this thing solved, and move on with my life :) Thanks in advance.
2011/12/26
[ "https://Stackoverflow.com/questions/8638775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112780/" ]
I don't see where the classes `add_to_total`, `quantity`, `part`, `hours`, `rate` or `is_total` are in your HTML, or which elements you're trying to select in your Javascript as a result...hope this helps... ***EDIT:*** Thinking about it again, it might be as a result of the newly-added rows' `add_to_total` classed elements *not* being bound to change events. Have you considered using the `.live()` / `.on()` jQuery events (depending on what version of jQuery you're using)? <http://api.jquery.com/live/> (jQuery < 1.7) <http://api.jquery.com/on/> (jQuery >= 1.7) Maybe implemented something like this: ``` // using the .live() event... $(".add_to_total").live('change', function(){ ... }); // using the .on() event... $(".add_to_total").on('change', function(){ ... }); ``` ***EDIT:*** Haha! Hopefully the last edit! Well, considering the following code: ``` var quantity = parseFloat($(".quantity").val()) || 0; ``` This will always return the **first** `$(".quantity")`'s value, although a set of elements is actually selected...this is just the functionality of the `.val()` function in jQuery. What you're looking to do is process calculations for each of the rows, like you said. Simplified, you need to get the `TR` element for the current `add_to_total`, only focus on its children, then move on. Obviously this is processing a LOT of unnecessary calculations, and I would suggest rather adding a class to each of the rows which need to have calculations run on them and loop through them directly rather: ``` <tr class="dynamic_row"> ... </tr> ``` Then in the Javascript: ``` $(".add_to_total").on('change', function() { var total = 0; $(".dynamic_row").each(function() { var row = $(this); var quantity = parseFloat(row.find(".quantity").val()) || 0; var part = parseFloat(row.find(".part").val()) || 0; var hours = parseFloat(row.find(".hours").val()) || 0; var rate = parseFloat(row.find(".rate").val()) || 0; total = (Number(quantity) * Number(part)) + (Number(rate) * Number(hours)); }); row.find(".is_total").val(total); }); ``` Hope this helps! :)
Thanks to Chris' suggestion, I moved the `row.find(".is_total").val(total);` associated to the row. In his suggestion, he had it outside the element where it was declared, so I *think* the function didn't know what we were talking about. I also changed the `$(".add_to_total").change(function() {` to: `$(".add_to_total").live('change',function() {` in order to make it function on each occurance, as I understand it from his Edit #3. So the final function to calculate the totals is: ``` $(".add_to_total").live('change',function() { var total = 0; $(".dynamic_row").each(function() { var row = $(this); var quantity = parseFloat(row.find(".quantity").val()) || 0; var part = parseFloat(row.find(".part").val()) || 0; var hours = parseFloat(row.find(".hours").val()) || 0; var rate = parseFloat(row.find(".rate").val()) || 0; total = (Number(quantity) * Number(part)) + (Number(rate) * Number(hours)); row.find(".is_total").val(total); }); }); ``` Since I'm a relatively newcomer to Stack Overflow, I'm not sure how to give him any credit, other than to accept his as an accepted answer, and to uptick the Useful option. Thank you VERY much!
9,342
I have written a library. It compiles. It has basic unit tests. - One could say it works. However, I would like to improve the usability of the API and get general feedback. Am I allowed to open a question about the library in codereview? I was not sure, being that I do not really have a concrete question on what I want to get reviewed...
2019/09/21
[ "https://codereview.meta.stackexchange.com/questions/9342", "https://codereview.meta.stackexchange.com", "https://codereview.meta.stackexchange.com/users/209950/" ]
> > I'm not asking to review the code > > > This alone dismisses the idea of a meta-review as invalid, for me. We only review code. The OP could easily just post the new code and receive valuable feedback about it. Whether that's feedback about portions of the new code that have been affected by the changeset or portions of the new code that were unaffected is fairly immaterial. One of our express policies is that any insightful observation about a post's code is on-topic, whether it match the OP's stated review goals or not. Constraining the question to say "don't review this old code - it's not applicable; only review the diff between the old and new code" confuses the matter. Among other things, it hinders question searchability - what if someone searches for a particular code construct and finds a match only in the old code, and there's by design no commentary on it at all?
We have a tag [comparative-review](https://codereview.stackexchange.com/questions/tagged/comparative-review "show questions tagged 'comparative-review'"). I believe this indicates that we do support these kinds of reviews. The user went one step further by including the git diff; I don't see that as a problem.
1,771,057
strange bug: i have an ajax datepicker added to a text box of my form. i submit the form.. and I could receive all values excepting those of the datepicker checkboxes. why is the .Text property empty of this elements? Thanks
2009/11/20
[ "https://Stackoverflow.com/questions/1771057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/141235/" ]
Is your TextBox disabled for user input, so that it might only be changed by javascript, by the datepicker? The problem in that case, is that .NET "knows" that the control is disabled, and just assumes that the value cannot, then, have changed since it was rendered. So .NET will use the ViewStated value immediately, without checking the POST data. There are two solutions to this: 1. Don't render the TextBox as disabled, but disable it with the datepicker script 2. Instead of relying on the TextBox's `Text` property, check `Request.Form[myTextBox.ClientID]`
Try accessing SelectedDate instead of Text.
50,544,555
How would I execute command like this from the Controller? Package I am using that gives the below artisan commands: <https://github.com/JosephSilber/page-cache> ``` php artisan page-cache:clear {slug} ``` For example if typed manually: ``` php artisan page-cache:clear about-us ``` Laravel docs gives us this: <https://laravel.com/docs/5.6/artisan#programmatically-executing-commands> ``` Artisan::call('email:send', [ 'user' => 1, '--queue' => 'default' ]); ``` Since the artisan command page-cache:clear does not take any named parameters, how do I send the slug parameter to it? I've tried this: ``` Artisan::call('page-cache:clear ' . $content->slug); ``` And get back this error: > > Command "page-cache:clear hem" is not defined.↵↵Did you mean this?↵ page-cache:clear > > > I've also tried this: ``` Artisan::call('page-cache:clear', [$content->slug]); ``` But then slug is not added and it calls `php artisan page-cache:clear` without slug so this package clears all the cached files.
2018/05/26
[ "https://Stackoverflow.com/questions/50544555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1080420/" ]
In the end, I discovered some requests sent to my auth service which didn't set the session cookie, for some paths it wasn't even supposed to be used. So I defined those paths related to session with: ```js const sessionPaths = ['/path1', '/path2', ...]; app.use(sessionPaths, session(sessionOptions)); app.use(sessionPaths, passport.initialize()); app.use(sessionPaths, passport.session()); app.use(sessionPaths, csrf()); ```
I had run in to the same issue a few days back! I have set up my repo and sharing my link to the same! It works perfect! Do check it out. <https://github.com/ritwbanerjee/angular-node-seed>
50,544,555
How would I execute command like this from the Controller? Package I am using that gives the below artisan commands: <https://github.com/JosephSilber/page-cache> ``` php artisan page-cache:clear {slug} ``` For example if typed manually: ``` php artisan page-cache:clear about-us ``` Laravel docs gives us this: <https://laravel.com/docs/5.6/artisan#programmatically-executing-commands> ``` Artisan::call('email:send', [ 'user' => 1, '--queue' => 'default' ]); ``` Since the artisan command page-cache:clear does not take any named parameters, how do I send the slug parameter to it? I've tried this: ``` Artisan::call('page-cache:clear ' . $content->slug); ``` And get back this error: > > Command "page-cache:clear hem" is not defined.↵↵Did you mean this?↵ page-cache:clear > > > I've also tried this: ``` Artisan::call('page-cache:clear', [$content->slug]); ``` But then slug is not added and it calls `php artisan page-cache:clear` without slug so this package clears all the cached files.
2018/05/26
[ "https://Stackoverflow.com/questions/50544555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1080420/" ]
Not sure if this is completely solved but given the order of how you lay it out, you might have the cors handler after the session handler. As the preflight requests come in a session is possibly being created for each of those as there is no session cookie or credentials being sent. The simple fix is to move the cors handler above the session handler.
I had run in to the same issue a few days back! I have set up my repo and sharing my link to the same! It works perfect! Do check it out. <https://github.com/ritwbanerjee/angular-node-seed>
50,544,555
How would I execute command like this from the Controller? Package I am using that gives the below artisan commands: <https://github.com/JosephSilber/page-cache> ``` php artisan page-cache:clear {slug} ``` For example if typed manually: ``` php artisan page-cache:clear about-us ``` Laravel docs gives us this: <https://laravel.com/docs/5.6/artisan#programmatically-executing-commands> ``` Artisan::call('email:send', [ 'user' => 1, '--queue' => 'default' ]); ``` Since the artisan command page-cache:clear does not take any named parameters, how do I send the slug parameter to it? I've tried this: ``` Artisan::call('page-cache:clear ' . $content->slug); ``` And get back this error: > > Command "page-cache:clear hem" is not defined.↵↵Did you mean this?↵ page-cache:clear > > > I've also tried this: ``` Artisan::call('page-cache:clear', [$content->slug]); ``` But then slug is not added and it calls `php artisan page-cache:clear` without slug so this package clears all the cached files.
2018/05/26
[ "https://Stackoverflow.com/questions/50544555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1080420/" ]
Not sure if this is completely solved but given the order of how you lay it out, you might have the cors handler after the session handler. As the preflight requests come in a session is possibly being created for each of those as there is no session cookie or credentials being sent. The simple fix is to move the cors handler above the session handler.
In the end, I discovered some requests sent to my auth service which didn't set the session cookie, for some paths it wasn't even supposed to be used. So I defined those paths related to session with: ```js const sessionPaths = ['/path1', '/path2', ...]; app.use(sessionPaths, session(sessionOptions)); app.use(sessionPaths, passport.initialize()); app.use(sessionPaths, passport.session()); app.use(sessionPaths, csrf()); ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
You should use a `for` loop instead of a `foreach` loop like so: ``` for($i = 0; $i < count($children); $i+=2) { $child1 = $children[$i]; $child2 = $children[$i+1]; // print both } ``` if you may have an odd number of children you have to check if `$i+1 < count($children)` before printing it.
Try this ``` $i = 1; //Build custom items foreach($children as $child){ if($i>2){ $i =1; } if ($i==2) { //close row } $i++; } ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
you're almost there: ``` //Build custom items echo "<row>"; $i = 0; foreach($children as $child) { echo "item "; $i++; if ($i % 2 == 0 && $i != count($children)) { echo "</row><row>"; } } echo "</row>" ```
> > This is in Wordpress but understands it and it will help you. > > > ``` <?php $query = new WP_Query( array( 'post_type' => 'slides', 'order'=> 'DESC', 'post_status' => 'publish', 'posts_per_page' => -1) ); $posts = $query->posts; $numOfCols = 2; $rowCount = 0; if(!empty($posts)){ ?> <div class="carousel-item <?php echo ($numOfCols-1==1)?'active':''; ?>"> <div class="row"> <?php foreach ($posts as $post) { ?> <div class="col-md-6 pt-4 pb-0 " > <h6 class="mb-2 text-uppercase"><b><a href="<?php echo get_permalink( $post->ID); ?>" target="_blank"><?php echo $post->post_title; ?></a></b></h6> <span><?php echo get_the_excerpt($post->ID); ?></span><span class="float-right"><a href="<?php echo get_permalink( $post->ID); ?>" target="_blank"><i _ngcontent-ttx-c19="" class="material-icons icon-image-preview" style="position: relative; top: 7px;">arrow_forward</i></a></span> </div> <?php $rowCount++; if($rowCount % $numOfCols == 0 && $rowCount != count($posts)) echo '</div></div><div class="carousel-item "><div class="row"> '; } ?> </div> </div> <?php } ?> ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
``` # Process every second item starting with the first one [0]. foreach ($array as $key => $value) { if (($key - 1) % 2 === 0) { continue; } # Do something here. } ```
Try this ``` $i = 1; //Build custom items foreach($children as $child){ if($i>2){ $i =1; } if ($i==2) { //close row } $i++; } ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
you're almost there: ``` //Build custom items echo "<row>"; $i = 0; foreach($children as $child) { echo "item "; $i++; if ($i % 2 == 0 && $i != count($children)) { echo "</row><row>"; } } echo "</row>" ```
Or this: ``` <?php $i=0; foreach($children as $child){ ++$i; if($i==1){ echo "<row>"; echo "<item>$child</item>"; } if($i==2){ echo "<item>$child</item>"; echo "</row>" $i=0; } } ``` [UPDATE] This bugs me: An odd count of children could possibly lead to a row without closing tag. While most Browser will just add the tag on render and you will have no problems at all, this is still not 100% correct. On odd children count, you would want a check and a closing row after the foreach loop like this: ``` if($i==1){ echo "</row>"; } ``` If $i == 1 after the loop, it was an odd count of children, and the row have to be closed. [/UPDATE]
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
Or this: ``` <?php $i=0; foreach($children as $child){ ++$i; if($i==1){ echo "<row>"; echo "<item>$child</item>"; } if($i==2){ echo "<item>$child</item>"; echo "</row>" $i=0; } } ``` [UPDATE] This bugs me: An odd count of children could possibly lead to a row without closing tag. While most Browser will just add the tag on render and you will have no problems at all, this is still not 100% correct. On odd children count, you would want a check and a closing row after the foreach loop like this: ``` if($i==1){ echo "</row>"; } ``` If $i == 1 after the loop, it was an odd count of children, and the row have to be closed. [/UPDATE]
``` # Process every second item starting with the first one [0]. foreach ($array as $key => $value) { if (($key - 1) % 2 === 0) { continue; } # Do something here. } ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
Or this: ``` <?php $i=0; foreach($children as $child){ ++$i; if($i==1){ echo "<row>"; echo "<item>$child</item>"; } if($i==2){ echo "<item>$child</item>"; echo "</row>" $i=0; } } ``` [UPDATE] This bugs me: An odd count of children could possibly lead to a row without closing tag. While most Browser will just add the tag on render and you will have no problems at all, this is still not 100% correct. On odd children count, you would want a check and a closing row after the foreach loop like this: ``` if($i==1){ echo "</row>"; } ``` If $i == 1 after the loop, it was an odd count of children, and the row have to be closed. [/UPDATE]
Try this ``` $i = 1; //Build custom items foreach($children as $child){ if($i>2){ $i =1; } if ($i==2) { //close row } $i++; } ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
You should use a `for` loop instead of a `foreach` loop like so: ``` for($i = 0; $i < count($children); $i+=2) { $child1 = $children[$i]; $child2 = $children[$i+1]; // print both } ``` if you may have an odd number of children you have to check if `$i+1 < count($children)` before printing it.
``` # Process every second item starting with the first one [0]. foreach ($array as $key => $value) { if (($key - 1) % 2 === 0) { continue; } # Do something here. } ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
you're almost there: ``` //Build custom items echo "<row>"; $i = 0; foreach($children as $child) { echo "item "; $i++; if ($i % 2 == 0 && $i != count($children)) { echo "</row><row>"; } } echo "</row>" ```
Try this ``` $i = 1; //Build custom items foreach($children as $child){ if($i>2){ $i =1; } if ($i==2) { //close row } $i++; } ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
> > This is in Wordpress but understands it and it will help you. > > > ``` <?php $query = new WP_Query( array( 'post_type' => 'slides', 'order'=> 'DESC', 'post_status' => 'publish', 'posts_per_page' => -1) ); $posts = $query->posts; $numOfCols = 2; $rowCount = 0; if(!empty($posts)){ ?> <div class="carousel-item <?php echo ($numOfCols-1==1)?'active':''; ?>"> <div class="row"> <?php foreach ($posts as $post) { ?> <div class="col-md-6 pt-4 pb-0 " > <h6 class="mb-2 text-uppercase"><b><a href="<?php echo get_permalink( $post->ID); ?>" target="_blank"><?php echo $post->post_title; ?></a></b></h6> <span><?php echo get_the_excerpt($post->ID); ?></span><span class="float-right"><a href="<?php echo get_permalink( $post->ID); ?>" target="_blank"><i _ngcontent-ttx-c19="" class="material-icons icon-image-preview" style="position: relative; top: 7px;">arrow_forward</i></a></span> </div> <?php $rowCount++; if($rowCount % $numOfCols == 0 && $rowCount != count($posts)) echo '</div></div><div class="carousel-item "><div class="row"> '; } ?> </div> </div> <?php } ?> ```
``` # Process every second item starting with the first one [0]. foreach ($array as $key => $value) { if (($key - 1) % 2 === 0) { continue; } # Do something here. } ```
30,031,751
``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items foreach($children as $child){ $i++; /* if (i % 2 == 0) { ?> <?php } */ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php } else { } ?> </div> </div> <?php } ?> </div> ``` Hi stackers! I need some php help on how to wrap the looped elements. I want to wrap 2 elements in a `<div class="row">.` So basically `<row> <item> <item> </row>` I have tried with some modulo as you can see, some if statements is still there. I set i as 0, and was trying to put `<div class="row">` when 1 % 2 = 0 but found no solution on how to close the tags correctly ( should be closed after the second item) Any chance you could help out me as a novice php hacker? EDIT: ``` <div class="puffar"> <?php //Set up the objects needed $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page')); //Get children $children = ($post->post_parent) ? get_page_children( $post->post_parent, $all_wp_pages ) : get_page_children( $post->ID, $all_wp_pages ); $i = 0; //Build custom items echo "<div class='row'>"; foreach($children as $child){ ?> <div class="col-sm-6"> <div class="puff"> <div class="puff-image-holder"> <?php echo get_the_post_thumbnail( $child->ID, 'full' ); ?> </div> <fieldset class="linedHeadline hlmedium"> <legend><?php echo get_the_title($child->ID); ?></legend> </fieldset> <?php echo get_field("puff_introtext", $child->ID); ?> <?php $values = get_field( 'puff_lanktext', $child->ID ); if (get_field( "popup_eller_lank", $child->ID ) == "popup") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage open-popup" href="<?php echo get_page_link($child->ID); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> </fieldset> <?php } elseif (get_field( "popup_eller_lank", $child->ID ) == "extern") { ?> <fieldset class="linedHeadline hlmedium"> <legend><a class ="linktopage" href="<?php echo get_field( "puff_lank", $child->ID ); ?>"><?php echo get_field( "puff_lanktext", $child->ID ); ?> </a></legend> <?php $i++; if ($i % 2 == 0) { echo "</div><div class='row'>"; } } else { } ?> </div> </div> <?php } ?> </div> </div> ``` This only wraps all my looped items, I want the div class=row to only wrap every 2 items
2015/05/04
[ "https://Stackoverflow.com/questions/30031751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820395/" ]
you're almost there: ``` //Build custom items echo "<row>"; $i = 0; foreach($children as $child) { echo "item "; $i++; if ($i % 2 == 0 && $i != count($children)) { echo "</row><row>"; } } echo "</row>" ```
``` # Process every second item starting with the first one [0]. foreach ($array as $key => $value) { if (($key - 1) % 2 === 0) { continue; } # Do something here. } ```
31,564,683
I wanted to count no. of objects on Google homepage using static programming, i mean without creating object first(the way we do in dynamic one). Pls tell me what is wrong in below statement ``` Set P = Browser("creationtime:=0").page("title:=Google").WebButton("type:=submit","html tag:=INPUT") MsgBox P.Count() ``` Pls help, screenshot of error is attached here. Thanks
2015/07/22
[ "https://Stackoverflow.com/questions/31564683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4824268/" ]
You can get the total number of buttons by using descriptive approach. ``` Set odesc = description.Create() odesc("micclass").value="WebButton" Set i = Browser("creationtime:=0").Page("title:=Google").ChildObjects(odesc) Msgbox i.Count() Set i = Nothing : Set odesc = Nothing ```
You are actually trying to get a count of the **child** webbutton objects on that **page** object. With the original code that you posted, if there is more than one webbutton object on the page with the descriptors you're using, QTP will throw a multiple object matches found error. Nelly's code regarding the description property is what you're after. If you are specifically looking for the count of all webbutton objects with a type:=submit, you can add additional description properties: ``` odesc("micclass").value="WebButton" odesc("type").value="submit" ``` doing this will filter out buttons that don't have the matching type value
59,729,550
I work on an ASP.NET MVC project that I need some help with. I need to be able to create x number of textboxes when the user click "add textbox". When the user enter the page a viewmodel is loaded. This viewmodel need to handle the x number of textboxes that the user create when he is on the page so that when the page is posted these textboxes are part of the model. The model should look something like this.. ``` public class PlanViewModel { public int Id { get; set; } public string Name { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public List<EventViewModel> EventList { get; set; } // this should be the list of textboxes that the user "create" by clicking add new } public class EventViewModel { public string Name { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string Description { get; set; } } ``` I'm kinda lost on how to do this so any help is appreciated. UPDATE I've added this javascript that add textboxes client side.. ``` <script type="text/javascript"> function GetDynamicTextBox(value) { return('<input type="text" name="events[0].Key" value="box1" /><input type="text" name="events[0].Value.StartDate" value="box2"/><button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(this)"><i class="fa fa-angle-right"></i> Remove</button>'); } function AddTextBox() { var div = document.createElement('DIV'); div.innerHTML = GetDynamicTextBox(""); document.getElementById("divcontent").appendChild(div); } function RemoveTextBox(div) { document.getElementById("divcontent").removeChild(div.parentNode); } </script> <div id="divcontent" class="form-group"> <button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button> </div> ``` I think I only need to add unique id's for the textboxes like this... ``` events[0].Key events[1].Key events[2].Key ``` and so on.. But I don't know how. Anyone knows?
2020/01/14
[ "https://Stackoverflow.com/questions/59729550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2153383/" ]
You can add a list of String, like this `public String[] MyTextFields` and then create HTML using Javascript, like this: `<input name="myTextFields[0]"></input>` `<input name="myTextFields[1]"></input>`
In Razor view: ``` @for (var i = 0; i < Model.EventList.Count; i++) { @Html.EditorFor(x => Model.EventList[i].Name) } ``` To set the name attribute of all edited elements in javascript, this is to be called on page load, and any time the collection changes (item is added or removed): ``` var children = document.getElementById("myDIV").children; // TODO: here supposing children are the input elements, may be different on your page (they may be nested in a different way) for (i = 0; i < children.length; i++) { var el = children[i]; el.name = 'EventList[' + i + '].Name'; // TODO: look into source code of the generated page for the actual format of existing elements and then modify the mask accordingly el.id = 'EventList[' + i + '].Name'; } ```
59,729,550
I work on an ASP.NET MVC project that I need some help with. I need to be able to create x number of textboxes when the user click "add textbox". When the user enter the page a viewmodel is loaded. This viewmodel need to handle the x number of textboxes that the user create when he is on the page so that when the page is posted these textboxes are part of the model. The model should look something like this.. ``` public class PlanViewModel { public int Id { get; set; } public string Name { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public List<EventViewModel> EventList { get; set; } // this should be the list of textboxes that the user "create" by clicking add new } public class EventViewModel { public string Name { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string Description { get; set; } } ``` I'm kinda lost on how to do this so any help is appreciated. UPDATE I've added this javascript that add textboxes client side.. ``` <script type="text/javascript"> function GetDynamicTextBox(value) { return('<input type="text" name="events[0].Key" value="box1" /><input type="text" name="events[0].Value.StartDate" value="box2"/><button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(this)"><i class="fa fa-angle-right"></i> Remove</button>'); } function AddTextBox() { var div = document.createElement('DIV'); div.innerHTML = GetDynamicTextBox(""); document.getElementById("divcontent").appendChild(div); } function RemoveTextBox(div) { document.getElementById("divcontent").removeChild(div.parentNode); } </script> <div id="divcontent" class="form-group"> <button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button> </div> ``` I think I only need to add unique id's for the textboxes like this... ``` events[0].Key events[1].Key events[2].Key ``` and so on.. But I don't know how. Anyone knows?
2020/01/14
[ "https://Stackoverflow.com/questions/59729550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2153383/" ]
You can add a list of String, like this `public String[] MyTextFields` and then create HTML using Javascript, like this: `<input name="myTextFields[0]"></input>` `<input name="myTextFields[1]"></input>`
If it is ok to have JS dependency than I suggest to use light Knockout library. It will help you to create/edit/delete your inputs. [Check example in JS fiddle](https://jsfiddle.net/yn9crg6w/). Use HTML to adjust your view. Tag **data-bind** lets you to bind to data and events ``` <button data-bind="click: addInput">Add</button> <div data-bind="foreach: inputs"> <input data-bind="value: text"/><br /> </div> <button data-bind="click: proceed">Proceed</button> <!-- Use Knockout JS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> ``` Then small JS script which handles adding new input and processing data on click. ``` function InputData(text) { let self = this; self.text = text; } function InputViewModel() { let self = this; // Your array of HTML inputs self.inputs = ko.observableArray([new InputData("Default value")]); self.output = ko.observable(); self.addInput = function() { // Dynamically adds new input on user click button "Add" self.inputs.push(new InputData("")); }; self.proceed = function() { // Process all input with their values for (var i = 0; i < self.inputs().length; i++) { console.log(self.inputs()[i].text); } } } // Bind our JS to HTML view ko.applyBindings(new InputViewModel()); ```
59,729,550
I work on an ASP.NET MVC project that I need some help with. I need to be able to create x number of textboxes when the user click "add textbox". When the user enter the page a viewmodel is loaded. This viewmodel need to handle the x number of textboxes that the user create when he is on the page so that when the page is posted these textboxes are part of the model. The model should look something like this.. ``` public class PlanViewModel { public int Id { get; set; } public string Name { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public List<EventViewModel> EventList { get; set; } // this should be the list of textboxes that the user "create" by clicking add new } public class EventViewModel { public string Name { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string Description { get; set; } } ``` I'm kinda lost on how to do this so any help is appreciated. UPDATE I've added this javascript that add textboxes client side.. ``` <script type="text/javascript"> function GetDynamicTextBox(value) { return('<input type="text" name="events[0].Key" value="box1" /><input type="text" name="events[0].Value.StartDate" value="box2"/><button type="button" class="btn btn-sm btn-primary" onclick="RemoveTextBox(this)"><i class="fa fa-angle-right"></i> Remove</button>'); } function AddTextBox() { var div = document.createElement('DIV'); div.innerHTML = GetDynamicTextBox(""); document.getElementById("divcontent").appendChild(div); } function RemoveTextBox(div) { document.getElementById("divcontent").removeChild(div.parentNode); } </script> <div id="divcontent" class="form-group"> <button type="button" class="btn btn-sm btn-primary" onclick="AddTextBox()"><i class="fa fa-angle-right"></i> Add</button> </div> ``` I think I only need to add unique id's for the textboxes like this... ``` events[0].Key events[1].Key events[2].Key ``` and so on.. But I don't know how. Anyone knows?
2020/01/14
[ "https://Stackoverflow.com/questions/59729550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2153383/" ]
In Razor view: ``` @for (var i = 0; i < Model.EventList.Count; i++) { @Html.EditorFor(x => Model.EventList[i].Name) } ``` To set the name attribute of all edited elements in javascript, this is to be called on page load, and any time the collection changes (item is added or removed): ``` var children = document.getElementById("myDIV").children; // TODO: here supposing children are the input elements, may be different on your page (they may be nested in a different way) for (i = 0; i < children.length; i++) { var el = children[i]; el.name = 'EventList[' + i + '].Name'; // TODO: look into source code of the generated page for the actual format of existing elements and then modify the mask accordingly el.id = 'EventList[' + i + '].Name'; } ```
If it is ok to have JS dependency than I suggest to use light Knockout library. It will help you to create/edit/delete your inputs. [Check example in JS fiddle](https://jsfiddle.net/yn9crg6w/). Use HTML to adjust your view. Tag **data-bind** lets you to bind to data and events ``` <button data-bind="click: addInput">Add</button> <div data-bind="foreach: inputs"> <input data-bind="value: text"/><br /> </div> <button data-bind="click: proceed">Proceed</button> <!-- Use Knockout JS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> ``` Then small JS script which handles adding new input and processing data on click. ``` function InputData(text) { let self = this; self.text = text; } function InputViewModel() { let self = this; // Your array of HTML inputs self.inputs = ko.observableArray([new InputData("Default value")]); self.output = ko.observable(); self.addInput = function() { // Dynamically adds new input on user click button "Add" self.inputs.push(new InputData("")); }; self.proceed = function() { // Process all input with their values for (var i = 0; i < self.inputs().length; i++) { console.log(self.inputs()[i].text); } } } // Bind our JS to HTML view ko.applyBindings(new InputViewModel()); ```
36,514,444
Now I am using JPA to access database. I want to get the comments in the specific courses and specific lessons, so the sql would like this: ``` select * from comment where (commentType, commentId) in (("course", "1"), ("lesson", 2)) ``` I use annotation @Query like this: ``` @Query("select c from Comment c where (c.commentType, c.commentId) in :attaches") Page<Comment> findByAttachIn(@Param("attaches") List<String[]> attaches, Pageable pageable); ``` But finally I got the sql like this: ``` select * from comment where (commentType, commentId) in (?) ``` JPA can not translate the array from jql to sql. What shall I do?
2016/04/09
[ "https://Stackoverflow.com/questions/36514444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3453976/" ]
An `IN` expression allows only a single-valued path expressions, so you can't do `(commentType, commentId) in` in a JPQL query.
JPQL BNF documentation is very clear for the IN part ``` in_expression ::= {state_field_path_expression | type_discriminator} [NOT] IN { ( in_item {, in_item}* ) | (subquery) | collection_valued_input_parameter } in_item ::= literal | single_valued_input_parameter ``` Consequently it can be concluded that you can't do that in JPQL. What you can do is do it manually in the WHERE clause ... ``` ... WHERE (commentType = :type1 AND commentId = :id1) OR (commentType = :type2 AND commentId = :id2) OR ... ``` long winded, but gets the answer, and complies with JPQL BNF notation. How you convert standard JPQL into some Spring syntax is left as an exercise to those familiar with that non-standard part
28,702,250
I want to regress y1 with x, then y2 with x and so on and save the slope,intercept,r2 values ,p values etc. to a vector such that the final vector should contain values for `y1...n` even if the value is NA. The following is how my data looks ``` y1 y2 y3 y4 y5 x NA 89 86 91 69 1 NA 86 NA 88 NA 2 NA 86 83 88 66 3 NA 100 NA 102 80 4 ``` Using the following code, the slope values will not be calculated for those columns where all the values of y[,i] are NA but will still be calculated if one of the values is a NA. ``` slope<-0 for(i in 1:length(names(y))){ if (all(is.na(y[,i]))==FALSE) { m <- lm(y[,i] ~ time) slope <- c(slope, m$coefficients[2]) } } ``` However,I still cannot figure out a way by which I maintain the positional information of all y[,i] such that my final vector output would look something like this ``` slope 1 NA 2 9.362637e-01 3 8.461538e-01 4 3.450549e-01 5 6.593407e-01 ``` ANy help will be much appreciated
2015/02/24
[ "https://Stackoverflow.com/questions/28702250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3389264/" ]
`sapply` over the non-x columns of `DF` returning the coefficients if there are any non-NAs in the dependent variable (`y`) and returning NAs otherwise: ``` t(sapply(DF[-6], function(y) if (any(!is.na(y))) coef(lm(y ~ x, DF)) else c(NA, NA))) ``` This gives the following where column 1 is the intercepts and column 2 is the slopes: ``` [,1] [,2] y1 NA NA y2 82.00000 3.300000 y3 87.50000 -1.500000 y4 84.00000 3.300000 y5 63.85714 2.928571 ``` If only the slopes are needed then: ``` matrix(sapply(DF[-6], function(y) if (any(!is.na(y))) coef(lm(y ~ x, DF))[2] else NA)) ```
``` #This is for the slope only. nn<-lapply(paste0("y",1:5),function(i){ if (all(is.na(y[[i]]))==FALSE) {bb<-lm(y[[i]]~x,data=y) return(bb[[1]][2]) }else{ return(NA) } }) do.call(rbind,kk) x [1,] NA [2,] 3.300000 [3,] -1.500000 [4,] 3.300000 [5,] 2.928571 do.call(rbind,nn) ```
63,998,033
Hey I am trying to delete the element I have clicked on My app.js ``` export default class App extends Component { constructor(props) { super(props); this.state = { ninja: [ { name: 'Ryu', age: 30, belt: 'black', id: 1 }, { name: 'Jacy', age: 34, belt: 'yellow', id: 2 }, { name: 'Ikenna', age: 20, belt: 'green', id: 3 }, { name: 'Cole', age: 50, belt: 'red', id: 4 } ] } } deleteNinja (itemToBeDeleted) { console.log(itemToBeDeleted) } render = () => <div> {this .state .ninja .map(function (ninja) { return ( <div> <div>{ninja.name}</div> <div>{ninja.age}</div> <div>{ninja.belt}</div> <button onClick={this .state .deleteNinja .bind(this)}>Delete</button> </div> ) })} </div> } ``` When I add the function deleteninja to my button it tells me cannot read state of undefined. I read something about binding it and still it wont do it. If I remove the button everything works fine
2020/09/21
[ "https://Stackoverflow.com/questions/63998033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13344058/" ]
Your first example was almost right, you just needed to specify the sequence of dates a bit differently. Get set up: ``` library(tidyverse) set.seed(pi) start_date = as.Date("2009-01-01") end_date = as.Date("2020-05-19") ``` Create a bit of demo data for testing: ``` df = expand_grid(site = LETTERS[1:3], type = "cat", date = seq.Date(start_date, end_date, by = "days")) %>% mutate(total = sample(x = 0:3, size = n(), replace = T, prob = c(0.6, 0.1, 0.1, 0.1))) %>% # Randomly remove a bunch of rows. slice(-sample(1:n(), size = 3000)) ``` Your first example was almost right... you just needed to specify the sequence of dates using `seq.Date` instead of the `:` operator. I didn't include your `mutate` line since this sample data date was already in `Date` format. ``` completed_df = df %>% complete(site, type, date = seq.Date(start_date, end_date, by = "days"), fill = list(total = 0)) %>% arrange(site, date) ```
Here's an option using packages from the tidyverse: ``` library(dplyr) library(tidyr) # find all date and site combinations all <- df %>% mutate(date = as.Date(date)) %>% expand(site, date = full_seq(date, 1)) # merge back all date/site combinations to original data df %>% right_join(all, by = c("date", "site")) %>% mutate(total = ifelse(is.na(total), 0, total), type = "cat") %>% arrange(date, site) ```
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
There are no common idioms / patterns that use dynamic downcasting because it is not very useful. The use of downcasting is indicative of a bad design. If you find yourself in a rare situation where you think that you need dynamic downcasting because you've been painted into a corner by the design of a framework or a library, then know that dynamic cast is there for you. But most of the time (hopefully), you are not going to be in that situation. If you cannot think of a case where you would need downcasting, then you are in a good place, and accompanied by most programmers. For static down casting, see dfri's answer.
Often there are APIs or libraries which use callbacks to notify you of events. Those will usually have a tag that you pass that gets passed back to the callback function. The problem with such a system is producing unique tags that can be associated back with a code object. The simplest system is to simply cast a pointer to the object to the tag type. That will fail spectacularly if a callback comes in after the object has been destroyed. I have an alternative, a mixin class that keeps a table of tag numbers and object pointers. The constructor will generate a unique tag ID and place it in a table along with the pointer to the object. The destructor will remove it from the table. But since the pointer stored in the table is the mixin class and not the actual object, you need a cast to make it useful again. ``` template<typename T> T* TagMixin::ObjectFromTag(Tag tag) { TagMixin * p = TableLookup(tag); if (p == nullptr) // (not found) return nullptr; return dynamic_cast<T*>(p); } ```
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
1. You obtain abstract class from external/user code you do not trust too much. And you need to verify that it matches the type(s) you expect. If it doesn't match you report error instead of going UB. Furthermore, it would be a problem if you were to expose too much of your code/classes to users/external code - so you hide them behind interface classes. 2. Useful for general object manager class - which stores abstract class without understanding what are those. So whenever user tries to obtain one of those and cast to appropriate type - it should apply dynamic cast to ensure that user didn't mess up with the types. 3. It is needed for dealing complex classes with non-trivial hierachies - for which simple pointer cast will probably fail. Though, it is ill adviced to deal with such classes in general.
Often there are APIs or libraries which use callbacks to notify you of events. Those will usually have a tag that you pass that gets passed back to the callback function. The problem with such a system is producing unique tags that can be associated back with a code object. The simplest system is to simply cast a pointer to the object to the tag type. That will fail spectacularly if a callback comes in after the object has been destroyed. I have an alternative, a mixin class that keeps a table of tag numbers and object pointers. The constructor will generate a unique tag ID and place it in a table along with the pointer to the object. The destructor will remove it from the table. But since the pointer stored in the table is the mixin class and not the actual object, you need a cast to make it useful again. ``` template<typename T> T* TagMixin::ObjectFromTag(Tag tag) { TagMixin * p = TableLookup(tag); if (p == nullptr) // (not found) return nullptr; return dynamic_cast<T*>(p); } ```
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
The main situations where I've seen downcasting useful in object-oriented frameworks like .NET and Java are those in which all objects implementing a certain interface can be used perform some task a certain way, but some can also be used to perform the task in a faster way. For example, one might have an instance of some type which behaves as a collection that may be read by index, and want to copy a range of items from that type into an array of the item type. If the source object happens to be an instance of a known array-wrapper type that exposes the wrapped array (I think the C++ `Vector<T>` does that), down-casting to that type, accessing the array, and copying elements from it may be much faster than accessing each individual element through the wrapper. In most such cases I've seen, the need for downcasting could have been avoided if the base interface had included more methods whose behavior was specified in a way that could be implemented by all types, even if not all implementations would be useful. For example, a "readable by index" collection could include a function that would return a structure containing either an array reference, an offset, and usable range of subscripts (if it wrapped an accessible backing array), or else a null array offset (if the backing array was inaccessible). At least in .NET and I think in Java (not sure about .NET), invoking a method of an interface an object is known to support is faster than testing whether an object supports an interface. I suspect the reason that Java and .NET didn't include such features in many of their widely used interfaces like `Enumerable<T>` (Java) or `IEnumerable<T>` (.NET) is that they didn't start out with any support for default interface methods, and thus including such methods would have massively increased the amount of bloat in common implementations.
Downcasting is widely used in Unreal Engine. There's even a dedicated `Cast` function that operates on integral representations of `UObject`-derived types which makes it cheap in terms of performance. The engine comes with a base hierarchy of types that are supposed to be inherited and extended in your game module. The thing is these types hold base type pointers to themselves, so when you extend these types you will still use the variables defined by base engine types, unless you define your own - which won't give you the full support though. Code like below is a common sight in Unreal Engine game code bases. ```cpp ACharacter* Character = GetCharacter(); // Base engine character type. AMyCharacter* MyCharacter = Cast<AMyCharacter>(Character); // Extended game character type. MyCharacter->Something(); ``` This is not to say that it's a manifestation of good architecture but certainly a real life example of the practice.
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
The curiously recurring template pattern (CRTP) =============================================== > > where downcasting is actually useful? > > > It is very useful when implementing the [Curiously recurring template pattern](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern): > > > ``` > template <class T> > struct Base > { > void interface() > { > // ... > static_cast<T*>(this)->implementation(); > // ... > } > > static void static_func() > { > // ... > T::static_sub_func(); > // ... > } > }; > > struct Derived : Base<Derived> > { > void implementation(); > static void static_sub_func(); > }; > > ``` > > The common base class template interface provides definitions that delegates calls to the derived class implementations, realized (for non-static member functions) by downcasting the `this` pointer of the base class to a pointer type of the respective derived class (for the particular specialization of the base class template) followed by dispatch to a derived class function. Note that that *downcasting* in this sense needn't necessarily be implemented in terms of dynamic casting; in this example a static cast is used to cast a base class pointer (`this`) to the respective derived class pointer.
Downcasting is widely used in Unreal Engine. There's even a dedicated `Cast` function that operates on integral representations of `UObject`-derived types which makes it cheap in terms of performance. The engine comes with a base hierarchy of types that are supposed to be inherited and extended in your game module. The thing is these types hold base type pointers to themselves, so when you extend these types you will still use the variables defined by base engine types, unless you define your own - which won't give you the full support though. Code like below is a common sight in Unreal Engine game code bases. ```cpp ACharacter* Character = GetCharacter(); // Base engine character type. AMyCharacter* MyCharacter = Cast<AMyCharacter>(Character); // Extended game character type. MyCharacter->Something(); ``` This is not to say that it's a manifestation of good architecture but certainly a real life example of the practice.
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
The main situations where I've seen downcasting useful in object-oriented frameworks like .NET and Java are those in which all objects implementing a certain interface can be used perform some task a certain way, but some can also be used to perform the task in a faster way. For example, one might have an instance of some type which behaves as a collection that may be read by index, and want to copy a range of items from that type into an array of the item type. If the source object happens to be an instance of a known array-wrapper type that exposes the wrapped array (I think the C++ `Vector<T>` does that), down-casting to that type, accessing the array, and copying elements from it may be much faster than accessing each individual element through the wrapper. In most such cases I've seen, the need for downcasting could have been avoided if the base interface had included more methods whose behavior was specified in a way that could be implemented by all types, even if not all implementations would be useful. For example, a "readable by index" collection could include a function that would return a structure containing either an array reference, an offset, and usable range of subscripts (if it wrapped an accessible backing array), or else a null array offset (if the backing array was inaccessible). At least in .NET and I think in Java (not sure about .NET), invoking a method of an interface an object is known to support is faster than testing whether an object supports an interface. I suspect the reason that Java and .NET didn't include such features in many of their widely used interfaces like `Enumerable<T>` (Java) or `IEnumerable<T>` (.NET) is that they didn't start out with any support for default interface methods, and thus including such methods would have massively increased the amount of bloat in common implementations.
Often there are APIs or libraries which use callbacks to notify you of events. Those will usually have a tag that you pass that gets passed back to the callback function. The problem with such a system is producing unique tags that can be associated back with a code object. The simplest system is to simply cast a pointer to the object to the tag type. That will fail spectacularly if a callback comes in after the object has been destroyed. I have an alternative, a mixin class that keeps a table of tag numbers and object pointers. The constructor will generate a unique tag ID and place it in a table along with the pointer to the object. The destructor will remove it from the table. But since the pointer stored in the table is the mixin class and not the actual object, you need a cast to make it useful again. ``` template<typename T> T* TagMixin::ObjectFromTag(Tag tag) { TagMixin * p = TableLookup(tag); if (p == nullptr) // (not found) return nullptr; return dynamic_cast<T*>(p); } ```
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
The curiously recurring template pattern (CRTP) =============================================== > > where downcasting is actually useful? > > > It is very useful when implementing the [Curiously recurring template pattern](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern): > > > ``` > template <class T> > struct Base > { > void interface() > { > // ... > static_cast<T*>(this)->implementation(); > // ... > } > > static void static_func() > { > // ... > T::static_sub_func(); > // ... > } > }; > > struct Derived : Base<Derived> > { > void implementation(); > static void static_sub_func(); > }; > > ``` > > The common base class template interface provides definitions that delegates calls to the derived class implementations, realized (for non-static member functions) by downcasting the `this` pointer of the base class to a pointer type of the respective derived class (for the particular specialization of the base class template) followed by dispatch to a derived class function. Note that that *downcasting* in this sense needn't necessarily be implemented in terms of dynamic casting; in this example a static cast is used to cast a base class pointer (`this`) to the respective derived class pointer.
The main situations where I've seen downcasting useful in object-oriented frameworks like .NET and Java are those in which all objects implementing a certain interface can be used perform some task a certain way, but some can also be used to perform the task in a faster way. For example, one might have an instance of some type which behaves as a collection that may be read by index, and want to copy a range of items from that type into an array of the item type. If the source object happens to be an instance of a known array-wrapper type that exposes the wrapped array (I think the C++ `Vector<T>` does that), down-casting to that type, accessing the array, and copying elements from it may be much faster than accessing each individual element through the wrapper. In most such cases I've seen, the need for downcasting could have been avoided if the base interface had included more methods whose behavior was specified in a way that could be implemented by all types, even if not all implementations would be useful. For example, a "readable by index" collection could include a function that would return a structure containing either an array reference, an offset, and usable range of subscripts (if it wrapped an accessible backing array), or else a null array offset (if the backing array was inaccessible). At least in .NET and I think in Java (not sure about .NET), invoking a method of an interface an object is known to support is faster than testing whether an object supports an interface. I suspect the reason that Java and .NET didn't include such features in many of their widely used interfaces like `Enumerable<T>` (Java) or `IEnumerable<T>` (.NET) is that they didn't start out with any support for default interface methods, and thus including such methods would have massively increased the amount of bloat in common implementations.
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
There are no common idioms / patterns that use dynamic downcasting because it is not very useful. The use of downcasting is indicative of a bad design. If you find yourself in a rare situation where you think that you need dynamic downcasting because you've been painted into a corner by the design of a framework or a library, then know that dynamic cast is there for you. But most of the time (hopefully), you are not going to be in that situation. If you cannot think of a case where you would need downcasting, then you are in a good place, and accompanied by most programmers. For static down casting, see dfri's answer.
Downcasting is widely used in Unreal Engine. There's even a dedicated `Cast` function that operates on integral representations of `UObject`-derived types which makes it cheap in terms of performance. The engine comes with a base hierarchy of types that are supposed to be inherited and extended in your game module. The thing is these types hold base type pointers to themselves, so when you extend these types you will still use the variables defined by base engine types, unless you define your own - which won't give you the full support though. Code like below is a common sight in Unreal Engine game code bases. ```cpp ACharacter* Character = GetCharacter(); // Base engine character type. AMyCharacter* MyCharacter = Cast<AMyCharacter>(Character); // Extended game character type. MyCharacter->Something(); ``` This is not to say that it's a manifestation of good architecture but certainly a real life example of the practice.
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
The curiously recurring template pattern (CRTP) =============================================== > > where downcasting is actually useful? > > > It is very useful when implementing the [Curiously recurring template pattern](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern): > > > ``` > template <class T> > struct Base > { > void interface() > { > // ... > static_cast<T*>(this)->implementation(); > // ... > } > > static void static_func() > { > // ... > T::static_sub_func(); > // ... > } > }; > > struct Derived : Base<Derived> > { > void implementation(); > static void static_sub_func(); > }; > > ``` > > The common base class template interface provides definitions that delegates calls to the derived class implementations, realized (for non-static member functions) by downcasting the `this` pointer of the base class to a pointer type of the respective derived class (for the particular specialization of the base class template) followed by dispatch to a derived class function. Note that that *downcasting* in this sense needn't necessarily be implemented in terms of dynamic casting; in this example a static cast is used to cast a base class pointer (`this`) to the respective derived class pointer.
There are no common idioms / patterns that use dynamic downcasting because it is not very useful. The use of downcasting is indicative of a bad design. If you find yourself in a rare situation where you think that you need dynamic downcasting because you've been painted into a corner by the design of a framework or a library, then know that dynamic cast is there for you. But most of the time (hopefully), you are not going to be in that situation. If you cannot think of a case where you would need downcasting, then you are in a good place, and accompanied by most programmers. For static down casting, see dfri's answer.
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
The curiously recurring template pattern (CRTP) =============================================== > > where downcasting is actually useful? > > > It is very useful when implementing the [Curiously recurring template pattern](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern): > > > ``` > template <class T> > struct Base > { > void interface() > { > // ... > static_cast<T*>(this)->implementation(); > // ... > } > > static void static_func() > { > // ... > T::static_sub_func(); > // ... > } > }; > > struct Derived : Base<Derived> > { > void implementation(); > static void static_sub_func(); > }; > > ``` > > The common base class template interface provides definitions that delegates calls to the derived class implementations, realized (for non-static member functions) by downcasting the `this` pointer of the base class to a pointer type of the respective derived class (for the particular specialization of the base class template) followed by dispatch to a derived class function. Note that that *downcasting* in this sense needn't necessarily be implemented in terms of dynamic casting; in this example a static cast is used to cast a base class pointer (`this`) to the respective derived class pointer.
1. You obtain abstract class from external/user code you do not trust too much. And you need to verify that it matches the type(s) you expect. If it doesn't match you report error instead of going UB. Furthermore, it would be a problem if you were to expose too much of your code/classes to users/external code - so you hide them behind interface classes. 2. Useful for general object manager class - which stores abstract class without understanding what are those. So whenever user tries to obtain one of those and cast to appropriate type - it should apply dynamic cast to ensure that user didn't mess up with the types. 3. It is needed for dealing complex classes with non-trivial hierachies - for which simple pointer cast will probably fail. Though, it is ill adviced to deal with such classes in general.
62,777,681
Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas? ``` def move_zeros(array): n = len(array) count = 0 for i in range(n): if array[i] is not 0: if type(array[i]) != int or type(array[i]) != float: array[count] = array[i] count += 1 else: array[count] = array[i] count += 1 while count < n: array[count] = 0 count += 1 return array ``` This is the failed test: `[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0]` should equal `[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]`. I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.
2020/07/07
[ "https://Stackoverflow.com/questions/62777681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842932/" ]
1. You obtain abstract class from external/user code you do not trust too much. And you need to verify that it matches the type(s) you expect. If it doesn't match you report error instead of going UB. Furthermore, it would be a problem if you were to expose too much of your code/classes to users/external code - so you hide them behind interface classes. 2. Useful for general object manager class - which stores abstract class without understanding what are those. So whenever user tries to obtain one of those and cast to appropriate type - it should apply dynamic cast to ensure that user didn't mess up with the types. 3. It is needed for dealing complex classes with non-trivial hierachies - for which simple pointer cast will probably fail. Though, it is ill adviced to deal with such classes in general.
Downcasting is widely used in Unreal Engine. There's even a dedicated `Cast` function that operates on integral representations of `UObject`-derived types which makes it cheap in terms of performance. The engine comes with a base hierarchy of types that are supposed to be inherited and extended in your game module. The thing is these types hold base type pointers to themselves, so when you extend these types you will still use the variables defined by base engine types, unless you define your own - which won't give you the full support though. Code like below is a common sight in Unreal Engine game code bases. ```cpp ACharacter* Character = GetCharacter(); // Base engine character type. AMyCharacter* MyCharacter = Cast<AMyCharacter>(Character); // Extended game character type. MyCharacter->Something(); ``` This is not to say that it's a manifestation of good architecture but certainly a real life example of the practice.
8,851,260
In [Revealing module pattern](http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript) of JavaScript how to use setTimeout function? Here is the [example](http://jsfiddle.net/ashwinkumark/Lrm3p/). HTML: `<div id="container1"></div>` JavaScript: ``` var classA = (function() { var i = 0; var names = ["a", "b", "c", "d", "e", "f"]; var callTest = function() { for (var n in names) { window.setTimeout(function() { callTest2(names[n]); }, 1000); } }; var callTest2 = function(pName) { $("#container1").append("In callTest " + i+++" " + pName + "<br>"); window.setTimeout(function() { callTest2(pName) }, 10000) }; return { testTheTest: function() { callTest(); } } })(); classA.testTheTest(); ``` Framework: jQuery 1.5.2 When I execute the output is: ``` In callTest 0 f In callTest 1 f In callTest 2 f In callTest 3 f In callTest 4 f In callTest 5 f ``` Instead of: ``` In callTest 0 a In callTest 1 b In callTest 2 c In callTest 3 d In callTest 4 e In callTest 5 f ``` What am I missing? Where am I doing wrong?
2012/01/13
[ "https://Stackoverflow.com/questions/8851260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815812/" ]
I've made a few slight modifications to your code which means it now works as you wish it to: ``` var classA = (function() { var i = 0, names = ["a", "b", "c", "d", "e", "f"], namesLength = names.length, callTest = function() { window.setTimeout(function() { callTest2(0); }, 1000); }, callTest2 = function(pIndex) { if (pIndex < namesLength) { var name = names[pIndex++]; $("#container1").append("In callTest " + i+++" " + name + "<br>"); window.setTimeout(function() { callTest2(pIndex); }, 1000); } }; return { testTheTest: function() { callTest(); } } })(); classA.testTheTest(); ``` Here's a [working example](http://jsfiddle.net/bTLLc/).
cause the function insight setTimeout is calling not in that place, but after 1sec. And when it is called the n is equal to the last index. You have to make n global and increment each time the function is called ``` var classA = (function() { var i = 0; var names = ["a", "b", "c", "d", "e", "f"]; var n = 0; var callTest = function() { for (var i in names) { window.setTimeout(function() { callTest2(names[n]); n++; }, 1000); } }; var callTest2 = function(pName) { $("#container1").append("In callTest " + i+++" " + pName + "<br>"); window.setTimeout(function() { callTest2(pName) }, 10000) }; return { testTheTest: function() { callTest(); } } })(); classA.testTheTest(); ```
8,851,260
In [Revealing module pattern](http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript) of JavaScript how to use setTimeout function? Here is the [example](http://jsfiddle.net/ashwinkumark/Lrm3p/). HTML: `<div id="container1"></div>` JavaScript: ``` var classA = (function() { var i = 0; var names = ["a", "b", "c", "d", "e", "f"]; var callTest = function() { for (var n in names) { window.setTimeout(function() { callTest2(names[n]); }, 1000); } }; var callTest2 = function(pName) { $("#container1").append("In callTest " + i+++" " + pName + "<br>"); window.setTimeout(function() { callTest2(pName) }, 10000) }; return { testTheTest: function() { callTest(); } } })(); classA.testTheTest(); ``` Framework: jQuery 1.5.2 When I execute the output is: ``` In callTest 0 f In callTest 1 f In callTest 2 f In callTest 3 f In callTest 4 f In callTest 5 f ``` Instead of: ``` In callTest 0 a In callTest 1 b In callTest 2 c In callTest 3 d In callTest 4 e In callTest 5 f ``` What am I missing? Where am I doing wrong?
2012/01/13
[ "https://Stackoverflow.com/questions/8851260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815812/" ]
I've made a few slight modifications to your code which means it now works as you wish it to: ``` var classA = (function() { var i = 0, names = ["a", "b", "c", "d", "e", "f"], namesLength = names.length, callTest = function() { window.setTimeout(function() { callTest2(0); }, 1000); }, callTest2 = function(pIndex) { if (pIndex < namesLength) { var name = names[pIndex++]; $("#container1").append("In callTest " + i+++" " + name + "<br>"); window.setTimeout(function() { callTest2(pIndex); }, 1000); } }; return { testTheTest: function() { callTest(); } } })(); classA.testTheTest(); ``` Here's a [working example](http://jsfiddle.net/bTLLc/).
``` for (var n in names) { window.setTimeout(function() { callTest2(names[n]); }, 1000); } ``` Code above is equivalent to below code. ``` callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); ``` Why..? Reason is function callTest2() is called after completion of one second, but before that whole names[] array is already iterated and "f" last character is passed to function callTest2. For loop is iternated at very little fraction of micro-second. i.e. names[] array will be iterated in very little time. At the end last character remains as "f" i.e. names[n].
8,851,260
In [Revealing module pattern](http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript) of JavaScript how to use setTimeout function? Here is the [example](http://jsfiddle.net/ashwinkumark/Lrm3p/). HTML: `<div id="container1"></div>` JavaScript: ``` var classA = (function() { var i = 0; var names = ["a", "b", "c", "d", "e", "f"]; var callTest = function() { for (var n in names) { window.setTimeout(function() { callTest2(names[n]); }, 1000); } }; var callTest2 = function(pName) { $("#container1").append("In callTest " + i+++" " + pName + "<br>"); window.setTimeout(function() { callTest2(pName) }, 10000) }; return { testTheTest: function() { callTest(); } } })(); classA.testTheTest(); ``` Framework: jQuery 1.5.2 When I execute the output is: ``` In callTest 0 f In callTest 1 f In callTest 2 f In callTest 3 f In callTest 4 f In callTest 5 f ``` Instead of: ``` In callTest 0 a In callTest 1 b In callTest 2 c In callTest 3 d In callTest 4 e In callTest 5 f ``` What am I missing? Where am I doing wrong?
2012/01/13
[ "https://Stackoverflow.com/questions/8851260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815812/" ]
cause the function insight setTimeout is calling not in that place, but after 1sec. And when it is called the n is equal to the last index. You have to make n global and increment each time the function is called ``` var classA = (function() { var i = 0; var names = ["a", "b", "c", "d", "e", "f"]; var n = 0; var callTest = function() { for (var i in names) { window.setTimeout(function() { callTest2(names[n]); n++; }, 1000); } }; var callTest2 = function(pName) { $("#container1").append("In callTest " + i+++" " + pName + "<br>"); window.setTimeout(function() { callTest2(pName) }, 10000) }; return { testTheTest: function() { callTest(); } } })(); classA.testTheTest(); ```
``` for (var n in names) { window.setTimeout(function() { callTest2(names[n]); }, 1000); } ``` Code above is equivalent to below code. ``` callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); callTest2("f"); ``` Why..? Reason is function callTest2() is called after completion of one second, but before that whole names[] array is already iterated and "f" last character is passed to function callTest2. For loop is iternated at very little fraction of micro-second. i.e. names[] array will be iterated in very little time. At the end last character remains as "f" i.e. names[n].
38,811,754
This is my code: ``` def fun_one(x): total = x + 5 return total def fun_two(y): y += 5 return y fun_one(5) print(fun_two(fun_one())) ``` Now here I want to pass `fun_one`'s return value as argument to `fun_two`. How to do it?
2016/08/07
[ "https://Stackoverflow.com/questions/38811754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6570112/" ]
You can do it as: ``` def fun_one(x): total = x + 5 return total def fun_two(y): y += 5 return y print(fun_two(fun_one(5))) ``` Or you can also do it as: ``` def fun_one(x): total = x + 5 return total def fun_two(y): y += 5 return y temp=fun_one(5) print(fun_two(temp)) ```
Call your `fun_one(5)` inside `fun_two()` like so: ``` # Replace these lines fun_one(5) print(fun_two(fun_one())) # With this print(fun_two(fun_one(5))) ```
49,796,141
I am trying to update an item on podio through their Java API. It worked fine for a while, but now, but after some time it gave me this error: ``` APIException [status=Conflict, error=conflict, description=A newer version exists , parameters=null] ``` Right now, if I sent another request to update the item that had this error, it will return the same error. I don't understand. What does this error mean? and how do i solve it? Is that item going to give me the same error error forever? Here's a snippet of my code: ``` List<FieldValuesUpdate> fields = new ArrayList<>(); String valueSubId = "value"; fields.add(new FieldValuesUpdate(1234567890, valueSubId, something.getName())); fields.add(new FieldValuesUpdate(1234567891, valueSubId, something.getCode())); fields.add(new FieldValuesUpdate(1234567892, valueSubId, something.getAddress())); fields.add(new FieldValuesUpdate(1234567893, valueSubId, something.getStatus())); ItemUpdate itemUpdate = new ItemUpdate(null, fields); int itemId = 123444; podioItemApi.updateItem(itemId, itemUpdate, true, false); ```
2018/04/12
[ "https://Stackoverflow.com/questions/49796141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206772/" ]
I like @jeprubio's answer above, however I ran into the same issue @desgraci mentioned in the comments, where their matcher is consistently looking for a view on an old, stale rootview. This happens frequently when trying to have transitions between activities in your test. My implementation of the traditional "Implicit Wait" pattern lives in the two Kotlin files below. **EspressoExtensions.kt** contains a function `searchFor` which returns a ViewAction once a match has been found within supplied rootview. ``` class EspressoExtensions { companion object { /** * Perform action of waiting for a certain view within a single root view * @param matcher Generic Matcher used to find our view */ fun searchFor(matcher: Matcher<View>): ViewAction { return object : ViewAction { override fun getConstraints(): Matcher<View> { return isRoot() } override fun getDescription(): String { return "searching for view $matcher in the root view" } override fun perform(uiController: UiController, view: View) { var tries = 0 val childViews: Iterable<View> = TreeIterables.breadthFirstViewTraversal(view) // Look for the match in the tree of childviews childViews.forEach { tries++ if (matcher.matches(it)) { // found the view return } } throw NoMatchingViewException.Builder() .withRootView(view) .withViewMatcher(matcher) .build() } } } } } ``` **BaseRobot.kt** calls the `searchFor()` method, checks if a matcher was returned. If no match is returned, it sleeps a tiny bit and then fetches a new root to match on until it has tried X times, then it throws an exception and the test fails. Confused about what a "Robot" is? Check out [this fantastic talk by Jake Wharton](https://academy.realm.io/posts/kau-jake-wharton-testing-robots/) about the Robot pattern. Its very similar to the Page Object Model pattern ``` open class BaseRobot { fun doOnView(matcher: Matcher<View>, vararg actions: ViewAction) { actions.forEach { waitForView(matcher).perform(it) } } fun assertOnView(matcher: Matcher<View>, vararg assertions: ViewAssertion) { assertions.forEach { waitForView(matcher).check(it) } } /** * Perform action of implicitly waiting for a certain view. * This differs from EspressoExtensions.searchFor in that, * upon failure to locate an element, it will fetch a new root view * in which to traverse searching for our @param match * * @param viewMatcher ViewMatcher used to find our view */ fun waitForView( viewMatcher: Matcher<View>, waitMillis: Int = 5000, waitMillisPerTry: Long = 100 ): ViewInteraction { // Derive the max tries val maxTries = waitMillis / waitMillisPerTry.toInt() var tries = 0 for (i in 0..maxTries) try { // Track the amount of times we've tried tries++ // Search the root for the view onView(isRoot()).perform(searchFor(viewMatcher)) // If we're here, we found our view. Now return it return onView(viewMatcher) } catch (e: Exception) { if (tries == maxTries) { throw e } sleep(waitMillisPerTry) } throw Exception("Error finding a view matching $viewMatcher") } } ``` **To use it** ``` // Click on element withId BaseRobot().doOnView(withId(R.id.viewIWantToFind), click()) // Assert element withId is displayed BaseRobot().assertOnView(withId(R.id.viewIWantToFind), matches(isDisplayed())) ``` I know that [IdlingResource](https://developer.android.com/training/testing/espresso/idling-resource) is what Google preaches to handle asynchronous events in Espresso testing, but it usually requires that you have test specific code (i.e hooks) embedded within your app code in order to synchronize the tests. That seems weird to me, and working on a team with a mature app and multiple developers committing code everyday, it seems like it would be a lot of extra work to retrofit idling resources everywhere in the app just for the sake of tests. Personally, I prefer to keep the app and test code as separate as possible. /end rant
You can either create an [idling resource](https://medium.com/azimolabs/wait-for-it-idlingresource-and-conditionwatcher-602055f32356) or use a custom [ViewAction](https://developer.android.com/reference/android/support/test/espresso/ViewAction.html) as this one: ``` /** * Perform action of waiting for a specific view id. * @param viewId The id of the view to wait for. * @param millis The timeout of until when to wait for. */ public static ViewAction waitId(final int viewId, final long millis) { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isRoot(); } @Override public String getDescription() { return "wait for a specific view with id <" + viewId + "> during " + millis + " millis."; } @Override public void perform(final UiController uiController, final View view) { uiController.loopMainThreadUntilIdle(); final long startTime = System.currentTimeMillis(); final long endTime = startTime + millis; final Matcher<View> viewMatcher = withId(viewId); do { for (View child : TreeIterables.breadthFirstViewTraversal(view)) { // found view with required ID if (viewMatcher.matches(child)) { return; } } uiController.loopMainThreadForAtLeast(50); } while (System.currentTimeMillis() < endTime); // timeout happens throw new PerformException.Builder() .withActionDescription(this.getDescription()) .withViewDescription(HumanReadables.describe(view)) .withCause(new TimeoutException()) .build(); } }; } ``` And you can use it this way: ``` onView(isRoot()).perform(waitId(R.id.theIdToWaitFor, 5000)); ``` changing `theIdToWaitFor` with the specific id and update the timeout of 5 secs (5000 millis) if necessary.
49,796,141
I am trying to update an item on podio through their Java API. It worked fine for a while, but now, but after some time it gave me this error: ``` APIException [status=Conflict, error=conflict, description=A newer version exists , parameters=null] ``` Right now, if I sent another request to update the item that had this error, it will return the same error. I don't understand. What does this error mean? and how do i solve it? Is that item going to give me the same error error forever? Here's a snippet of my code: ``` List<FieldValuesUpdate> fields = new ArrayList<>(); String valueSubId = "value"; fields.add(new FieldValuesUpdate(1234567890, valueSubId, something.getName())); fields.add(new FieldValuesUpdate(1234567891, valueSubId, something.getCode())); fields.add(new FieldValuesUpdate(1234567892, valueSubId, something.getAddress())); fields.add(new FieldValuesUpdate(1234567893, valueSubId, something.getStatus())); ItemUpdate itemUpdate = new ItemUpdate(null, fields); int itemId = 123444; podioItemApi.updateItem(itemId, itemUpdate, true, false); ```
2018/04/12
[ "https://Stackoverflow.com/questions/49796141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206772/" ]
You can either create an [idling resource](https://medium.com/azimolabs/wait-for-it-idlingresource-and-conditionwatcher-602055f32356) or use a custom [ViewAction](https://developer.android.com/reference/android/support/test/espresso/ViewAction.html) as this one: ``` /** * Perform action of waiting for a specific view id. * @param viewId The id of the view to wait for. * @param millis The timeout of until when to wait for. */ public static ViewAction waitId(final int viewId, final long millis) { return new ViewAction() { @Override public Matcher<View> getConstraints() { return isRoot(); } @Override public String getDescription() { return "wait for a specific view with id <" + viewId + "> during " + millis + " millis."; } @Override public void perform(final UiController uiController, final View view) { uiController.loopMainThreadUntilIdle(); final long startTime = System.currentTimeMillis(); final long endTime = startTime + millis; final Matcher<View> viewMatcher = withId(viewId); do { for (View child : TreeIterables.breadthFirstViewTraversal(view)) { // found view with required ID if (viewMatcher.matches(child)) { return; } } uiController.loopMainThreadForAtLeast(50); } while (System.currentTimeMillis() < endTime); // timeout happens throw new PerformException.Builder() .withActionDescription(this.getDescription()) .withViewDescription(HumanReadables.describe(view)) .withCause(new TimeoutException()) .build(); } }; } ``` And you can use it this way: ``` onView(isRoot()).perform(waitId(R.id.theIdToWaitFor, 5000)); ``` changing `theIdToWaitFor` with the specific id and update the timeout of 5 secs (5000 millis) if necessary.
If the text that you're waiting on is in a `TextView` that won't enter the view hierarchy until after the sign-in is complete, then I suggest going with one of the other answers in this thread which operate on the root view (i.e. [here](https://stackoverflow.com/a/49814995/1071320) or [here](https://stackoverflow.com/a/56499223/1071320)). However, if you're waiting on the text to change in a `TextView` that is already present in the view hierarchy, then I would strongly suggest defining a `ViewAction` that operates on the `TextView` itself for better test output in the case of test failure. Defining a `ViewAction` that operates on a particular `TextView` instead of operating on the root view is a three-step process as below. Firstly, define the `ViewAction` class as follows: ``` /** * A [ViewAction] that waits up to [timeout] milliseconds for a [View]'s text to change to [text]. * * @param text the text to wait for. * @param timeout the length of time in milliseconds to wait for. */ class WaitForTextAction(private val text: String, private val timeout: Long) : ViewAction { override fun getConstraints(): Matcher<View> { return isAssignableFrom(TextView::class.java) } override fun getDescription(): String { return "wait up to $timeout milliseconds for the view to have text $text" } override fun perform(uiController: UiController, view: View) { val endTime = System.currentTimeMillis() + timeout do { if ((view as? TextView)?.text == text) return uiController.loopMainThreadForAtLeast(50) } while (System.currentTimeMillis() < endTime) throw PerformException.Builder() .withActionDescription(description) .withCause(TimeoutException("Waited $timeout milliseconds")) .withViewDescription(HumanReadables.describe(view)) .build() } } ``` Secondly, define a helper function that wraps this class as follows: ``` /** * @return a [WaitForTextAction] instance created with the given [text] and [timeout] parameters. */ fun waitForText(text: String, timeout: Long): ViewAction { return WaitForTextAction(text, timeout) } ``` Thirdly and finally, call on the helper function as follows: ``` onView(withId(R.id.someTextView)).perform(waitForText("Some text", 5000)) ```
49,796,141
I am trying to update an item on podio through their Java API. It worked fine for a while, but now, but after some time it gave me this error: ``` APIException [status=Conflict, error=conflict, description=A newer version exists , parameters=null] ``` Right now, if I sent another request to update the item that had this error, it will return the same error. I don't understand. What does this error mean? and how do i solve it? Is that item going to give me the same error error forever? Here's a snippet of my code: ``` List<FieldValuesUpdate> fields = new ArrayList<>(); String valueSubId = "value"; fields.add(new FieldValuesUpdate(1234567890, valueSubId, something.getName())); fields.add(new FieldValuesUpdate(1234567891, valueSubId, something.getCode())); fields.add(new FieldValuesUpdate(1234567892, valueSubId, something.getAddress())); fields.add(new FieldValuesUpdate(1234567893, valueSubId, something.getStatus())); ItemUpdate itemUpdate = new ItemUpdate(null, fields); int itemId = 123444; podioItemApi.updateItem(itemId, itemUpdate, true, false); ```
2018/04/12
[ "https://Stackoverflow.com/questions/49796141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206772/" ]
I like @jeprubio's answer above, however I ran into the same issue @desgraci mentioned in the comments, where their matcher is consistently looking for a view on an old, stale rootview. This happens frequently when trying to have transitions between activities in your test. My implementation of the traditional "Implicit Wait" pattern lives in the two Kotlin files below. **EspressoExtensions.kt** contains a function `searchFor` which returns a ViewAction once a match has been found within supplied rootview. ``` class EspressoExtensions { companion object { /** * Perform action of waiting for a certain view within a single root view * @param matcher Generic Matcher used to find our view */ fun searchFor(matcher: Matcher<View>): ViewAction { return object : ViewAction { override fun getConstraints(): Matcher<View> { return isRoot() } override fun getDescription(): String { return "searching for view $matcher in the root view" } override fun perform(uiController: UiController, view: View) { var tries = 0 val childViews: Iterable<View> = TreeIterables.breadthFirstViewTraversal(view) // Look for the match in the tree of childviews childViews.forEach { tries++ if (matcher.matches(it)) { // found the view return } } throw NoMatchingViewException.Builder() .withRootView(view) .withViewMatcher(matcher) .build() } } } } } ``` **BaseRobot.kt** calls the `searchFor()` method, checks if a matcher was returned. If no match is returned, it sleeps a tiny bit and then fetches a new root to match on until it has tried X times, then it throws an exception and the test fails. Confused about what a "Robot" is? Check out [this fantastic talk by Jake Wharton](https://academy.realm.io/posts/kau-jake-wharton-testing-robots/) about the Robot pattern. Its very similar to the Page Object Model pattern ``` open class BaseRobot { fun doOnView(matcher: Matcher<View>, vararg actions: ViewAction) { actions.forEach { waitForView(matcher).perform(it) } } fun assertOnView(matcher: Matcher<View>, vararg assertions: ViewAssertion) { assertions.forEach { waitForView(matcher).check(it) } } /** * Perform action of implicitly waiting for a certain view. * This differs from EspressoExtensions.searchFor in that, * upon failure to locate an element, it will fetch a new root view * in which to traverse searching for our @param match * * @param viewMatcher ViewMatcher used to find our view */ fun waitForView( viewMatcher: Matcher<View>, waitMillis: Int = 5000, waitMillisPerTry: Long = 100 ): ViewInteraction { // Derive the max tries val maxTries = waitMillis / waitMillisPerTry.toInt() var tries = 0 for (i in 0..maxTries) try { // Track the amount of times we've tried tries++ // Search the root for the view onView(isRoot()).perform(searchFor(viewMatcher)) // If we're here, we found our view. Now return it return onView(viewMatcher) } catch (e: Exception) { if (tries == maxTries) { throw e } sleep(waitMillisPerTry) } throw Exception("Error finding a view matching $viewMatcher") } } ``` **To use it** ``` // Click on element withId BaseRobot().doOnView(withId(R.id.viewIWantToFind), click()) // Assert element withId is displayed BaseRobot().assertOnView(withId(R.id.viewIWantToFind), matches(isDisplayed())) ``` I know that [IdlingResource](https://developer.android.com/training/testing/espresso/idling-resource) is what Google preaches to handle asynchronous events in Espresso testing, but it usually requires that you have test specific code (i.e hooks) embedded within your app code in order to synchronize the tests. That seems weird to me, and working on a team with a mature app and multiple developers committing code everyday, it seems like it would be a lot of extra work to retrofit idling resources everywhere in the app just for the sake of tests. Personally, I prefer to keep the app and test code as separate as possible. /end rant
If the text that you're waiting on is in a `TextView` that won't enter the view hierarchy until after the sign-in is complete, then I suggest going with one of the other answers in this thread which operate on the root view (i.e. [here](https://stackoverflow.com/a/49814995/1071320) or [here](https://stackoverflow.com/a/56499223/1071320)). However, if you're waiting on the text to change in a `TextView` that is already present in the view hierarchy, then I would strongly suggest defining a `ViewAction` that operates on the `TextView` itself for better test output in the case of test failure. Defining a `ViewAction` that operates on a particular `TextView` instead of operating on the root view is a three-step process as below. Firstly, define the `ViewAction` class as follows: ``` /** * A [ViewAction] that waits up to [timeout] milliseconds for a [View]'s text to change to [text]. * * @param text the text to wait for. * @param timeout the length of time in milliseconds to wait for. */ class WaitForTextAction(private val text: String, private val timeout: Long) : ViewAction { override fun getConstraints(): Matcher<View> { return isAssignableFrom(TextView::class.java) } override fun getDescription(): String { return "wait up to $timeout milliseconds for the view to have text $text" } override fun perform(uiController: UiController, view: View) { val endTime = System.currentTimeMillis() + timeout do { if ((view as? TextView)?.text == text) return uiController.loopMainThreadForAtLeast(50) } while (System.currentTimeMillis() < endTime) throw PerformException.Builder() .withActionDescription(description) .withCause(TimeoutException("Waited $timeout milliseconds")) .withViewDescription(HumanReadables.describe(view)) .build() } } ``` Secondly, define a helper function that wraps this class as follows: ``` /** * @return a [WaitForTextAction] instance created with the given [text] and [timeout] parameters. */ fun waitForText(text: String, timeout: Long): ViewAction { return WaitForTextAction(text, timeout) } ``` Thirdly and finally, call on the helper function as follows: ``` onView(withId(R.id.someTextView)).perform(waitForText("Some text", 5000)) ```
1,103,868
i have included DotnetFramework, Windows installer in VS Setup Project through Setup Project ->properties [alt text http://img35.imageshack.us/img35/3158/prerequisite.jpg](http://img35.imageshack.us/img35/3158/prerequisite.jpg) but while run setup.msi it ask me to download dotnet framework from online i would like to eliminate the process, it should be run from local folder
2009/07/09
[ "https://Stackoverflow.com/questions/1103868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107748/" ]
i have found one solution [DotnetInstaller](http://dotnetinstaller.codeplex.com), which is perfectly worked for me
You have to include the actual .NET framework file in your installer then. The properties page simply lists dependencies, but does not actually include them.
1,385,231
If the lines $2x+3y=10$ and $2x-3y=10$ are tangents at the extremities of its same latus rectum to an ellipse whose center is origin,then the length of the latus rectum is $(A)\frac{110}{27}\hspace{1cm}(B)\frac{98}{27}\hspace{1cm}(C)\frac{100}{27}\hspace{1cm}(D)\frac{120}{27}$ I found point of intersection of two tangents at $(5,0)$ but dont know how to solve further.Any guidance will be helpful.
2015/08/05
[ "https://math.stackexchange.com/questions/1385231", "https://math.stackexchange.com", "https://math.stackexchange.com/users/258051/" ]
This would be the fastest. $$ P(2 \leq X\leq 6) = P(X\leq 6) - P(X<2) $$ so this would be $$ P(X=2) + P(X=3) + P(X=4) + P(X=5) + P(X=6) $$
You can also approximate the answer using a normal approximation to the binomial, since $n$ is fairly large: $$X\sim B(100,0.028)$$ can be recast as a normal distribution: $$X\sim N(np,npq) \implies X\sim N(np,np(1-p))$$ so with your numbers, $n=100$, $p=0.028$: $$X\sim N(2.8,2.7216)$$.
1,385,231
If the lines $2x+3y=10$ and $2x-3y=10$ are tangents at the extremities of its same latus rectum to an ellipse whose center is origin,then the length of the latus rectum is $(A)\frac{110}{27}\hspace{1cm}(B)\frac{98}{27}\hspace{1cm}(C)\frac{100}{27}\hspace{1cm}(D)\frac{120}{27}$ I found point of intersection of two tangents at $(5,0)$ but dont know how to solve further.Any guidance will be helpful.
2015/08/05
[ "https://math.stackexchange.com/questions/1385231", "https://math.stackexchange.com", "https://math.stackexchange.com/users/258051/" ]
As far as I know, if $X\sim \mathcal{B}(n,p)$, then it can be approached by the Gaussian distribution $\mathcal{N}\big(np,np(1-p)\big)$, as long as $\mathbf{n\ge 30}$ and $\mathbf{np \ge 5}$, which can give us a fairly good approximation. In that case, we have: $$\Pr(a\le X\le b)\approx \Pr\left(\frac{a - np}{\sqrt{np(1-np)}}\le Z = \frac{X-\mu}{\sigma} \le \frac{b-np}{\sqrt{np(1-p)}}\right),$$ where $\mu = np, \sigma = \sqrt{np(1-p)}$ and $Z \sim \mathcal{N}(0,1)$. In that specific situation we have that $n = 100$ and $p = 0.028$, which implies $np = 2.8$. So, I don't know if that approach would be good enough. * Following the normal procedure, we have (with the help of Mathematica): $$\textbf{prob\_1}=\Pr(2\le X\le 6) = \sum\_{k = 2}^{6}\binom{100}k\cdot 0.028^k \cdot (1-0.028)^{100-k}=\boxed{0.750672}. $$ * Considering the approach by the Gaussian distribution (which is a lot faster in some way), we have: $$\textbf{prob\_2} = \Pr(-0.484929\le Z \le 1.93971) \begin{array}[t]{l} =\Phi(1.93971) - \Phi(-0.484929) \\ =\Phi(1.93971) + \Phi(0.484929)-1 \\ = \boxed{0.65993}. \end{array}$$ As long as $n\ge 30$ and $np\gg 5$, then $\left| \textbf{prob\_1} - \textbf{prob\_2} \right| \to 0$.
You can also approximate the answer using a normal approximation to the binomial, since $n$ is fairly large: $$X\sim B(100,0.028)$$ can be recast as a normal distribution: $$X\sim N(np,npq) \implies X\sim N(np,np(1-p))$$ so with your numbers, $n=100$, $p=0.028$: $$X\sim N(2.8,2.7216)$$.
22,267,875
I'm bringing a web application from PHP core to Laravel 4. In the current application passwords are encrypted with phpass. Encrypted passwords of phpass are compatible with the encryption of laravel? or I have to implement phpass on laravel? Thanks.
2014/03/08
[ "https://Stackoverflow.com/questions/22267875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2352191/" ]
You'll have to replace the default hasher, which uses the Bcrypt hashing algorithm. Here's an example repository which shows how to do it - in his case he's replaced it with a simple MD5, but you can modify it to use whatever algorithm you like. <https://github.com/robclancy/laravel4-hashing>
There is bundle to override bcrypt hashing <https://github.com/ksungcaya/phpass>
29,981,545
From [python docs](https://docs.python.org/3.0/library/heapq.html#heapq.merge). I have found the algorithm in quite a few places such as [here](https://stackoverflow.com/a/5446254/3664835), [here](http://www.geeksforgeeks.org/merge-k-sorted-arrays/) and [here](http://www.careercup.com/question?id=2261). None of them have mentioned the name of the algorithm. I need to give a reference for a paper so please point me in the right direction.
2015/05/01
[ "https://Stackoverflow.com/questions/29981545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3664835/" ]
This is known as *"Multiway merging"* and is described by Donald Knuth in The Art of Computer Programming, Volume III - Sorting and Searching, section 5.4.1.
If you understand merging of sorted lists then that is what this function is basically doing. There is no name for it, other than merging. As an aside, merge-sort uses a similar routine, generally on two sorted lists. It is why it's called 'merge'-sort.
19,282,833
I'm trying to compare two lists of integers, each the same size, in Python 2.6. The comparison I need is to compare the first item in List 1 with the first item in List 2, the second item in List 1 with the second item in List 2, and so on, and returns a result if ALL of the list items follow the same comparison criteria. It should behave as follows: ``` list1 = [1,1,1,1] list2 = [2,1,2,3] compare(list1,list2) # returns a "list 1 is <= list 2" response. list1 = [4,1,4,3] list2 = [2,1,2,3] compare(list1,list2) # returns a "list 1 is >= list 2" response. list1 = [3,2,3,2] list2 = [1,4,1,4] compare(list1,list2) # returns None— some items in list1 > list2, and some items in list2 > list1. ``` I figured I could write the code like the following block, but I don't know if it's the most efficient. My program is going to be calling this method a LOT so I want to streamline this as much as possible. ``` def compare(list1,list2): gt_found = 0 lt_found = 0 for x in range(len(list1)): if list1[x] > list2[x]: gt_found += 1 elif list1[x] < list2[x]: lt_found += 1 if gt_found > 0 and lt_found > 0: return None #(some items >, some items <) if gt_found > 0: return 1 #(list1 >= list2) if lt_found > 0: return -1 #(list1 <= list2) return 0 #(list1 == list2) ``` Is it already as good as it's going to get (big-O of n), or is there a faster way to go about it (or a way that uses system functions instead)? CLARIFICATION: I expect the case that returns 'None' to happen the most often, so it is important.
2013/10/09
[ "https://Stackoverflow.com/questions/19282833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541913/" ]
You can consider a numpy-based vectorized comparison. ``` import numpy as np a = [1,1,1,2] b = [2,2,4,3] all_larger = np.all(np.asarray(b) > np.asarray(a)) # true if b > a holds elementwise print all_larger True ``` Clearly, you can engineer the thing to have your answer. ``` all_larger = lambda b,a : np.all(np.asarray(b) > np.asarray(a)) if all_larger(b,a): print "b > a" elif all_larger(a,b): print "a > b" else print "nothing!" ``` Every type of comparison such as `<, >, <=, >=,` can be done.
Are you familiar with the wonderful `zip` function? ``` import itertools def compare(xs, ys): all_less = True all_greater = True for x, y in itertools.izip(xs, ys): if not all_less and not all_greater: return None if x > y: all_less = False elif x < y: all_greater = False if all_less: return "list 1 is <= list 2" elif all_greater: return "list 1 is >= list 2" return None # all_greater might be set False on final iteration ``` Zip takes two lists (`xs` and `ys` in this case, but call them whatever you want) and creates an iterator for a sequence of tuples. ``` izip([1,2,3,4], [4,3,2,1]) == [(1,4), (2,3), (3,2), (4,1)] ``` This way you can iterate through both lists simultaneously and compare each value in tandem. The time complexity should be O(n), where n is the size of your lists. It will return early in cases where neither the >= or <= condition are met. ### Update As **James Matta** points out, `itertools.izip` performs better than the standard `zip` in Python 2. This isn't true in Python 3, where the standard `zip` works the way `izip` does in older versions.
19,282,833
I'm trying to compare two lists of integers, each the same size, in Python 2.6. The comparison I need is to compare the first item in List 1 with the first item in List 2, the second item in List 1 with the second item in List 2, and so on, and returns a result if ALL of the list items follow the same comparison criteria. It should behave as follows: ``` list1 = [1,1,1,1] list2 = [2,1,2,3] compare(list1,list2) # returns a "list 1 is <= list 2" response. list1 = [4,1,4,3] list2 = [2,1,2,3] compare(list1,list2) # returns a "list 1 is >= list 2" response. list1 = [3,2,3,2] list2 = [1,4,1,4] compare(list1,list2) # returns None— some items in list1 > list2, and some items in list2 > list1. ``` I figured I could write the code like the following block, but I don't know if it's the most efficient. My program is going to be calling this method a LOT so I want to streamline this as much as possible. ``` def compare(list1,list2): gt_found = 0 lt_found = 0 for x in range(len(list1)): if list1[x] > list2[x]: gt_found += 1 elif list1[x] < list2[x]: lt_found += 1 if gt_found > 0 and lt_found > 0: return None #(some items >, some items <) if gt_found > 0: return 1 #(list1 >= list2) if lt_found > 0: return -1 #(list1 <= list2) return 0 #(list1 == list2) ``` Is it already as good as it's going to get (big-O of n), or is there a faster way to go about it (or a way that uses system functions instead)? CLARIFICATION: I expect the case that returns 'None' to happen the most often, so it is important.
2013/10/09
[ "https://Stackoverflow.com/questions/19282833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541913/" ]
Are you familiar with the wonderful `zip` function? ``` import itertools def compare(xs, ys): all_less = True all_greater = True for x, y in itertools.izip(xs, ys): if not all_less and not all_greater: return None if x > y: all_less = False elif x < y: all_greater = False if all_less: return "list 1 is <= list 2" elif all_greater: return "list 1 is >= list 2" return None # all_greater might be set False on final iteration ``` Zip takes two lists (`xs` and `ys` in this case, but call them whatever you want) and creates an iterator for a sequence of tuples. ``` izip([1,2,3,4], [4,3,2,1]) == [(1,4), (2,3), (3,2), (4,1)] ``` This way you can iterate through both lists simultaneously and compare each value in tandem. The time complexity should be O(n), where n is the size of your lists. It will return early in cases where neither the >= or <= condition are met. ### Update As **James Matta** points out, `itertools.izip` performs better than the standard `zip` in Python 2. This isn't true in Python 3, where the standard `zip` works the way `izip` does in older versions.
For anyone interested in the performance of the two methods, I named the iterative method 'tortoise' and the numpy method 'hare', and tested it with the code below. At first, the 'tortoise' won [.009s [T] vs .033s [H]], but I checked it and found that asarray() was being called more often than it need to be. With that fix, the 'hare' won again, [.009s [T] vs .006s [H]]. The data is here: <http://tny.cz/64d6e5dc> It consists of 28 lines of about 950 elements in length. Four of the lines collectively >= all the others. It might be interesting to see how the performance works on larger data sets. ``` import itertools, operator, math import cProfile import numpy as np data = #SEE PASTEBIN def tortoise(xs, ys): all_less = True all_greater = True for x, y in zip(xs, ys): if not all_less and not all_greater: return None if x > y: all_less = False elif x < y: all_greater = False if all_greater and all_less: return 0 if all_greater: return 1 if all_less: return -1 return None # all_greater might be set False on final iteration hare = lambda b,a : np.all(b >= a) def find_uniques_tortoise(): include_list = range(len(data)) current_list_index = 0 while current_list_index < len(data): if current_list_index not in include_list: current_list_index += 1 continue for x in range(current_list_index+1,len(data)): if x not in include_list: continue result = tortoise(data[current_list_index], data[x]) if result is None: #no comparison continue elif result == 1 or result == 0: # this one beats the other one include_list.remove(x) continue elif result == -1: #the other one beats this one include_list.remove(current_list_index) break current_list_index +=1 return include_list def find_uniques_hare(): include_list = range(len(data)) current_list_index = 0 #do all asarray()s beforehand for max efficiency for x in range(len(data)): data[x] = np.asarray(data[x]) while current_list_index < len(data): if current_list_index not in include_list: current_list_index += 1 continue for x in range(current_list_index+1,len(data)): if x not in include_list: continue if hare(data[current_list_index], data[x]): # this one beats the other one, or it's a tie include_list.remove(x) # print x continue elif hare(data[x], data[current_list_index]): #the other one beats this one include_list.remove(current_list_index) # print current_list_index break else: #no comparison continue current_list_index +=1 return include_list cProfile.run('find_uniques_tortoise()') cProfile.run('find_uniques_hare()') print find_uniques_tortoise() print print find_uniques_hare() ```
19,282,833
I'm trying to compare two lists of integers, each the same size, in Python 2.6. The comparison I need is to compare the first item in List 1 with the first item in List 2, the second item in List 1 with the second item in List 2, and so on, and returns a result if ALL of the list items follow the same comparison criteria. It should behave as follows: ``` list1 = [1,1,1,1] list2 = [2,1,2,3] compare(list1,list2) # returns a "list 1 is <= list 2" response. list1 = [4,1,4,3] list2 = [2,1,2,3] compare(list1,list2) # returns a "list 1 is >= list 2" response. list1 = [3,2,3,2] list2 = [1,4,1,4] compare(list1,list2) # returns None— some items in list1 > list2, and some items in list2 > list1. ``` I figured I could write the code like the following block, but I don't know if it's the most efficient. My program is going to be calling this method a LOT so I want to streamline this as much as possible. ``` def compare(list1,list2): gt_found = 0 lt_found = 0 for x in range(len(list1)): if list1[x] > list2[x]: gt_found += 1 elif list1[x] < list2[x]: lt_found += 1 if gt_found > 0 and lt_found > 0: return None #(some items >, some items <) if gt_found > 0: return 1 #(list1 >= list2) if lt_found > 0: return -1 #(list1 <= list2) return 0 #(list1 == list2) ``` Is it already as good as it's going to get (big-O of n), or is there a faster way to go about it (or a way that uses system functions instead)? CLARIFICATION: I expect the case that returns 'None' to happen the most often, so it is important.
2013/10/09
[ "https://Stackoverflow.com/questions/19282833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1541913/" ]
You can consider a numpy-based vectorized comparison. ``` import numpy as np a = [1,1,1,2] b = [2,2,4,3] all_larger = np.all(np.asarray(b) > np.asarray(a)) # true if b > a holds elementwise print all_larger True ``` Clearly, you can engineer the thing to have your answer. ``` all_larger = lambda b,a : np.all(np.asarray(b) > np.asarray(a)) if all_larger(b,a): print "b > a" elif all_larger(a,b): print "a > b" else print "nothing!" ``` Every type of comparison such as `<, >, <=, >=,` can be done.
For anyone interested in the performance of the two methods, I named the iterative method 'tortoise' and the numpy method 'hare', and tested it with the code below. At first, the 'tortoise' won [.009s [T] vs .033s [H]], but I checked it and found that asarray() was being called more often than it need to be. With that fix, the 'hare' won again, [.009s [T] vs .006s [H]]. The data is here: <http://tny.cz/64d6e5dc> It consists of 28 lines of about 950 elements in length. Four of the lines collectively >= all the others. It might be interesting to see how the performance works on larger data sets. ``` import itertools, operator, math import cProfile import numpy as np data = #SEE PASTEBIN def tortoise(xs, ys): all_less = True all_greater = True for x, y in zip(xs, ys): if not all_less and not all_greater: return None if x > y: all_less = False elif x < y: all_greater = False if all_greater and all_less: return 0 if all_greater: return 1 if all_less: return -1 return None # all_greater might be set False on final iteration hare = lambda b,a : np.all(b >= a) def find_uniques_tortoise(): include_list = range(len(data)) current_list_index = 0 while current_list_index < len(data): if current_list_index not in include_list: current_list_index += 1 continue for x in range(current_list_index+1,len(data)): if x not in include_list: continue result = tortoise(data[current_list_index], data[x]) if result is None: #no comparison continue elif result == 1 or result == 0: # this one beats the other one include_list.remove(x) continue elif result == -1: #the other one beats this one include_list.remove(current_list_index) break current_list_index +=1 return include_list def find_uniques_hare(): include_list = range(len(data)) current_list_index = 0 #do all asarray()s beforehand for max efficiency for x in range(len(data)): data[x] = np.asarray(data[x]) while current_list_index < len(data): if current_list_index not in include_list: current_list_index += 1 continue for x in range(current_list_index+1,len(data)): if x not in include_list: continue if hare(data[current_list_index], data[x]): # this one beats the other one, or it's a tie include_list.remove(x) # print x continue elif hare(data[x], data[current_list_index]): #the other one beats this one include_list.remove(current_list_index) # print current_list_index break else: #no comparison continue current_list_index +=1 return include_list cProfile.run('find_uniques_tortoise()') cProfile.run('find_uniques_hare()') print find_uniques_tortoise() print print find_uniques_hare() ```
6,978,304
I am trying to delete a few records but am getting the following error: > > Cannot delete or update a parent row: a foreign key constraint fails > > > The thing is, the foreign key constraint is failing for only 1 or 2 of my 100 records I wish to delete. I wish to write a query which deletes these 98-99 records, ***skipping the 1 or 2 which failed***, which I can later manually inspect and delete/modify. Not stopping because of some single problematic record, but continuing with the others, ignoring that. Is there a neat way to do this ?
2011/08/08
[ "https://Stackoverflow.com/questions/6978304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363502/" ]
You have to `LEFT JOIN` the referencing table and add a condition saying that the row is missing in that table. For example: ``` DELETE a FROM a LEFT JOIN b ON b.a_id = a.id WHERE b.a_id IS NULL; ```
Use ignore: ``` DELETE IGNORE ... ``` <http://dev.mysql.com/doc/refman/5.0/en/delete.html>
71,379,340
How can I implement a photo-like layout using flexbox? [enter image description here](https://i.stack.imgur.com/BTHB8.jpg) ``` <div class="row"> <div class="col-md-6"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> <div class="col-md-6"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> </div> ```
2022/03/07
[ "https://Stackoverflow.com/questions/71379340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16727131/" ]
This is easier done via `grid`. Here's the implementation: ```css .row { display: grid; grid-template-areas: "a b c" "d d c" "e f c"; grid-gap: 5px; } div { border: 1px solid black; padding: 5px; } .a { grid-area: a; } .b { grid-area: b; } .c { grid-area: c; } .d { grid-area: d; } .e { grid-area: e; } .f { grid-area: f; } ``` ```html <div class="row"> <div class="col-md-6 a">a</div> <div class="col-md-3 b">b</div> <div class="col-md-3 c">c</div> <div class="col-md-6 d">d</div> <div class="col-md-3 e">e</div> <div class="col-md-3 f">f</div> </div> ```
```css * { box-sizing: border-box; } .row { display: grid; grid-template-columns: repeat(4, 100px); grid-template-rows: repeat(3, 200px); grid-gap: 10px; width: max-content; margin: auto; } .col { background-color: red; display: flex; justify-content: center; align-items: center; } .col:nth-child(3) { background-color: blue; grid-column: 3 / 5; grid-row: 1 / 4; } .col:nth-child(4) { grid-column: 1 / 3; } ``` ```html <div class="row"> <div class="col col-md-3">col3</div> <div class="col col-md-3">col3</div> <div class="col col-md-6">col6</div> <div class="col col-md-6">col6</div> <div class="col col-md-3">col3</div> <div class="col col-md-3">col3</div> </div> ```
71,379,340
How can I implement a photo-like layout using flexbox? [enter image description here](https://i.stack.imgur.com/BTHB8.jpg) ``` <div class="row"> <div class="col-md-6"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> <div class="col-md-6"></div> <div class="col-md-3"></div> <div class="col-md-3"></div> </div> ```
2022/03/07
[ "https://Stackoverflow.com/questions/71379340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16727131/" ]
HTML CODES: ``` <div class="main-div"> <div class="leftside"> <div class="leftside-1"> <div class="leftside-1a">1a</div> <div class="leftside-2a">2a</div> </div> <div class="leftside-2">2</div> <div class="leftside-3"> <div class="leftside-1c">1c</div> <div class="leftside-2c">2c</div> </div> </div> <div class="rightside"> </div> </div> ``` CSS CODES: ``` * { margin: 0; padding: 0; -webkit-box-sizing: border-box; box-sizing: border-box; } html { font-size: 10px; } .main-div { width: 100vw; min-height: 100vh; display: -webkit-box; display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; } .main-div .leftside { -webkit-box-flex: 1; -ms-flex: 1 1 40rem; flex: 1 1 40rem; -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; flex-direction: column; background-color: darkkhaki; } .main-div .leftside .leftside-1 { width: 100%; min-height: 25%; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -ms-flex-wrap: wrap; flex-wrap: wrap; } .main-div .leftside .leftside-1 .leftside-1a { -webkit-box-flex: 1; -ms-flex: 1 1 20rem; flex: 1 1 20rem; background-color: red; } .main-div .leftside .leftside-1 .leftside-2a { -webkit-box-flex: 1; -ms-flex: 1 1 20rem; flex: 1 1 20rem; background-color: cyan; } .main-div .leftside .leftside-2 { -webkit-box-flex: 1; -ms-flex: 1 1 40rem; flex: 1 1 40rem; min-height: 50%; background-color: green; } .main-div .leftside .leftside-3 { width: 100%; min-height: 25%; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -ms-flex-direction: row; flex-direction: row; -ms-flex-wrap: wrap; flex-wrap: wrap; } .main-div .leftside .leftside-3 .leftside-1c { -webkit-box-flex: 1; -ms-flex: 1 1 20rem; flex: 1 1 20rem; background-color: red; } .main-div .leftside .leftside-3 .leftside-2c { -webkit-box-flex: 1; -ms-flex: 1 1 20rem; flex: 1 1 20rem; background-color: cyan; } .main-div .rightside { -webkit-box-flex: 1; -ms-flex: 1 1 40rem; flex: 1 1 40rem; background-color: darkgrey; } ```
```css * { box-sizing: border-box; } .row { display: grid; grid-template-columns: repeat(4, 100px); grid-template-rows: repeat(3, 200px); grid-gap: 10px; width: max-content; margin: auto; } .col { background-color: red; display: flex; justify-content: center; align-items: center; } .col:nth-child(3) { background-color: blue; grid-column: 3 / 5; grid-row: 1 / 4; } .col:nth-child(4) { grid-column: 1 / 3; } ``` ```html <div class="row"> <div class="col col-md-3">col3</div> <div class="col col-md-3">col3</div> <div class="col col-md-6">col6</div> <div class="col col-md-6">col6</div> <div class="col col-md-3">col3</div> <div class="col col-md-3">col3</div> </div> ```
38,565,590
I have data in the following form: ``` TicketID Status Datetime 25 Open 2016-07-21 11:46:40 25 Open 2016-07-22 09:42:40 25 Closed 2016-07-22 09:46:40 25 Open 2016-07-23 08:42:40 25 Open 2016-07-24 08:46:40 25 Open 2016-07-24 09:26:40 25 Closed 2016-07-25 11:46:40 ``` I want to calculate the following: ((2016-07-22 09:46:40 - 2016-07-21 11:46:40) + (2016-07-25 11:46:40 - 2016-07-23 08:42:40))/2.
2016/07/25
[ "https://Stackoverflow.com/questions/38565590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1621640/" ]
Here is an idea: For each "open" get the next "closed". Then only choose the "closed" values and take the minimum open to determine the length of time. So, the following gets the pairs of times that you want: ``` select close_datetime, min(datetime) as open_datetime from (select t.*, (select t2.DateTime from t t2 where t2.status = 'Closed' and t2.DateTime > t.DateTime ) as close_datetime from t where status = 'Open' ) t group by close_datetime; ``` You can then get the sum of the differences. This gets the value in seconds: ``` select sum(timestampdiff(second, clsoe_datetime, open_datetime) as num_seconds from (select close_datetime, min(datetime) as open_datetime from (select t.*, (select t2.DateTime from t t2 where t2.status = 'Closed' and t2.DateTime > t.DateTime ) as close_datetime from t where status = 'Open' ) t group by close_datetime ) t ```
This seems okay to me. ``` set @x=now(), @y=-1; select avg(timestampdiff(second,prev_stat_dt,curr_stat_dt)) from (select TicketID, @y prev_stat, @y:=Status curr_stat, @x prev_stat_dt, @x:=DateTime curr_stat_dt from table1 where Status in ('Open' , 'Closed')) t where prev_stat = 'Open' and curr_stat = 'Closed'; ```
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
[Per documentation](http://www.postgresql.org/docs/9.4/static/functions-json.html), there are also the functions ``` jsonb_populate_record() jsonb_populate_recordset() ``` Analog to their json twins (present since pg 9.3) ``` json_populate_record() json_populate_recordset() ``` You need a predefined row type. Either use the row-type of an existing table or define one with `CREATE TYPE`. Or substitute with a temporary table ad hoc: ``` CREATE TEMP TABLE x(lat **float**); ``` Can be a single column or a long list of columns. Only those columns are filled, where the **name** matches a **key** in the `json` object. The **value** is coerced to the column **type** and has to be compatible or an exception is raised. Other keys are ignored. ``` SELECT lat + 1 -- no need for 1.0, this is float already FROM updates u , jsonb_populate_record(NULL::x, u.json_data->'position') LIMIT 5; ``` Using an [implicit `LATERAL JOIN`](https://stackoverflow.com/questions/22409986/dynamically-execute-query-using-the-output-of-another-query/22410799#22410799) here. Similarly, use `jsonb_populate_recordset()` to decompose arrays into multiple rows per entry. This works the same way in Postgres 9.3 with `json`. There is the added benefit that casting to / from `text` internally is not necessary for numeric data in `jsonb`.
You must to cast the json value to text and then to float. Try this: ``` (json_data #>> '{field}')::float ```
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
There are two operations to get value from `JSON`. The first one `->` will return `JSON`. The second one `->>` will return text. Details: [JSON Functions and Operators](http://www.postgresql.org/docs/current/static/functions-json.html) Try ``` SELECT (json_data->'position'->>'lat')::float + 1.0 AS lat FROM updates LIMIT 5 ```
[Per documentation](http://www.postgresql.org/docs/9.4/static/functions-json.html), there are also the functions ``` jsonb_populate_record() jsonb_populate_recordset() ``` Analog to their json twins (present since pg 9.3) ``` json_populate_record() json_populate_recordset() ``` You need a predefined row type. Either use the row-type of an existing table or define one with `CREATE TYPE`. Or substitute with a temporary table ad hoc: ``` CREATE TEMP TABLE x(lat **float**); ``` Can be a single column or a long list of columns. Only those columns are filled, where the **name** matches a **key** in the `json` object. The **value** is coerced to the column **type** and has to be compatible or an exception is raised. Other keys are ignored. ``` SELECT lat + 1 -- no need for 1.0, this is float already FROM updates u , jsonb_populate_record(NULL::x, u.json_data->'position') LIMIT 5; ``` Using an [implicit `LATERAL JOIN`](https://stackoverflow.com/questions/22409986/dynamically-execute-query-using-the-output-of-another-query/22410799#22410799) here. Similarly, use `jsonb_populate_recordset()` to decompose arrays into multiple rows per entry. This works the same way in Postgres 9.3 with `json`. There is the added benefit that casting to / from `text` internally is not necessary for numeric data in `jsonb`.
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
There are two operations to get value from `JSON`. The first one `->` will return `JSON`. The second one `->>` will return text. Details: [JSON Functions and Operators](http://www.postgresql.org/docs/current/static/functions-json.html) Try ``` SELECT (json_data->'position'->>'lat')::float + 1.0 AS lat FROM updates LIMIT 5 ```
AFAIK there's no json->float casting in Postgres, so you could try an explicit `(json_data->'position'->'lat')::text::float` cast
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
There are two operations to get value from `JSON`. The first one `->` will return `JSON`. The second one `->>` will return text. Details: [JSON Functions and Operators](http://www.postgresql.org/docs/current/static/functions-json.html) Try ``` SELECT (json_data->'position'->>'lat')::float + 1.0 AS lat FROM updates LIMIT 5 ```
Now we can do it! ----------------- In nowadays we can cast directly from JSONb to SQL datatypes. I am using PostgreSQL **v12.3**, where it is working fine: ```sql SELECT (j->'i')::int, (j->>'i')::int, (j->'f')::float, (j->>'f')::float FROM (SELECT '{"i":123,"f":12.34}'::jsonb) t(j); ``` --- Sub-questions: * *From which version is it possible?* * *It is a syntax sugar or a [real conversion](https://stackoverflow.com/a/62558306/287948)?* * *If real "binary JSONb → binary SQL" conversion, where the micro-optimizations?* For example, what wold be faster (?) tham "binary JSONb → string → binary SQL"? boolean→boolean, number→numeric, number→int, number→bigint; number→flloat, number→double. * *Why not optimized for NULL?* Curiosily the "NULL to SqlType" not works, "ERROR: cannot cast jsonb null to type integer". --- Benchmark suggestion -------------------- How to check? When PostgreSQL optimize loop queries? ```sql EXPLAIN ANALYSE SELECT (j->'i')::int, (j->'f')::float -- bynary to bynary INT and FLOAT -- EXPLAIN ANALYSE SELECT (j->>'i')::int, (j->>'f')::float -- string to bynary INT and FLOAT -- EXPLAIN ANALYSE SELECT (j->'i')::numeric, (j->'f')::numeric -- bynary to bynary NUMERIC -- EXPLAIN ANALYSE SELECT (j->>'i')::numeric, (j->>'f')::numeric -- string to bynary NUMERIC FROM ( SELECT (('{"i":'||x||',"f":'||x||'.34}')::jsonb) as j FROM generate_series(1,599999) g(x) -- SELECT (('{"i":123,"f":12.34}')::jsonb) as j FROM generate_series(1,599999) g(x) ) t; ``` --- PostgreSQL bug? --------------- Even now, 2021 with version pg13 version... Not make sense to not cast NULLs: the natural is to cast `NULL::int` to integer, but PostgreSQL fail in the automatic cast: ```sql SELECT (j->'i')::int FROM (SELECT '{"i":null}'::jsonb) t(j); -- fail ``` results in *"ERROR: cannot cast jsonb null to type integer"*.
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
AFAIK there's no json->float casting in Postgres, so you could try an explicit `(json_data->'position'->'lat')::text::float` cast
Now we can do it! ----------------- In nowadays we can cast directly from JSONb to SQL datatypes. I am using PostgreSQL **v12.3**, where it is working fine: ```sql SELECT (j->'i')::int, (j->>'i')::int, (j->'f')::float, (j->>'f')::float FROM (SELECT '{"i":123,"f":12.34}'::jsonb) t(j); ``` --- Sub-questions: * *From which version is it possible?* * *It is a syntax sugar or a [real conversion](https://stackoverflow.com/a/62558306/287948)?* * *If real "binary JSONb → binary SQL" conversion, where the micro-optimizations?* For example, what wold be faster (?) tham "binary JSONb → string → binary SQL"? boolean→boolean, number→numeric, number→int, number→bigint; number→flloat, number→double. * *Why not optimized for NULL?* Curiosily the "NULL to SqlType" not works, "ERROR: cannot cast jsonb null to type integer". --- Benchmark suggestion -------------------- How to check? When PostgreSQL optimize loop queries? ```sql EXPLAIN ANALYSE SELECT (j->'i')::int, (j->'f')::float -- bynary to bynary INT and FLOAT -- EXPLAIN ANALYSE SELECT (j->>'i')::int, (j->>'f')::float -- string to bynary INT and FLOAT -- EXPLAIN ANALYSE SELECT (j->'i')::numeric, (j->'f')::numeric -- bynary to bynary NUMERIC -- EXPLAIN ANALYSE SELECT (j->>'i')::numeric, (j->>'f')::numeric -- string to bynary NUMERIC FROM ( SELECT (('{"i":'||x||',"f":'||x||'.34}')::jsonb) as j FROM generate_series(1,599999) g(x) -- SELECT (('{"i":123,"f":12.34}')::jsonb) as j FROM generate_series(1,599999) g(x) ) t; ``` --- PostgreSQL bug? --------------- Even now, 2021 with version pg13 version... Not make sense to not cast NULLs: the natural is to cast `NULL::int` to integer, but PostgreSQL fail in the automatic cast: ```sql SELECT (j->'i')::int FROM (SELECT '{"i":null}'::jsonb) t(j); -- fail ``` results in *"ERROR: cannot cast jsonb null to type integer"*.
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
There are two operations to get value from `JSON`. The first one `->` will return `JSON`. The second one `->>` will return text. Details: [JSON Functions and Operators](http://www.postgresql.org/docs/current/static/functions-json.html) Try ``` SELECT (json_data->'position'->>'lat')::float + 1.0 AS lat FROM updates LIMIT 5 ```
When creating a view I used CAST: ``` create view mydb.myview as select id, config->>'version' as version, config->>'state' as state, config->>'name' as name, config->>'internal-name' as internal_name, config->>'namespace' as namespace, create_date, update_date, CAST(config ->> 'version' as double precision) as version_number from mydb.mytbl; ```
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
You must to cast the json value to text and then to float. Try this: ``` (json_data #>> '{field}')::float ```
When creating a view I used CAST: ``` create view mydb.myview as select id, config->>'version' as version, config->>'state' as state, config->>'name' as name, config->>'internal-name' as internal_name, config->>'namespace' as namespace, create_date, update_date, CAST(config ->> 'version' as double precision) as version_number from mydb.mytbl; ```
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
Adding a clarification because this comes up as the top hit for a 'JSONB float conversion' search - note that you need to wrap the JSON conversion in brackets, and *then* apply the '::' casting. As mentioned above, the correct method is: ``` (json_data #>> '{field}')::float ``` If instead you try this it will fail: ``` json_data #>> '{field}'::float ``` This was the mistake I was making in my code and it took me a while to see it - easy fix once I noticed.
You must to cast the json value to text and then to float. Try this: ``` (json_data #>> '{field}')::float ```
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
Adding a clarification because this comes up as the top hit for a 'JSONB float conversion' search - note that you need to wrap the JSON conversion in brackets, and *then* apply the '::' casting. As mentioned above, the correct method is: ``` (json_data #>> '{field}')::float ``` If instead you try this it will fail: ``` json_data #>> '{field}'::float ``` This was the mistake I was making in my code and it took me a while to see it - easy fix once I noticed.
When creating a view I used CAST: ``` create view mydb.myview as select id, config->>'version' as version, config->>'state' as state, config->>'name' as name, config->>'internal-name' as internal_name, config->>'namespace' as namespace, create_date, update_date, CAST(config ->> 'version' as double precision) as version_number from mydb.mytbl; ```
24,826,385
I'm trying the following query: ``` SELECT (json_data->'position'->'lat') + 1.0 AS lat FROM updates LIMIT 5; ``` (The +1.0 is just there to force conversion to float. My actual queries are far more complex, this query is just a test case for the problem.) I get the error: ``` ERROR: operator does not exist: jsonb + numeric ``` If I add in explicit casting: ``` SELECT (json_data->'position'->'lat')::float + 1.0 AS lat FROM updates LIMIT 5; ``` the error becomes: ``` ERROR: operator does not exist: jsonb + double precesion ``` I understand that most jsonb values cannot be cast into floats, but in this case I know that the lats are all JSON numbers. Is there a function which casts jsonb values to floats (or return NULLs for the uncastable)?
2014/07/18
[ "https://Stackoverflow.com/questions/24826385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129805/" ]
AFAIK there's no json->float casting in Postgres, so you could try an explicit `(json_data->'position'->'lat')::text::float` cast
When creating a view I used CAST: ``` create view mydb.myview as select id, config->>'version' as version, config->>'state' as state, config->>'name' as name, config->>'internal-name' as internal_name, config->>'namespace' as namespace, create_date, update_date, CAST(config ->> 'version' as double precision) as version_number from mydb.mytbl; ```
2,144,175
If I have $\begin{bmatrix}a&0\\0&a^{-1}\end{bmatrix}$ in $SL(2,\Bbb C)$, how do I find what element I would have corresponding to this in $\mathfrak{sl}(2,\Bbb C)$? I imagine it might be something like $\begin{bmatrix}a&0\\0&-a\end{bmatrix}$, but I am not sure how to find this. I know I want to go from determinant $1$ matrices to traceless matrices. But I can't get the correspondence down yet.
2017/02/14
[ "https://math.stackexchange.com/questions/2144175", "https://math.stackexchange.com", "https://math.stackexchange.com/users/229882/" ]
The exponential map $\exp: \mathfrak{g}\rightarrow G$ gives you the matrices, however it need not be surjective (or injective) in general. Indeed, for $\mathfrak{g}=\mathfrak{sl}\_2(\mathbb{C})$ and $G=SL\_2(\mathbb{C})$ it is not - see [here](https://math.stackexchange.com/questions/643216/non-surjectivity-of-the-exponential-map-to-sl2-mathbbc), or [here](https://math.stackexchange.com/questions/301504/on-surjectivity-of-exponential-map-for-lie-groups). However, the diagonal matrices have preimages in the Lie algebra, as was shown already. So you can find such matrices of trace zero.
In general, there is no one-to-one correspondence between a group $G$ and its Lie algebra $\mathfrak{g}$, but we do have a map $$\exp:\mathfrak{g}\to G.$$ In case of matrix groups, we have that for diagonal matrices $$\exp\begin{pmatrix}s & 0 \\ 0 & t\end{pmatrix}=\begin{pmatrix}e^s & 0 \\ 0 & e^t\end{pmatrix}.$$ Thus, $$\begin{pmatrix}\log a & 0 \\ 0 & -\log a\end{pmatrix}\in\mathfrak{sl}(2,\mathbb{C})$$ is an element you are looking for (for any branch of $\log$ not passing through $a$). But note that it is not unique, as we may add multiples of $2\pi i$.
2,144,175
If I have $\begin{bmatrix}a&0\\0&a^{-1}\end{bmatrix}$ in $SL(2,\Bbb C)$, how do I find what element I would have corresponding to this in $\mathfrak{sl}(2,\Bbb C)$? I imagine it might be something like $\begin{bmatrix}a&0\\0&-a\end{bmatrix}$, but I am not sure how to find this. I know I want to go from determinant $1$ matrices to traceless matrices. But I can't get the correspondence down yet.
2017/02/14
[ "https://math.stackexchange.com/questions/2144175", "https://math.stackexchange.com", "https://math.stackexchange.com/users/229882/" ]
In general, there is no one-to-one correspondence between a group $G$ and its Lie algebra $\mathfrak{g}$, but we do have a map $$\exp:\mathfrak{g}\to G.$$ In case of matrix groups, we have that for diagonal matrices $$\exp\begin{pmatrix}s & 0 \\ 0 & t\end{pmatrix}=\begin{pmatrix}e^s & 0 \\ 0 & e^t\end{pmatrix}.$$ Thus, $$\begin{pmatrix}\log a & 0 \\ 0 & -\log a\end{pmatrix}\in\mathfrak{sl}(2,\mathbb{C})$$ is an element you are looking for (for any branch of $\log$ not passing through $a$). But note that it is not unique, as we may add multiples of $2\pi i$.
The correspondence between elements is given by the exponential map. This is actually a pretty deep statement in Lie theory, but for this particular case suffice it to say that the identity $$e^{\text{tr}(A)} = \det(e^A)$$ holds (not hard to show with Jordan normal form), and this shows that $$\text{tr}(A) = 0 \iff \det(e^A) = 1$$ For diagonal matrices, the exponential map (and it's inverse) are easy to calculate: you'll just apply a complex logarithm to the diagonal entries of your element of $SL(2,\mathbb{C})$.
2,144,175
If I have $\begin{bmatrix}a&0\\0&a^{-1}\end{bmatrix}$ in $SL(2,\Bbb C)$, how do I find what element I would have corresponding to this in $\mathfrak{sl}(2,\Bbb C)$? I imagine it might be something like $\begin{bmatrix}a&0\\0&-a\end{bmatrix}$, but I am not sure how to find this. I know I want to go from determinant $1$ matrices to traceless matrices. But I can't get the correspondence down yet.
2017/02/14
[ "https://math.stackexchange.com/questions/2144175", "https://math.stackexchange.com", "https://math.stackexchange.com/users/229882/" ]
The exponential map $\exp: \mathfrak{g}\rightarrow G$ gives you the matrices, however it need not be surjective (or injective) in general. Indeed, for $\mathfrak{g}=\mathfrak{sl}\_2(\mathbb{C})$ and $G=SL\_2(\mathbb{C})$ it is not - see [here](https://math.stackexchange.com/questions/643216/non-surjectivity-of-the-exponential-map-to-sl2-mathbbc), or [here](https://math.stackexchange.com/questions/301504/on-surjectivity-of-exponential-map-for-lie-groups). However, the diagonal matrices have preimages in the Lie algebra, as was shown already. So you can find such matrices of trace zero.
The correspondence between elements is given by the exponential map. This is actually a pretty deep statement in Lie theory, but for this particular case suffice it to say that the identity $$e^{\text{tr}(A)} = \det(e^A)$$ holds (not hard to show with Jordan normal form), and this shows that $$\text{tr}(A) = 0 \iff \det(e^A) = 1$$ For diagonal matrices, the exponential map (and it's inverse) are easy to calculate: you'll just apply a complex logarithm to the diagonal entries of your element of $SL(2,\mathbb{C})$.
101,557
I would like to control several high power DC devices (12V DC LEDs). From a tutorial, I found that I can control these using a 3.3V PWM input and a MOSFET. From what I understand, the MOSFET only allows current to flow through the LED to ground when the PWM input is high. I have several (lets say 4) of these LEDs and want to be able to select which one I am controlling. If I could activate the LEDs directly using the 3.3V PWM, then I would probably try to do something like this: 1. Get a 2 to 4 bit decoder. 2. Connect 2 output pins from the controlling device to the 2 select pins of the decoder. 3. Get 4 AND gates. 4. Using the AND gates, AND together each of the 4 outputs of the decoder with the single PWM output from the controlling device. 5. Connect the outputs of the AND gates to the LEDs. I think this would work (please correct me if I'm wrong). If I got one MOSFET per LED, then this approach could still work with the higher power devices that I can't directly control. My two questions are: 1. Does this approach make sense? 2. Is there a way to accomplish this using only a single MOSFET?
2014/03/02
[ "https://electronics.stackexchange.com/questions/101557", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/34208/" ]
You can skip step 3 if you get a decoder with an enable input, e.g. 74HC238. Connect the PWM output to the enable input and this will switch the decoded output on and off with the PWM signal. You will still need one sink per device you want to switch though.
> > Does this approach make sense? > > > Yes, it might work. However, the real question is if this is what you really want. Being able to choose a single LED to power at a time is less useful than being able to power all LEDs simultaneously. And the fact is that this latter version is simpler and requires less components, while providing more flexibility. So I see no point in doing the original version. > > Is there a way to accomplish this using only a single MOSFET? > > > Only if the LEDs are of so little power that an IC is enough to power them (15-20mA/output). Power LEDs usually require larger currents, for which you need some external power switching device (a MOSFET or a transistor).
101,557
I would like to control several high power DC devices (12V DC LEDs). From a tutorial, I found that I can control these using a 3.3V PWM input and a MOSFET. From what I understand, the MOSFET only allows current to flow through the LED to ground when the PWM input is high. I have several (lets say 4) of these LEDs and want to be able to select which one I am controlling. If I could activate the LEDs directly using the 3.3V PWM, then I would probably try to do something like this: 1. Get a 2 to 4 bit decoder. 2. Connect 2 output pins from the controlling device to the 2 select pins of the decoder. 3. Get 4 AND gates. 4. Using the AND gates, AND together each of the 4 outputs of the decoder with the single PWM output from the controlling device. 5. Connect the outputs of the AND gates to the LEDs. I think this would work (please correct me if I'm wrong). If I got one MOSFET per LED, then this approach could still work with the higher power devices that I can't directly control. My two questions are: 1. Does this approach make sense? 2. Is there a way to accomplish this using only a single MOSFET?
2014/03/02
[ "https://electronics.stackexchange.com/questions/101557", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/34208/" ]
You can skip step 3 if you get a decoder with an enable input, e.g. 74HC238. Connect the PWM output to the enable input and this will switch the decoded output on and off with the PWM signal. You will still need one sink per device you want to switch though.
Why don't you look for an analogue multiplexer that can run from a 12V power supply and has low on-resistance and can take the current for one LED. You haven't stated the LED current so this approach may not yield a definite result. This one might work for you: - ![enter image description here](https://i.stack.imgur.com/rq3y9.jpg) If you use the correct package 200mA is the max current but you might be able to current share with two devices. It all totally depends on the LED spec. There are possibly higher power multiplxers as well.
101,557
I would like to control several high power DC devices (12V DC LEDs). From a tutorial, I found that I can control these using a 3.3V PWM input and a MOSFET. From what I understand, the MOSFET only allows current to flow through the LED to ground when the PWM input is high. I have several (lets say 4) of these LEDs and want to be able to select which one I am controlling. If I could activate the LEDs directly using the 3.3V PWM, then I would probably try to do something like this: 1. Get a 2 to 4 bit decoder. 2. Connect 2 output pins from the controlling device to the 2 select pins of the decoder. 3. Get 4 AND gates. 4. Using the AND gates, AND together each of the 4 outputs of the decoder with the single PWM output from the controlling device. 5. Connect the outputs of the AND gates to the LEDs. I think this would work (please correct me if I'm wrong). If I got one MOSFET per LED, then this approach could still work with the higher power devices that I can't directly control. My two questions are: 1. Does this approach make sense? 2. Is there a way to accomplish this using only a single MOSFET?
2014/03/02
[ "https://electronics.stackexchange.com/questions/101557", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/34208/" ]
Why don't you look for an analogue multiplexer that can run from a 12V power supply and has low on-resistance and can take the current for one LED. You haven't stated the LED current so this approach may not yield a definite result. This one might work for you: - ![enter image description here](https://i.stack.imgur.com/rq3y9.jpg) If you use the correct package 200mA is the max current but you might be able to current share with two devices. It all totally depends on the LED spec. There are possibly higher power multiplxers as well.
> > Does this approach make sense? > > > Yes, it might work. However, the real question is if this is what you really want. Being able to choose a single LED to power at a time is less useful than being able to power all LEDs simultaneously. And the fact is that this latter version is simpler and requires less components, while providing more flexibility. So I see no point in doing the original version. > > Is there a way to accomplish this using only a single MOSFET? > > > Only if the LEDs are of so little power that an IC is enough to power them (15-20mA/output). Power LEDs usually require larger currents, for which you need some external power switching device (a MOSFET or a transistor).
28,378,516
I have a grid of 25 NSButtons. I'm attempting to set a tag on each of them, from 1-25, and link them to one IBAction, containing this: ``` - (IBAction)buttonClicked:(id)sender { NSLog(@"Clicked button %lo.", [sender tag]); } ``` However, I'm running into a problem. It works fine from buttons 1-7, but the 8th one returns 10, the 9th returns 11, and the 10th returns 12. I experimentally set a button's tag to 88, and it returned 130. Is this a bug, or am I going about this the wrong way?
2015/02/07
[ "https://Stackoverflow.com/questions/28378516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1107398/" ]
Your button values are correct, you're just printing them wrong, in octal format (the 'o' in %lo) instead of decimal. That's why your 8 prints out as a 10 -- that's 8 in octal representation. 130 is octal for 88 decimal:
You should use an `unsigned int` (**%u**) format, not `long` (**%lo**): ``` NSLog(@"Clicked button %u.", [sender tag]); ``` * depending on the format of your tag you could possibly just use `%o`. Treating the integer as long is what is adding to the number.
66,738,678
### When I load the following code using php... `<?php <h1>Some text</h1> ?>` ### the tags are printed as text - `<h1>Some text</h1>` ### Any ideas? Found the answer - see my answer. =================================
2021/03/21
[ "https://Stackoverflow.com/questions/66738678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14920090/" ]
You need to output the actual HTML code if you are placing any HTML code within PHP. You can achieve this using [`echo()`](https://www.php.net/manual/en/function.echo.php). ```php <?php echo("<h1>Some text</h1>"); ?> ```
``` <h1><?php Some text ?></h1> ``` why dont you try this.
66,738,678
### When I load the following code using php... `<?php <h1>Some text</h1> ?>` ### the tags are printed as text - `<h1>Some text</h1>` ### Any ideas? Found the answer - see my answer. =================================
2021/03/21
[ "https://Stackoverflow.com/questions/66738678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14920090/" ]
You need to output the actual HTML code if you are placing any HTML code within PHP. You can achieve this using [`echo()`](https://www.php.net/manual/en/function.echo.php). ```php <?php echo("<h1>Some text</h1>"); ?> ```
You must print it in order for it to appear the way you want it to ``` <?php echo"<h1>Some text</h1>" ?> ``` like this