qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
47,136,417
For the below code, ``` // Print indexes var randArray = [5, 6, 7, 8]; for(var val in randArray){ // val is type inferred to String type document.write(val + "<br>"); } // Print values for(var val of randArray){ // Line 95 document.write(val + "<br>"); } ``` --- Below is the error, ``` tstut.ts(95,9): error TS2403: Subsequent variable declarations must have the same type. Variable 'val' must be of type 'string', but here has type 'number'. ``` --- Below code, ``` // Print indexes var randArray = [5, 6, 7, 8]; for(var index in randArray){ document.write(index + "<br>"); } // Print values for(var val of randArray){ document.write(val + "<br>"); } ``` resolves the problem. --- In problem case, Why `val` type cannot be `number` type?
2017/11/06
[ "https://Stackoverflow.com/questions/47136417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3317808/" ]
An easy fix to your code is to change `var` to [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let): ``` // Print indexes var randArray = [5, 6, 7, 8]; for(let val in randArray){ console.log(val); } // Print values for(let val of randArray){ console.log(val); } ``` Your problem has it's root in how `var` keyword scopes the variable. (See the [manual](https://www.typescriptlang.org/docs/handbook/variable-declarations.html).) `var` declarations' scope is the enclosing functions, thus your second `for(var val...)` point in fact to the same variable and in TypeScript, they have a single, defined type. `let` instead scopes the variable in to the enclosing block or `for`, which means that the two variables can have same name, but are still separate variables.
Using "for..in" in JavaScript exposes the **key/index** of an array , simply 'coz it doesn't iterate over array items, instead it iterates over the keys/index in an array. For example, ```js var randArray = [5, 6, 7, 8]; for(let val in randArray){ document.write(val + "<br>"); } ``` In above code, no matter what items does "randArray" array contains its always going to throw the indexes. "for..of" comes to the rescue. This is one of the reasons why "for..of" exists in TypeScript (and ES6). The above code with "for..of" loop will iterate over items in an array. Also, replace "var" with "let" 'coz "let" keyword binds the variable to the local scope unlike "var" keyword in JavaScript.
14,903
MS Project seems to take a task and calculate *per day work* by dividing *total work* by *duration*. In the schedule I am working on, each resource is available for 10 hours per day, but MS Project doesn't take advantage of this. I would like to level my schedule based on the 10 available hours per day rather than simply spreading my tasks out beyond the predetermined finish date. I can do this manually by moving work around in the Resource Usage tab, but I was wondering if there is a simpler way to do this. Thanks. ![Hopefully a useful visual](https://i.stack.imgur.com/dV2tv.png) (Also, this is my first time using Project Management Exchange, so if my etiquette is not up to par please feel free to direct me to any guidelines that would improve my question.)
2015/05/11
[ "https://pm.stackexchange.com/questions/14903", "https://pm.stackexchange.com", "https://pm.stackexchange.com/users/17113/" ]
If each resource is available to work 10 hours per day then set up a resource calendar with the 10 hours working times on it. Then apply that resource calendar to each resource as required. Additionally you can modify the project settings in Change Working Time, to define a working day as 10 hours so that Project calculates the correct amount of work (in hours) when you define a duration in days. Note though that it is not enough to *just* do this, you must also have allowed the resources to have 10 hours per day, as above, to ensure that each resource is loaded to ten hours and not the default 8.
You can update the resource table to show greater than 100% utilization. In this case, you would load 125%. This will allow greater than 8 working hours per day.
11,633,959
I am trying to create a route in route table that routes to a virtual item (using a cms that creates url like example.com/about/company, where there is no physical file called company exists) using system.web.routing (unfortunately i cannot use iis rewriting/routing). I have tried the following but it results in 404. If I were to point to another physical file (tor testing purpose), the routing works fine. ``` void RegisterRoutes(RouteCollection routes) { routes.RouteExistingFiles = true; routes.MapPageRoute("about", "about/us", "~/about/company", false); } ``` So, is it possible to point to an item like that?
2012/07/24
[ "https://Stackoverflow.com/questions/11633959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330201/" ]
I got it. I put it in the cache folder and it works now. Plus, I stupidly forgot the new command (since create() didn't seem to need it). My working code: I stored the file in the cache dir, that works! ``` File output = new File(getCacheDir() + "/exampleout.mid"); ``` And then calling the file: ``` String filePath = null; File file = null; FileInputStream inputStream = null; try { filePath = getCacheDir() + "/exampleout.mid"; file = new File(filePath); inputStream = new FileInputStream(file); if(inputStream.getFD().valid()) { System.out.println("Valid!"); } } catch (Exception e1) { e1.printStackTrace(); System.exit(-1); } try { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(inputStream.getFD()); inputStream.close(); } catch (Exception e1) { e1.printStackTrace(); System.exit(-1); } try { mediaPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ```
**1.** If you have dropped your file directly on to your sd-card , then you can access it this way... ``` "/sdcard/test3.mp3" ``` **2.** But **above mentioned way is Not the proper way** to do it... **See below for the appropriate way.** ``` String baseDirectory = Environment.getExternalStorageDirectory().getAbsolutePath(); String fileName = "test3.mp3"; File f = new File(baseDirectory + File.separator + fileName); ```
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
It is because `for` loop won't wait for your `setTimeout` method to execute. Every time the `for` loop encounters the `setTimeout` method, JS will call the event loop and place it there (to be executed once it times out) and move forward. That's why it calls your `resolve` before printing the `console.log` statements from the `setTimeout` method. For an analogy, check this ``` for (let i= 0; i< 5; i++) { setTimeout(() => { console.log('I am inside'); }, 1000); console.log('I am outside') } ``` It will print `I am outside` first (5 times) and then `I am inside`.
Well, you call `resolve()` *inside* of your `for` loop. You should place it outside of the `for` loop so that it waits for the loop to finish.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
`setTimeout` doesn't wait for the function to return - it just schedules it to be executed later. The call to `setTimeout` returns immediately and your task finishes after that. To wait for the scheduled function to execute after a certain period of time, call `resolve()` at the end of the delayed function. That way the promise will only be completed once the scheduled function executes.
Well, you call `resolve()` *inside* of your `for` loop. You should place it outside of the `for` loop so that it waits for the loop to finish.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
It is possible to create this effect, but you need to put your `resolve()` in its own `setTimeout()`, adjusting the second parameter such that there is sufficient time for the other timeouts to complete. ```js const first = new Promise((resolve, reject) => { setTimeout(() => { resolve('First promise resolved!') }, 400) }) const second = new Promise((resolve, reject) => { let iter = 7 for (let i = 1; i < iter; i++) { setTimeout(() => { console.log("Iteration: ", i) }, i * 500) } setTimeout(() => { resolve('Second promise resolved!') }, iter * 500) }) first .then(res => console.log(res)) .then(() => second .then(res => console.log(res))) ``` EDIT: Just to note, the `for` loop will start printing as soon as `second` is defined. If you want to wait for this loop to start, you should add it inside `.then()` so that it triggers after the first promise has been resolved.
Well, you call `resolve()` *inside* of your `for` loop. You should place it outside of the `for` loop so that it waits for the loop to finish.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
@johnnybigH, The second function resolve's outside of timeout so technically it will not wait for timeout function to complete as you are resolving it out of setTimeout. Now 2nd one is resolved so it is going for the execution of the third function. What you can do is inside of 2nd function for the loop. look for the last iteration and resolve the end function. ``` for (let i = 0; i <= iter; i++) { (function(n) { setTimeout(function(){ console.log('hi'); console.log(n); if(i == iter) resolve(); }, 400 * i); }(i)*i); } ```
It is possible to create this effect, but you need to put your `resolve()` in its own `setTimeout()`, adjusting the second parameter such that there is sufficient time for the other timeouts to complete. ```js const first = new Promise((resolve, reject) => { setTimeout(() => { resolve('First promise resolved!') }, 400) }) const second = new Promise((resolve, reject) => { let iter = 7 for (let i = 1; i < iter; i++) { setTimeout(() => { console.log("Iteration: ", i) }, i * 500) } setTimeout(() => { resolve('Second promise resolved!') }, iter * 500) }) first .then(res => console.log(res)) .then(() => second .then(res => console.log(res))) ``` EDIT: Just to note, the `for` loop will start printing as soon as `second` is defined. If you want to wait for this loop to start, you should add it inside `.then()` so that it triggers after the first promise has been resolved.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
@johnnybigH, The second function resolve's outside of timeout so technically it will not wait for timeout function to complete as you are resolving it out of setTimeout. Now 2nd one is resolved so it is going for the execution of the third function. What you can do is inside of 2nd function for the loop. look for the last iteration and resolve the end function. ``` for (let i = 0; i <= iter; i++) { (function(n) { setTimeout(function(){ console.log('hi'); console.log(n); if(i == iter) resolve(); }, 400 * i); }(i)*i); } ```
Well, you call `resolve()` *inside* of your `for` loop. You should place it outside of the `for` loop so that it waits for the loop to finish.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
@johnnybigH, The second function resolve's outside of timeout so technically it will not wait for timeout function to complete as you are resolving it out of setTimeout. Now 2nd one is resolved so it is going for the execution of the third function. What you can do is inside of 2nd function for the loop. look for the last iteration and resolve the end function. ``` for (let i = 0; i <= iter; i++) { (function(n) { setTimeout(function(){ console.log('hi'); console.log(n); if(i == iter) resolve(); }, 400 * i); }(i)*i); } ```
This is the expected behavior. The setTimeouts will not demonstrate expected order since the functions themselves resolved in the order as defined in the promise. Just replace the setTimeouts with console.log()'s and you will see the order executed as defined.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
@johnnybigH, The second function resolve's outside of timeout so technically it will not wait for timeout function to complete as you are resolving it out of setTimeout. Now 2nd one is resolved so it is going for the execution of the third function. What you can do is inside of 2nd function for the loop. look for the last iteration and resolve the end function. ``` for (let i = 0; i <= iter; i++) { (function(n) { setTimeout(function(){ console.log('hi'); console.log(n); if(i == iter) resolve(); }, 400 * i); }(i)*i); } ```
`setTimeout` doesn't wait for the function to return - it just schedules it to be executed later. The call to `setTimeout` returns immediately and your task finishes after that. To wait for the scheduled function to execute after a certain period of time, call `resolve()` at the end of the delayed function. That way the promise will only be completed once the scheduled function executes.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
This is the expected behavior. The setTimeouts will not demonstrate expected order since the functions themselves resolved in the order as defined in the promise. Just replace the setTimeouts with console.log()'s and you will see the order executed as defined.
Well, you call `resolve()` *inside* of your `for` loop. You should place it outside of the `for` loop so that it waits for the loop to finish.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
`setTimeout` doesn't wait for the function to return - it just schedules it to be executed later. The call to `setTimeout` returns immediately and your task finishes after that. To wait for the scheduled function to execute after a certain period of time, call `resolve()` at the end of the delayed function. That way the promise will only be completed once the scheduled function executes.
This is the expected behavior. The setTimeouts will not demonstrate expected order since the functions themselves resolved in the order as defined in the promise. Just replace the setTimeouts with console.log()'s and you will see the order executed as defined.
57,964,811
I have a trouble that I can't resolve. I have two models **User** & **Orgs** They are bounded by a pivot table **user\_org** through a belongsToMany relationship. An user can be member of many Orgs and an Orgs can have many users. Into my controller I craft a query : `$users = User::query();` I wanted to get $users depending on various filters, no problem to apply filters, then order them by orgs if they have one "VIP" orgs through some weighting with `orderByRaw("CASE WHEN org_id = X THEN 1 ELSE 2 END")` [EDIT] Full query over here : ``` $users = User::query(); $queryOrder = "CASE WHEN org_id = 13 THEN 1 "; $queryOrder .= "WHEN org_id = 14 THEN 2 "; $queryOrder .= "ELSE 3 END"; $users = $users->join('user_org', 'user_org.user_id', '=', 'users.id')->orderByRaw($queryOrder); ``` Adding distinct() didn't do the job. Problem, the result of the query give me some duplicate as an user can belongs to severals orgs. I can't manage to sort the users giving me firstly the users who belongs to the VIP orgs. Did you have any clue for me ? Thanks a lot !
2019/09/16
[ "https://Stackoverflow.com/questions/57964811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2217654/" ]
It is because `for` loop won't wait for your `setTimeout` method to execute. Every time the `for` loop encounters the `setTimeout` method, JS will call the event loop and place it there (to be executed once it times out) and move forward. That's why it calls your `resolve` before printing the `console.log` statements from the `setTimeout` method. For an analogy, check this ``` for (let i= 0; i< 5; i++) { setTimeout(() => { console.log('I am inside'); }, 1000); console.log('I am outside') } ``` It will print `I am outside` first (5 times) and then `I am inside`.
This is the expected behavior. The setTimeouts will not demonstrate expected order since the functions themselves resolved in the order as defined in the promise. Just replace the setTimeouts with console.log()'s and you will see the order executed as defined.
6,795,585
I have an element with multiple elements inside. All of the elements inside have the same name. Is there any way to remove them using one function? (refer to this question for example [Remove multiple children from parent?](https://stackoverflow.com/questions/6795034/remove-multiple-children-from-parent/6795103)
2011/07/22
[ "https://Stackoverflow.com/questions/6795585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/843787/" ]
ok this should be easy. First get the parent element: ``` var theParent = document.getElementById("notSoHappyFather"); ``` then get an array of the nodes that you want to remove: ``` var theChildren = theParent.getElementsByName("unluckyChild"); ``` Lastly, remove them with a loop: ``` for (var i = 0; i < theChildren.length; i++) { theParent.removeChild(theChildren[i]); } ```
A sample of your HTML would get you a more complete answer, but one can fairly easy call DOM functions to get the list of children and just remove them. In jQuery, remove all children would be something like this: ``` $("#target > *").remove(); ``` or ``` $("#target").html(""); ``` And, you can see a demo here: <http://jsfiddle.net/jfriend00/ZBYCh/> Or, not using jQuery you could also do: ``` document.getElementById("target").innerHTML = ""; ``` If you're trying to only remove a subset of the children (and leave others intact), then you need to be more specific how one would determine which children to leave and which to remove. In jQuery, you could use a .find() select or a filter() selector to narrow the list of children to just the children you wanted to target for removal.
6,795,585
I have an element with multiple elements inside. All of the elements inside have the same name. Is there any way to remove them using one function? (refer to this question for example [Remove multiple children from parent?](https://stackoverflow.com/questions/6795034/remove-multiple-children-from-parent/6795103)
2011/07/22
[ "https://Stackoverflow.com/questions/6795585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/843787/" ]
Here's a solution that removes the first level children with the specified name for the parent with the specified id. If you want to go deeper, you can recursively call it on the child elements you get inside (you'll have to add a `parent` parameter as well). ``` function removeChildren (params){ var parentId = params.parentId; var childName = params.childName; var childNodes = document.getElementById(parentId).childNodes; for(var i=childNodes.length-1;i >= 0;i--){ var childNode = childNodes[i]; if(childNode.name == 'foo'){ childNode.parentNode.removeChild(childNode); } } } ``` And to call it: ``` removeChildren({parentId:'div1',childName:'foo'}); ``` And a [fiddle](http://jsfiddle.net/briguy37/U8xkg/) for testing: Notes: You can only access the name element dependably in JavaScript when it supported on your element (e.g. NOT on DIVs!). See [here](https://stackoverflow.com/questions/570641/javascript-cant-find-div-element-by-name) for why. **UPDATE:** [Here](http://jsfiddle.net/briguy37/U8xkg/9/)'s a solution using className based on our conversation: ``` function removeChildren (params){ var parentId = params.parentId; var childName = params.childName; var childNodesToRemove = document.getElementById(parentId).getElementsByClassName('foo'); for(var i=childNodesToRemove.length-1;i >= 0;i--){ var childNode = childNodesToRemove[i]; childNode.parentNode.removeChild(childNode); } } ```
A sample of your HTML would get you a more complete answer, but one can fairly easy call DOM functions to get the list of children and just remove them. In jQuery, remove all children would be something like this: ``` $("#target > *").remove(); ``` or ``` $("#target").html(""); ``` And, you can see a demo here: <http://jsfiddle.net/jfriend00/ZBYCh/> Or, not using jQuery you could also do: ``` document.getElementById("target").innerHTML = ""; ``` If you're trying to only remove a subset of the children (and leave others intact), then you need to be more specific how one would determine which children to leave and which to remove. In jQuery, you could use a .find() select or a filter() selector to narrow the list of children to just the children you wanted to target for removal.
6,795,585
I have an element with multiple elements inside. All of the elements inside have the same name. Is there any way to remove them using one function? (refer to this question for example [Remove multiple children from parent?](https://stackoverflow.com/questions/6795034/remove-multiple-children-from-parent/6795103)
2011/07/22
[ "https://Stackoverflow.com/questions/6795585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/843787/" ]
**2021 Answer:** Perhaps there are lots of way to do it, such as [Element.replaceChildren()](https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceChildren). I would like to show you an effective solution with **only one redraw & reflow** *supporting all ES6+ browsers*. ``` function removeChildren(cssSelector, parentNode){ var elements = parentNode.querySelectorAll(cssSelector); let fragment = document.createDocumentFragment(); fragment.textContent=' '; fragment.firstChild.replaceWith(...elements); } ``` Usage: `removeChildren('.foo',document.body);`: remove all elements with className `foo` in `<body>`
A sample of your HTML would get you a more complete answer, but one can fairly easy call DOM functions to get the list of children and just remove them. In jQuery, remove all children would be something like this: ``` $("#target > *").remove(); ``` or ``` $("#target").html(""); ``` And, you can see a demo here: <http://jsfiddle.net/jfriend00/ZBYCh/> Or, not using jQuery you could also do: ``` document.getElementById("target").innerHTML = ""; ``` If you're trying to only remove a subset of the children (and leave others intact), then you need to be more specific how one would determine which children to leave and which to remove. In jQuery, you could use a .find() select or a filter() selector to narrow the list of children to just the children you wanted to target for removal.
6,795,585
I have an element with multiple elements inside. All of the elements inside have the same name. Is there any way to remove them using one function? (refer to this question for example [Remove multiple children from parent?](https://stackoverflow.com/questions/6795034/remove-multiple-children-from-parent/6795103)
2011/07/22
[ "https://Stackoverflow.com/questions/6795585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/843787/" ]
Here's a solution that removes the first level children with the specified name for the parent with the specified id. If you want to go deeper, you can recursively call it on the child elements you get inside (you'll have to add a `parent` parameter as well). ``` function removeChildren (params){ var parentId = params.parentId; var childName = params.childName; var childNodes = document.getElementById(parentId).childNodes; for(var i=childNodes.length-1;i >= 0;i--){ var childNode = childNodes[i]; if(childNode.name == 'foo'){ childNode.parentNode.removeChild(childNode); } } } ``` And to call it: ``` removeChildren({parentId:'div1',childName:'foo'}); ``` And a [fiddle](http://jsfiddle.net/briguy37/U8xkg/) for testing: Notes: You can only access the name element dependably in JavaScript when it supported on your element (e.g. NOT on DIVs!). See [here](https://stackoverflow.com/questions/570641/javascript-cant-find-div-element-by-name) for why. **UPDATE:** [Here](http://jsfiddle.net/briguy37/U8xkg/9/)'s a solution using className based on our conversation: ``` function removeChildren (params){ var parentId = params.parentId; var childName = params.childName; var childNodesToRemove = document.getElementById(parentId).getElementsByClassName('foo'); for(var i=childNodesToRemove.length-1;i >= 0;i--){ var childNode = childNodesToRemove[i]; childNode.parentNode.removeChild(childNode); } } ```
ok this should be easy. First get the parent element: ``` var theParent = document.getElementById("notSoHappyFather"); ``` then get an array of the nodes that you want to remove: ``` var theChildren = theParent.getElementsByName("unluckyChild"); ``` Lastly, remove them with a loop: ``` for (var i = 0; i < theChildren.length; i++) { theParent.removeChild(theChildren[i]); } ```
6,795,585
I have an element with multiple elements inside. All of the elements inside have the same name. Is there any way to remove them using one function? (refer to this question for example [Remove multiple children from parent?](https://stackoverflow.com/questions/6795034/remove-multiple-children-from-parent/6795103)
2011/07/22
[ "https://Stackoverflow.com/questions/6795585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/843787/" ]
**2021 Answer:** Perhaps there are lots of way to do it, such as [Element.replaceChildren()](https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceChildren). I would like to show you an effective solution with **only one redraw & reflow** *supporting all ES6+ browsers*. ``` function removeChildren(cssSelector, parentNode){ var elements = parentNode.querySelectorAll(cssSelector); let fragment = document.createDocumentFragment(); fragment.textContent=' '; fragment.firstChild.replaceWith(...elements); } ``` Usage: `removeChildren('.foo',document.body);`: remove all elements with className `foo` in `<body>`
ok this should be easy. First get the parent element: ``` var theParent = document.getElementById("notSoHappyFather"); ``` then get an array of the nodes that you want to remove: ``` var theChildren = theParent.getElementsByName("unluckyChild"); ``` Lastly, remove them with a loop: ``` for (var i = 0; i < theChildren.length; i++) { theParent.removeChild(theChildren[i]); } ```
6,795,585
I have an element with multiple elements inside. All of the elements inside have the same name. Is there any way to remove them using one function? (refer to this question for example [Remove multiple children from parent?](https://stackoverflow.com/questions/6795034/remove-multiple-children-from-parent/6795103)
2011/07/22
[ "https://Stackoverflow.com/questions/6795585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/843787/" ]
Here's a solution that removes the first level children with the specified name for the parent with the specified id. If you want to go deeper, you can recursively call it on the child elements you get inside (you'll have to add a `parent` parameter as well). ``` function removeChildren (params){ var parentId = params.parentId; var childName = params.childName; var childNodes = document.getElementById(parentId).childNodes; for(var i=childNodes.length-1;i >= 0;i--){ var childNode = childNodes[i]; if(childNode.name == 'foo'){ childNode.parentNode.removeChild(childNode); } } } ``` And to call it: ``` removeChildren({parentId:'div1',childName:'foo'}); ``` And a [fiddle](http://jsfiddle.net/briguy37/U8xkg/) for testing: Notes: You can only access the name element dependably in JavaScript when it supported on your element (e.g. NOT on DIVs!). See [here](https://stackoverflow.com/questions/570641/javascript-cant-find-div-element-by-name) for why. **UPDATE:** [Here](http://jsfiddle.net/briguy37/U8xkg/9/)'s a solution using className based on our conversation: ``` function removeChildren (params){ var parentId = params.parentId; var childName = params.childName; var childNodesToRemove = document.getElementById(parentId).getElementsByClassName('foo'); for(var i=childNodesToRemove.length-1;i >= 0;i--){ var childNode = childNodesToRemove[i]; childNode.parentNode.removeChild(childNode); } } ```
**2021 Answer:** Perhaps there are lots of way to do it, such as [Element.replaceChildren()](https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceChildren). I would like to show you an effective solution with **only one redraw & reflow** *supporting all ES6+ browsers*. ``` function removeChildren(cssSelector, parentNode){ var elements = parentNode.querySelectorAll(cssSelector); let fragment = document.createDocumentFragment(); fragment.textContent=' '; fragment.firstChild.replaceWith(...elements); } ``` Usage: `removeChildren('.foo',document.body);`: remove all elements with className `foo` in `<body>`
9,412,881
I am using Eclipse IDE , i need to search a String inside my Project . So inside Eclipse , I clikced Search Item from Menu and Selected File and entered a String "exch" . It is displaying all the results such as "exchange" , but i want to display only the Exact String matched "exch" ![enter image description here](https://i.stack.imgur.com/peQ6V.png)
2012/02/23
[ "https://Stackoverflow.com/questions/9412881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Check the "Regular expression" checkbox, and surround your word with `\b` at the beginning and end which matches beginning and end (boundaries) of a word, so your search term will be `\bexch\b`
Check Regular expression and search `\sexch\s`
10,407
I'm ready to move from MyISAM to InnoDB but wanted to know if there was a full list of things to look for? For example, I haven't seen any list mention that running `DISABLE KEYS` on an InnoDB table will throw a warning, except the manual page for `ALTER TABLE`. It's that kind of thing I need to know about before converting over. I thought I'd be fine with my queries but apparently not.
2012/01/09
[ "https://dba.stackexchange.com/questions/10407", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/5693/" ]
Here are some gotchas **Memory Usage** ================ MyISAM ------ * only caches index pages. * shared keycache (sized by key\_buffer\_size). * [You can also set up dedicated keycache, one or more tables per cache table](http://dev.mysql.com/doc/refman/5.5/en/cache-index.html). InnoDB ------ * caches data pages and index pages. * one buffer pool and one size before MySQL 5.5 * 1 or more buffer pools starting with MySQL 5.5 [Here are some queries I wrote and posted earlier on how to choose a proper size for the MyISAM Key Cache and InnoDB Buffer Pool](https://dba.stackexchange.com/a/2194/877). **FULLTEXT Indexes** ==================== MyISAM ------ * Supports FULLTEXT indexes InnoDB ------ * Starting with MySQL 5.6, yes, [**but still in beta**](https://dba.stackexchange.com/a/8481/877) (UPDATE: MySQL 5.6 exists and has FULLTEXT indexes. If you are using FULLTEXT indexing in MySQL 5.6, make sure you are using the [InnoDB-specific FULLTEXT options](http://dev.mysql.com/doc/refman/5.6/en/innodb-parameters.html#sysvar_innodb_ft_aux_table)) * Before MySQL 5.6, This means you cannot convert MyISAM to InnoDB. MySQL 5.5 and back ------------------ To locate which MyISAM tables have a FULLTEXT index run this query: ``` select tbl.table_schema,tbl.table_name from ( select table_schema,table_name from information_schema.tables where engine='MyISAM' and table_schema NOT IN ('information_schema','mysql') ) tbl INNER JOIN ( select table_schema,table_name from information_schema.statistics where index_type='FULLTEXT' ) ndx USING (table_schema,table_name); ``` Whatever comes out of this query cannot be converted to InnoDB until you upgrade to MySQL 5.6. **OPTIMIZE TABLE** ================== MyISAM ------ * The MyISAM table is shrunk * [ANALYZE TABLE](http://dev.mysql.com/doc/refman/5.5/en/analyze-table.html) runs index statistics on all indexes InnoDB ------ * [ANALYZE TABLE is totally useless because index stats are always being recollected](https://dba.stackexchange.com/a/3402/877) * With [innodb\_file\_per\_table](http://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html#sysvar_innodb_file_per_table) disabled, ibdata1 will grow bigger * With [innodb\_file\_per\_table](http://dev.mysql.com/doc/refman/5.5/en/innodb-parameters.html#sysvar_innodb_file_per_table) enabled, tablespace (.ibd) file is shrunk
I think the biggest gotcha would be around innodb being transactional. You'll want to know if the MySQL libraries being used by your applications auto\_commit by default or not. [Python](http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away), for example, does not auto commit. This means if an application was inserting a row right before closing it's connection that insert would now be rolled back after you alter to innodb. The python script for example would need to be sure to call connection.commit(); Another point of difference could be around around multi row inserts or updates. Consider a single multi row inser ``` insert into tbl values (...row1...), (...row2...), (...rowN....); ``` Consider what happens if there is some kind of error such as a unique key collision on row3. With MyISAM the first two rows would have been written, under innodb all rows being written would be rolled back leaving nothing written in the even of such an error. With innodb you will enter the world of deadlocks. These aren't inherently bad unless they're occuring with such frequency to prevent any work from being done. However your applications will need to be coded in a such a way they anticipate deadlocks and handle them appropriately (which most likely means just retry). Consider memory/storage limitations. Innodb is a lot more resource intensive than MyISAM. If you have enough RAM to keep your buffer pools large enough to accommodate all your tables then you're golden. Look for tables that have large primary keys. Innodb's clustered indexing means each secondary index holds another copy of the corresponding row's PK. If you have 2 secondary indexes that means each rows PK is stored 3 times (PK + each index). If the pk spans across several column and large datatypes (char(N) for example) you can see how the index requirements can quickly explode under innodb.
72,212,425
I have the following function ``` function wordCount(input) { const count = {}; input .forEach(r => { const words = r.split(" ") words.forEach(w => { w = w.replace(/[^a-zöüßä ]/i,"") w = w[0].toUpperCase() + w.slice(1).toLocaleLowerCase(); count[w] = (count[w] || 0) + 1 }) }) const res = [] for(const [word,frequency] of Object.entries(count)) { res.push([word,frequency]) } return res; } ``` I want to pass a column of sentences to the function, and it should return a row with two cells. One with a unique word and the next with it's frequency in the sentences. When using this function iv'e made I just get `r.split` is not a function. Can anyone figure out why?
2022/05/12
[ "https://Stackoverflow.com/questions/72212425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6193913/" ]
You need to make your pictures to fill their layouts, AND keep their aspect ratio. The best way is to set their ["object-fit"](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) css property to "contain". Try this: ``` <Card raised sx={{ maxWidth: 280, margin: "0 auto", padding: "0.1em", }} > <CardMedia component="img" height="250" image={imageNetwork} alt={"alt"} title={"titleasdasdsada"} sx={{ padding: "1em 1em 0 1em", objectFit: "contain" }} /> // Other Content </Card> ```
Try this ``` parent-image-element { width: 100px; } image { width: 100%; max-height: 100px; } ```
6,328,872
Currently I have a servlet `CsmServlet.java` which is getting called by the client side, here is the `web.xml` part ``` <servlet> <display-name>upload</display-name> <servlet-name>upload</servlet-name> <servlet-class>com.abc.csm.web.CsmServlet</servlet-class> </servlet> ``` which is perfect. Now I have to use struts 2 and re factor all of my code so what shall i use in my `struts.xml` to call `CsmServlet` class. Here is my struts.xml, right now i am making a redirect to a another page ``` <struts> <package name="default" extends="struts-default" namespace="/"> <action name="showResult"> <result>/csminfo.jsp</result> </action> </package> </struts> ``` I'll repeat my question, 1. What shall i add to my struts.xml to make a request to CsmServlet class 2. Do I require any changes in my web.inf? My **Servlet** content ``` protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); Map<String, String> requestParamter=getParamMap(req.getParameterMap()); RequestTransformer transformer = new RequestTransformer(req); //(map and operation type) goes to CSMData CSMData data = transformer.transform(requestParamter); RequestHandler handler = new RequestHandler(req); String result = handler.handle(data); log.info(result); out.println(result); } private Map<String,String> getParamMap(Map<String,String[]> params) { Map<String,String> paramsMap = new HashMap<String, String>(); for(Map.Entry<String,String[]> entry : params.entrySet()) { paramsMap.put(entry.getKey(),entry.getValue()[0]); } return paramsMap; } ```
2011/06/13
[ "https://Stackoverflow.com/questions/6328872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707414/" ]
As Struts implements the MVC architecture, ideally you would not want to have your servlet doing the controlling part. You may want to copy the logic from your servlet to the Struts action. In general, you would have two options: 1. Dont have servlets in you code (as controllers) and let the struts handle controlling. Copy the business logic from servlets (if any) into the actions of struts. 2. In case you dont want bigger changes, you could forward you request from Strut's action to the already created servlets. Hope this helps.
Struts has a front controller servlet that accepts all requests and passes them on to Action classes that do the work. I think your servlet is out of a job. It sounds like it should be an Action class that's called by the front controller when clients ask for it.
39,616,729
While browsing Linux kernel code, I found the following two functions in `kernel/capability.c`. **1)** ``` bool has_capability(struct task_struct *t, int cap) /*Does a task have a capability in init_user_ns.*/ ``` **2)** ``` bool has_ns_capability(struct task_struct *t, struct user_namespace *ns, int cap) /*Does a task have a capability in a specific user ns.*/ ``` What is the `init_user` namespace mentioned in the first function? From what I know, a process either has a capability (let us not worry about the different capability sets of a process for now), or it doesn't, so how can a process be said to have a capability with respect to a namespace? If you look at the definition of `cap_get_target_pid()`, in the same file, it just talks about getting capabilities of a process with the given pid, without worrying about the user namespace. This looks more natural to me.
2016/09/21
[ "https://Stackoverflow.com/questions/39616729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981766/" ]
Linux capabilities were introduced in Linux 2.2, while namespaces were introduced in Linux 3.8. I therefore though that since they were developed independently, they should have independent existence. As I now realise, after reading these articles ([Link1](https://lwn.net/Articles/420328/) and [Link2](https://lwn.net/Articles/420624/)) the situation is not quite so. The confluence of the two technologies occurred when there was a need of allowing underprivileged processes to create user namespaces. Inside the created user namespace, the process could have all the capabilities but it should be powerless outside. Thus, if a process P1 is trying to send IPC to another process P2, and P1 has the capability to send IPC, the kernel must not just check for the capability, but it must check whether P1 has the required capability with respect to the user namespace of the process P2. The user namespaces of the two processes can be completely disjoint, with no IPC capabilities over one another, hence this operation must not be allowed. However, process P1 must be allowed to send IPC to all processes in its own user namespace. From [this](https://en.wikipedia.org/wiki/Linux_namespaces) wikipedia article, ``` Permissions for namespace of the other kinds are checked in the user namespace, they got created in. ``` As pointed out by [Gil Hamilton](https://stackoverflow.com/a/39627154/981766), the `init_user` namespace (`init_user_ns`) is just the root namespace, i.e. the user namespace that is created at boot time. [Here](https://www.evernote.com/shard/s415/sh/fb20594c-0503-480d-b1de-b6efebfdef29/eacbd4e3b2e7c84891da01ba52cc2d5c) is my complete writeup on the topic.
Namespaces are the key to containers, such as `docker` and the like. They provide resource isolation between the containers. The idea is that each container has separate namespaces for a number of attribute types, including process and thread IDs, user and group IDs, TCP/UDP ports, network interfaces, mounted filesystems, etc. Each container is able to behave as if it were the entire system. The namespaces prevent processes in one namespace from being able to access those in another (except as configured), or their actions inadvertently bleeding over into another. The `init_user` namespace is the "user namespace" belonging to the underlying host system (aka the "root" namespace). Since namespaces are hierarchical, if a process is in the init\_user namespace, its capabilities are effective in the root namespace and all others (since they are all descendants of the root namespace).
13,350,485
Here is [a jsFiddle](http://jsfiddle.net/bmh_ca/SksQ3/1/) demonstrating the following problem: Given a foreach binding over a list of (observable) strings, the observables do not seem to update from changes to input tags bound inside the foreach. One would expect them to. Here's the example from the jsFiddle: ### HTML ``` <ul data-bind='foreach: list'> <li><input data-bind='value: $data'/></li> </ul> <ul data-bind='foreach: list'> <li><span data-bind='text: $data'></span></li> </ul> ``` ### Javascript ``` ​var vm = { list: [ko.observable('123'), ko.observable('456')] }; ko.applyBindings(vm);​ ``` In the above example, one would expect that updating the input tags in the first list would cause the observables to update. Unfortunately they do not update as expected, as can be seen by the failure of the second list to reflect any changes to made to the first. I verified that the list was not in fact being updated when the input elements are changed. Interestingly, changes made to the observables are reflected in both lists (as one would expect). Namely, `vm.list[1]("444")` will update the second element of both lists. My recollection is that Knockout 2.0.0 did not have this issue, though I stand to be corrected. I did not find any documentation, Google or comments in the Knockout code that yielded any indication as to why this does not work or how to achieve the outcome expected. Why does this not work as expected, and are there any workarounds that do not require changing the data structure?
2012/11/12
[ "https://Stackoverflow.com/questions/13350485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
I worked around this by using `value: $parent.list[$index()]`, as seen in [this jsFiddle](http://jsfiddle.net/bmh_ca/SksQ3/3/). The new bindings looks like this: ``` <ul data-bind='foreach: list'> <li> <input data-bind='value: $parent.list[$index()]' /> </li> </ul> ``` One could perhaps improve on this with a custom binding. See also this related [GitHub issue #708](https://github.com/SteveSanderson/knockout/issues/708) for Knockout.js. **Update for Knockout 3.0:** Knockout now provides `$rawData`: ``` <ul data-bind='foreach: list'> <li><input data-bind='value: $rawData'/></li> </ul> ``` creates a two-way binding as expected. From the *[Binding Context](http://knockoutjs.com/documentation/binding-context.html)* documentation: > > $rawData > > > This is the raw view model value in the current context. Usually this > will be the same as $data, but if the view model provided to Knockout > is wrapped in an observable, $data will be the unwrapped view model, > and $rawData will be the observable itself. > > >
Every data object used in the default knockout bindings will always be unwrapped. So you are essentially binding to the value of the items in the list, not the observable as you are expecting. Observables should be properties of an object, not a replacement of the object itself. Set the observables as a property of some object so this doesn't happen. ``` ​var vm = { list: [ { value: ko.observable('123') }, { value: ko.observable('456') } ] }; ``` ``` <ul data-bind='foreach: list'> <li><input data-bind='value: value'/></li> </ul> <ul data-bind='foreach: list'> <li><span data-bind='text: value'></span></li> </ul> ```
16,818,309
I'm trying to copy my uploaded file to another directory called **img** folder with following code. But it doesn't work properly. I don't know why ? can you help me plz ? **php Code:** ``` if($image["name"] != "") { //$path = PATH . DS . "uploads" . DS . "products" . DS . $id; $path = "../../uploads" . DS . "products" . DS . $id; $path2 = "img"; if(!is_dir($path)) { mkdir($path); } chmod($path, 0755); //move_uploaded_file($image["tmp_name"], $path . DS . $image["name"]); move_uploaded_file($image["tmp_name"], $path . DS . $uploadImage);//exit; copy($uploadImage, $path2); } ``` **Following error message show:** ``` Warning: copy(249.jpg) [function.copy]: failed to open stream: No such file or directory in... ```
2013/05/29
[ "https://Stackoverflow.com/questions/16818309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2331198/" ]
The `copy()` function needs the full file path for the source file; you're just passing the filename, not the path. As things stand, it's looking in the current folder for the file, not finding it, and throwing the error as a result. From the previous line of code, it looks like your full path should be `$path . DS . $uploadImage`, so the copy command should look like this: ``` copy($path . DS . $uploadImage, $path2); ``` hope that helps.
Your copy function is wrong... ``` copy($uploadImage, $path2); ``` As Spudley answer says, you have to use the full path of the image. Also, `$path2` is a directory. You have to give a name for the new copy of the image. So, your copy function would be as follows: ``` copy($path . DS . $uploadImage, $path2. DS . $uploadImage); ``` Try it and let us know.
5,982,094
I have managed to fork and exec a different program from within my app. I'm currently working on how to wait until the process called from exec returns a result through a pipe or stdout. However, can I have a group of processes using a single fork, or do I have to fork many times and call the same program again? Can I get a PID for each different process ? I want my app to call the same program I'm currently calling many times but with different parameters: I want a group of 8 processes of the same program running and returning results via pipes. Can someone please point me to the right direction please ? I've gone through the linux.die man pages, but they are quite spartan and cryptic in their description. Is there an ebook or pdf I can find for detailed information ? Thank you! ``` pid_t pID = fork(); if (pID == 0){ int proc = execl(BOLDAGENT,BOLDAGENT,"-u","2","-c","walkevo.xml",NULL); std::cout << strerror(errno) << std::endl; } ``` For example, how can I control by PID which child (according to the parameter xml file) has obtained which result (by pipe or stdout), and thus act accordingly? Do I have to encapsulate children processes in an object, and work from there, or can I group them altogether?
2011/05/12
[ "https://Stackoverflow.com/questions/5982094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/499699/" ]
One `Fork` syscall make only one new process (one PID). You should organize some data structures (e.g. array of pids, array of parent's ends of pipes, etc), do 8 fork from main program (every child will do `exec`) and then wait for childs. After each fork() it will return you a PID of child. You can store this pid and associated information like this: ``` #define MAX_CHILD=8 pid_t pids[MAX_CHILD]; int pipe_fd[MAX_CHILD]; for(int child=0;child<MAX_CHILD;child++) { int pipe[2]; /* create a pipe; save one of pipe fd to the pipe_fd[child] */ int ret; ret = fork(); if(ret) { /* parent */ /* close alien half of pipe */ pids[child] = ret; /* save the pid */ } else { /* child */ /* close alien half of pipe */ /* We are child #child, exec needed program */ exec(...); /* here can be no more code in the child, as `exec` will not return if there is no error! */ } } /* there you can do a `select` to wait data from several pipes; select will give you number of fd with data waiting, you can find a pid from two arrays */ ```
It's mind-bending at first, but you seem to grasp that, when you call fork( ): * the calling process (the "parent") is essentially duplicated by the operating system and the duplicate process becomes the "child" with a unique PID all its own; * the returned value from the fork( ) call is either: integer 0,1 meaning that the program receiving the 0 return is the "child"; or it is the non-zero integer PID of that forked child; and * the new child process is entered into the scheduling queue for execution. The parent remains in the scheduling queue and continues to execute as before. It is this ( 0 **.xor.** non-0 ) return from fork( ) that tells the program which role it's playing at this instant -- 0 returned, program is the child process; anything else returned, program is the parent process. If the program playing the parent role wants many children, he has to fork( ) each one separately; there's no such thing as multiple children sharing a fork( ). Intermediate results certainly can be sent via a pipe. As for calling each child with different parameters, there's really nothing special to do: you can be sure that, when the child gets control, he will have (copies of) exactly the same variables as does the parent. So communicating parameters to the child is a matter of the parent's setting up variable values he wants the child to operate on; and then calling fork( ). --- 1 More accurately: fork( ) returns a value of type `pid_t`, which these days is identical to an integer on quite a few systems.
5,982,094
I have managed to fork and exec a different program from within my app. I'm currently working on how to wait until the process called from exec returns a result through a pipe or stdout. However, can I have a group of processes using a single fork, or do I have to fork many times and call the same program again? Can I get a PID for each different process ? I want my app to call the same program I'm currently calling many times but with different parameters: I want a group of 8 processes of the same program running and returning results via pipes. Can someone please point me to the right direction please ? I've gone through the linux.die man pages, but they are quite spartan and cryptic in their description. Is there an ebook or pdf I can find for detailed information ? Thank you! ``` pid_t pID = fork(); if (pID == 0){ int proc = execl(BOLDAGENT,BOLDAGENT,"-u","2","-c","walkevo.xml",NULL); std::cout << strerror(errno) << std::endl; } ``` For example, how can I control by PID which child (according to the parameter xml file) has obtained which result (by pipe or stdout), and thus act accordingly? Do I have to encapsulate children processes in an object, and work from there, or can I group them altogether?
2011/05/12
[ "https://Stackoverflow.com/questions/5982094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/499699/" ]
One `Fork` syscall make only one new process (one PID). You should organize some data structures (e.g. array of pids, array of parent's ends of pipes, etc), do 8 fork from main program (every child will do `exec`) and then wait for childs. After each fork() it will return you a PID of child. You can store this pid and associated information like this: ``` #define MAX_CHILD=8 pid_t pids[MAX_CHILD]; int pipe_fd[MAX_CHILD]; for(int child=0;child<MAX_CHILD;child++) { int pipe[2]; /* create a pipe; save one of pipe fd to the pipe_fd[child] */ int ret; ret = fork(); if(ret) { /* parent */ /* close alien half of pipe */ pids[child] = ret; /* save the pid */ } else { /* child */ /* close alien half of pipe */ /* We are child #child, exec needed program */ exec(...); /* here can be no more code in the child, as `exec` will not return if there is no error! */ } } /* there you can do a `select` to wait data from several pipes; select will give you number of fd with data waiting, you can find a pid from two arrays */ ```
It's been a while since I've worked in C/C++, but a few points: * The Wikipedia [fork-exec page](http://en.wikipedia.org/wiki/Fork-exec) provides a starting point to learn about forking and execing. Google is your friend here too. * As osgx's answer says, fork() can only give you one subprocess, so you'll have to call it 8 times to get 8 processes and then each one will have to exec the other program. * fork() returns the PID of the child process to the main process and 0 to the subprocess, so you should be able to do something like: ```c int pid = fork(); if (pid == 0) { /* exec new program here */ } else { /* continue with parent process stuff */ } ```
5,982,094
I have managed to fork and exec a different program from within my app. I'm currently working on how to wait until the process called from exec returns a result through a pipe or stdout. However, can I have a group of processes using a single fork, or do I have to fork many times and call the same program again? Can I get a PID for each different process ? I want my app to call the same program I'm currently calling many times but with different parameters: I want a group of 8 processes of the same program running and returning results via pipes. Can someone please point me to the right direction please ? I've gone through the linux.die man pages, but they are quite spartan and cryptic in their description. Is there an ebook or pdf I can find for detailed information ? Thank you! ``` pid_t pID = fork(); if (pID == 0){ int proc = execl(BOLDAGENT,BOLDAGENT,"-u","2","-c","walkevo.xml",NULL); std::cout << strerror(errno) << std::endl; } ``` For example, how can I control by PID which child (according to the parameter xml file) has obtained which result (by pipe or stdout), and thus act accordingly? Do I have to encapsulate children processes in an object, and work from there, or can I group them altogether?
2011/05/12
[ "https://Stackoverflow.com/questions/5982094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/499699/" ]
It's mind-bending at first, but you seem to grasp that, when you call fork( ): * the calling process (the "parent") is essentially duplicated by the operating system and the duplicate process becomes the "child" with a unique PID all its own; * the returned value from the fork( ) call is either: integer 0,1 meaning that the program receiving the 0 return is the "child"; or it is the non-zero integer PID of that forked child; and * the new child process is entered into the scheduling queue for execution. The parent remains in the scheduling queue and continues to execute as before. It is this ( 0 **.xor.** non-0 ) return from fork( ) that tells the program which role it's playing at this instant -- 0 returned, program is the child process; anything else returned, program is the parent process. If the program playing the parent role wants many children, he has to fork( ) each one separately; there's no such thing as multiple children sharing a fork( ). Intermediate results certainly can be sent via a pipe. As for calling each child with different parameters, there's really nothing special to do: you can be sure that, when the child gets control, he will have (copies of) exactly the same variables as does the parent. So communicating parameters to the child is a matter of the parent's setting up variable values he wants the child to operate on; and then calling fork( ). --- 1 More accurately: fork( ) returns a value of type `pid_t`, which these days is identical to an integer on quite a few systems.
It's been a while since I've worked in C/C++, but a few points: * The Wikipedia [fork-exec page](http://en.wikipedia.org/wiki/Fork-exec) provides a starting point to learn about forking and execing. Google is your friend here too. * As osgx's answer says, fork() can only give you one subprocess, so you'll have to call it 8 times to get 8 processes and then each one will have to exec the other program. * fork() returns the PID of the child process to the main process and 0 to the subprocess, so you should be able to do something like: ```c int pid = fork(); if (pid == 0) { /* exec new program here */ } else { /* continue with parent process stuff */ } ```
4,004,926
I cannot seem to find a solution to the following Diophantine Equation: $x^2-y^3=2$, where $x,y \in \mathbb{Z}.$ I thought that I could maybe reduce it to a simpler equation , maybe check for the extension $\mathbb{Q}\left[\sqrt{2}\right],$ but nothing that I have tried seems to work. Perhaps it is a known equation/curve I am not aware of? I was first introduced to the problem when my friend pointed out that he could not solve it. I would appreciate your help. Thanks, in advance.
2021/01/29
[ "https://math.stackexchange.com/questions/4004926", "https://math.stackexchange.com", "https://math.stackexchange.com/users/870427/" ]
Let $x$ and $y$ be integers such that $x^2-y^3=2$. Then $x$ and $y$ are both odd, and $$y^3=(x-\sqrt{2})(x+\sqrt{2}),$$ where the gcd of the two factors on the right hand side divides their sum $2\sqrt{2}=\sqrt{2}^3$, and because their product is odd we see that they are coprime. Because $\Bbb{Z}[\sqrt{2}]$ is a unique factorization domain we have $$x+\sqrt{2}=u(a+b\sqrt{2})^3,$$ for some integers $a$ and $b$, and some unit $u\in\Bbb{Z}[\sqrt{2}]^{\times}$. Then $u=\pm(1+\sqrt{2})^k$ for some integer $k$, and without loss of generality we have the $+$-sign and $k\in\{0,1,2\}$. So we distinguish three cases: * If $k=0$ then $$x+\sqrt{2}=(a+b\sqrt{2})^3=a(a^2+6b^2)+b(3a^2+2b^2)\sqrt{2},$$ and comparing the coefficients of $\sqrt{2}$ shows that $$b(3a^2+2b^2)=1,$$ which clearly has no integral solutions. * If $k=1$ then in a similar way we find that $$a^3+3a^2b+6ab^2+2b^3=1,$$ which is a(nother) cubic Thue equation. Its unique integral solution is $(a,b)=(1,0)$, corresponding to $x=1$. * If $k=2$ then in a similar way we find that $$2a^3+9a^2b+12ab^2+6b^3=1,$$ which is another cubic Thue equation. Its unique integral solution is $(a,b)=(-1,1)$, corresponding to $x=-1$.
$x^2-y^3=2\quad\implies\quad y=\sqrt[\large3]{x^2-2}\quad\lor\quad x=\sqrt{y^3+2}\quad$ Both equations are true only when $\quad (x,y)=(\pm1,-1)$ For larger values, no squares and cubes differ by only $2$.
4,004,926
I cannot seem to find a solution to the following Diophantine Equation: $x^2-y^3=2$, where $x,y \in \mathbb{Z}.$ I thought that I could maybe reduce it to a simpler equation , maybe check for the extension $\mathbb{Q}\left[\sqrt{2}\right],$ but nothing that I have tried seems to work. Perhaps it is a known equation/curve I am not aware of? I was first introduced to the problem when my friend pointed out that he could not solve it. I would appreciate your help. Thanks, in advance.
2021/01/29
[ "https://math.stackexchange.com/questions/4004926", "https://math.stackexchange.com", "https://math.stackexchange.com/users/870427/" ]
Let $x$ and $y$ be integers such that $x^2-y^3=2$. Then $x$ and $y$ are both odd, and $$y^3=(x-\sqrt{2})(x+\sqrt{2}),$$ where the gcd of the two factors on the right hand side divides their sum $2\sqrt{2}=\sqrt{2}^3$, and because their product is odd we see that they are coprime. Because $\Bbb{Z}[\sqrt{2}]$ is a unique factorization domain we have $$x+\sqrt{2}=u(a+b\sqrt{2})^3,$$ for some integers $a$ and $b$, and some unit $u\in\Bbb{Z}[\sqrt{2}]^{\times}$. Then $u=\pm(1+\sqrt{2})^k$ for some integer $k$, and without loss of generality we have the $+$-sign and $k\in\{0,1,2\}$. So we distinguish three cases: * If $k=0$ then $$x+\sqrt{2}=(a+b\sqrt{2})^3=a(a^2+6b^2)+b(3a^2+2b^2)\sqrt{2},$$ and comparing the coefficients of $\sqrt{2}$ shows that $$b(3a^2+2b^2)=1,$$ which clearly has no integral solutions. * If $k=1$ then in a similar way we find that $$a^3+3a^2b+6ab^2+2b^3=1,$$ which is a(nother) cubic Thue equation. Its unique integral solution is $(a,b)=(1,0)$, corresponding to $x=1$. * If $k=2$ then in a similar way we find that $$2a^3+9a^2b+12ab^2+6b^3=1,$$ which is another cubic Thue equation. Its unique integral solution is $(a,b)=(-1,1)$, corresponding to $x=-1$.
COMMENT.- The discriminant $\Delta = - (4a ^ 3 + 27b ^ 2)$ of the curve $x ^ 2 = y ^ 3 + 2$ considering it as a case of $y ^ 2 = x ^ 3 + ax + b$ (Weirstrass form) in which they have reversed the usual roles of the coordinates, it is different from zero so the curve is not singular or elliptic. There is an obvious solution $A = (x, y) = (1, -1)$. It is doubtful that the tangent to the curve in this integer point (that is, $2A$ in the arithmetic of the elliptic curve) produces another integer point (*in fact graphically it does not give it*) but **if this point $A$ is not torsion then it will produce an infinity of rational points on the curve**. We do not apply the operations that define an additive group law on the curve because this is not the case here. Regarding solving the equation $x^2-y ^ 3 = 2$ by other means, this has the savor of the Catalan's conjecture that lasted almost two centuries to be proven by Mihăilescu's so we better stop here this comment.
4,004,926
I cannot seem to find a solution to the following Diophantine Equation: $x^2-y^3=2$, where $x,y \in \mathbb{Z}.$ I thought that I could maybe reduce it to a simpler equation , maybe check for the extension $\mathbb{Q}\left[\sqrt{2}\right],$ but nothing that I have tried seems to work. Perhaps it is a known equation/curve I am not aware of? I was first introduced to the problem when my friend pointed out that he could not solve it. I would appreciate your help. Thanks, in advance.
2021/01/29
[ "https://math.stackexchange.com/questions/4004926", "https://math.stackexchange.com", "https://math.stackexchange.com/users/870427/" ]
Let $x$ and $y$ be integers such that $x^2-y^3=2$. Then $x$ and $y$ are both odd, and $$y^3=(x-\sqrt{2})(x+\sqrt{2}),$$ where the gcd of the two factors on the right hand side divides their sum $2\sqrt{2}=\sqrt{2}^3$, and because their product is odd we see that they are coprime. Because $\Bbb{Z}[\sqrt{2}]$ is a unique factorization domain we have $$x+\sqrt{2}=u(a+b\sqrt{2})^3,$$ for some integers $a$ and $b$, and some unit $u\in\Bbb{Z}[\sqrt{2}]^{\times}$. Then $u=\pm(1+\sqrt{2})^k$ for some integer $k$, and without loss of generality we have the $+$-sign and $k\in\{0,1,2\}$. So we distinguish three cases: * If $k=0$ then $$x+\sqrt{2}=(a+b\sqrt{2})^3=a(a^2+6b^2)+b(3a^2+2b^2)\sqrt{2},$$ and comparing the coefficients of $\sqrt{2}$ shows that $$b(3a^2+2b^2)=1,$$ which clearly has no integral solutions. * If $k=1$ then in a similar way we find that $$a^3+3a^2b+6ab^2+2b^3=1,$$ which is a(nother) cubic Thue equation. Its unique integral solution is $(a,b)=(1,0)$, corresponding to $x=1$. * If $k=2$ then in a similar way we find that $$2a^3+9a^2b+12ab^2+6b^3=1,$$ which is another cubic Thue equation. Its unique integral solution is $(a,b)=(-1,1)$, corresponding to $x=-1$.
This is an elliptic curve, and can be solved by a computer algebra system. I use the following code on [sage cell server](https://sagecell.sagemath.org/), and you can also try it yourself. ``` E = EllipticCurve([0, 2]) print(E.integral_points()) ``` The output: ``` [(-1 : 1 : 1)] ``` Therefore this is (up to sign) the only non-trivial solution. An interesting fact is that this curve actually has Mordell-Weil rank $1$, meaning that it has infinitely many rational points. Examples: ``` (17/4 : -71/8 : 1) (127/441 : 13175/9261 : 1) (66113/80656 : -36583777/22906304 : 1) ``` etc. All these calculations are done with Sage. How does Sage do that, and how can Sage be sure that the results are correct? This is a much deeper subject. A good starting point is the GTM book "The Arithmetic of Elliptic Curves" by Joe Silverman.
4,004,926
I cannot seem to find a solution to the following Diophantine Equation: $x^2-y^3=2$, where $x,y \in \mathbb{Z}.$ I thought that I could maybe reduce it to a simpler equation , maybe check for the extension $\mathbb{Q}\left[\sqrt{2}\right],$ but nothing that I have tried seems to work. Perhaps it is a known equation/curve I am not aware of? I was first introduced to the problem when my friend pointed out that he could not solve it. I would appreciate your help. Thanks, in advance.
2021/01/29
[ "https://math.stackexchange.com/questions/4004926", "https://math.stackexchange.com", "https://math.stackexchange.com/users/870427/" ]
COMMENT.- The discriminant $\Delta = - (4a ^ 3 + 27b ^ 2)$ of the curve $x ^ 2 = y ^ 3 + 2$ considering it as a case of $y ^ 2 = x ^ 3 + ax + b$ (Weirstrass form) in which they have reversed the usual roles of the coordinates, it is different from zero so the curve is not singular or elliptic. There is an obvious solution $A = (x, y) = (1, -1)$. It is doubtful that the tangent to the curve in this integer point (that is, $2A$ in the arithmetic of the elliptic curve) produces another integer point (*in fact graphically it does not give it*) but **if this point $A$ is not torsion then it will produce an infinity of rational points on the curve**. We do not apply the operations that define an additive group law on the curve because this is not the case here. Regarding solving the equation $x^2-y ^ 3 = 2$ by other means, this has the savor of the Catalan's conjecture that lasted almost two centuries to be proven by Mihăilescu's so we better stop here this comment.
$x^2-y^3=2\quad\implies\quad y=\sqrt[\large3]{x^2-2}\quad\lor\quad x=\sqrt{y^3+2}\quad$ Both equations are true only when $\quad (x,y)=(\pm1,-1)$ For larger values, no squares and cubes differ by only $2$.
4,004,926
I cannot seem to find a solution to the following Diophantine Equation: $x^2-y^3=2$, where $x,y \in \mathbb{Z}.$ I thought that I could maybe reduce it to a simpler equation , maybe check for the extension $\mathbb{Q}\left[\sqrt{2}\right],$ but nothing that I have tried seems to work. Perhaps it is a known equation/curve I am not aware of? I was first introduced to the problem when my friend pointed out that he could not solve it. I would appreciate your help. Thanks, in advance.
2021/01/29
[ "https://math.stackexchange.com/questions/4004926", "https://math.stackexchange.com", "https://math.stackexchange.com/users/870427/" ]
This is an elliptic curve, and can be solved by a computer algebra system. I use the following code on [sage cell server](https://sagecell.sagemath.org/), and you can also try it yourself. ``` E = EllipticCurve([0, 2]) print(E.integral_points()) ``` The output: ``` [(-1 : 1 : 1)] ``` Therefore this is (up to sign) the only non-trivial solution. An interesting fact is that this curve actually has Mordell-Weil rank $1$, meaning that it has infinitely many rational points. Examples: ``` (17/4 : -71/8 : 1) (127/441 : 13175/9261 : 1) (66113/80656 : -36583777/22906304 : 1) ``` etc. All these calculations are done with Sage. How does Sage do that, and how can Sage be sure that the results are correct? This is a much deeper subject. A good starting point is the GTM book "The Arithmetic of Elliptic Curves" by Joe Silverman.
$x^2-y^3=2\quad\implies\quad y=\sqrt[\large3]{x^2-2}\quad\lor\quad x=\sqrt{y^3+2}\quad$ Both equations are true only when $\quad (x,y)=(\pm1,-1)$ For larger values, no squares and cubes differ by only $2$.
18,639,962
My controller calls this model method on update: ``` def update_standard(param_attributes) ... if param_attributes[:is_legacy] == true param_attributes[:foo_type_id] = 2 end update_attributes(param_attributes) end ``` `foo_type_id` should overwrite whatever the user entered in the form, but the user's choice is what is written to the DB. How can I enforce `foo_type_id` being 2 when `is_legacy` is true?
2013/09/05
[ "https://Stackoverflow.com/questions/18639962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810434/" ]
``` param_attributes[:is_legacy] == "true" ? param_attributes[:foo_type_id] = 2 : param_attributes[:foo_type_id] update_attributes(param_attributes) ```
I think there could be some issues with your logic evaluation. Try changing this to the following and see if it works? ``` if !param_attributes[:is_legacy].nil? && param_attributes[:is_legacy].to_sym == :true param_attributes[:foo_type_id] = 2 end ```
18,639,962
My controller calls this model method on update: ``` def update_standard(param_attributes) ... if param_attributes[:is_legacy] == true param_attributes[:foo_type_id] = 2 end update_attributes(param_attributes) end ``` `foo_type_id` should overwrite whatever the user entered in the form, but the user's choice is what is written to the DB. How can I enforce `foo_type_id` being 2 when `is_legacy` is true?
2013/09/05
[ "https://Stackoverflow.com/questions/18639962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810434/" ]
You should check to make sure that `params[:is_legacy]` actually returns `true` and not `"true"` -- pretty sure params are always strings.
I think there could be some issues with your logic evaluation. Try changing this to the following and see if it works? ``` if !param_attributes[:is_legacy].nil? && param_attributes[:is_legacy].to_sym == :true param_attributes[:foo_type_id] = 2 end ```
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
How much time have you spent already trying to fix the PC? You may just find that booting with something like an Ubuntu live CD to copy all data to a removable USB hard drive, then formatting the disk and re-installing is actually the fastest way to solve this problem. I've seen it happen time and time again where so many more hours are spent trying to remove viruses or malware than what it takes to simply backup, format and re-install. I know you don't want to do this, you would rather use a tool to fix the problem, but I think you'll save time by doing a clean install and you'll also know that the malware is really gone. You computer will probably run faster as well as this is usually the case on a fresh install.
Most, but not all, malware can be **manually** removed with [autoruns](http://technet.microsoft.com/en-us/sysinternals/bb963902). Try the following procedure: * download autoruns from the above link and run it straight from the zip archive * let it scan (if it can) * look for two types of entries - ones with **no signature** and more importantly entries which say '**file not found**'. The second kind is typical for viruses that insert themselves into various parts of the system that get executed during start time (but upon startup they temporarily remove the infected file and make it accessible only on the next restart). By unticking the problematic/suspicious entries you can cripple the malware to the point that it will not be active in the system anymore (and if you untick something that is needed you can always tick it back on). Now, if you can not run autoruns that would be due to the virus already blocking it - however viruses will rarely do that. This procedure is surprisingly efficient, but of course this is only due to viruses not targeting it. You can always try it. After going through it you can use * [process explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653) to check if there are strange processes running on you system * [tcpview](http://technet.microsoft.com/en-us/sysinternals/bb897437) to audit and monitor your network activity Using these tools is not trivial (does require knowledge of the normal system behavior), but in case that * the regular anti-virus software does not recognize the threat yet neither will booting to linux and trying to clean with clamav * you really want to try to clean it and try to avoid re-format you can try to follow the procedure I gave.
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
So, after spending several days fighting this thing, I finally got rid of it. I'm pretty sure I got the right one, but along the way I found some suspicious items that could have contributed. Here's the steps it took to clean it up. First thing I did was to check all of the autostart locations on windows. I followed this article [here](http://www.bleepingcomputer.com/tutorials/tutorial44.html). Most of the locations where clean except for: 1. `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit` * This key had a second path on it pointing to `C:\Documents and Settings\NetworkService\Application Data\09A52917-B4FC-4f02-AE3B-BF55D9351F4A\msvcs.exe` 2. `HKLM\Software\Microsoft\Windows\CurrentVersion\Run` * This node had a `REG_SZ` key named `2C508BD5-F9C6-4955-B93A-09B835EC3C64` which was pointing to the msvcs.exe file in the `Userinit` key. 3. `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify` * This node had two other nodes that looked suspicious to me. They were named `\toldvw32` and `torlfsvses`. Both nodes had keys that pointed to a `toldvw32.dll` file and were set with a `WlStartupEvent` event. Looking these up on Google didn't produce any meaningful results at the time, so I went ahead an removed them. There doesn't seem to be problems with having done that yet. The real issue is that `msvcs.exe` file. If one manages to survive it will replicate it self across all user profiles on the machine. Since it was hooked up into the `NetworkService` profile it would always make sure it existed in the other profiles. There's three locations where `msvcs.exe` exists. They are: 1. `{PROFILE}/Application Data/09A52917-B4FC-4f02-AE3B-BF55D9351F4A` 2. `{PROFILE}/Start Menu/Programs/Startup` 3. `WINDOWS\Prefetch` * Not 100% sure on this one, but I did find two suspicious files: `MSVCS.EXE-0CA809BA.pf` and `MSVCS.EXE-301B4EC0.pf`. I went ahead and removed them without issues (so far at-least). I hope this helps someone in the future. It worked for me. If you have a computer that had/has this and it's hooked up to a domain make sure to check the user's profile folder on the server as well, there's a copy there too. Needless to say, ***don't*** login into that profile directly on the server because you're just going to have a very fun time after that... Also, you can't clean it through Safe Mode if the profile you're logging into has been infected. I used [UBCD4Win](http://www.ubcd4win.com/) to clean up what I saw, then I did the rest through Safe Mode. Now, I know the general consensus is to nuke the computer and start from scratch, but that is not always possible in a business environment. After I had it cleaned up and confirmed clean by several antivirus tools I ran `chkdsk /f /r` on the drive, defragmented it with [MyDefrag (4.3.1)](http://mydefrag.com/) and the computer works perfectly as if it never happened. So, nuking the computer is not always the best course of action as @Synetech pointed out him/her self. Lastly, Kaspersky was installed on the computer, but somehow was turned off and that's how the virus (malware?) got through and did what it did. I'm not a fan of antivirus software at all, in fact I don't have any on my 6 or so machines that I have, but in an environment where you have technically challenged personel, it is a good idea to have it and its also a very good idea to make sure it's actually turned *on* and updated. That is all fellow awesome people. I hope someone else can benefit from this answer in the future.
This seems to be a brand new scareware. As far as I see, it has not been described by the antivirus specialists yet. It threatens to delete the contents of the disk and sue you for using an illegal copy of Windows. I propose you turn off the infected computer, remove the disk and copy the contents of the disk to some safe spot. Then you can also retry a virusscan while attached to a different computer (not booting this infected disk). Personally, I would backup the data and go for a fresh install. Once a malware was on a windows, there is no way to make sure all traces have been removed, because once they have a hold of your computer they will continue to try and use it / your data / your bank account. In cases like this, it seems to be usual to load more malware onto the computer. Users of this computer should change their passwords, if banking has been done, check their bank accounts and set a new PIN. Oh, and dont pay. If you do, it might ask for admin permissions to "fix" your windows, and then rootkit you for good.
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
As it's been said over and over again, the *only* sure-fire way to ensure that a virus is gone is to format your computer, and re-install things one by one. That said, this isn't technically a virus, but a new kind of malware that makes you pay to remove it, which you should not do under any circumstances, because you're contributing to organised crime.
Most, but not all, malware can be **manually** removed with [autoruns](http://technet.microsoft.com/en-us/sysinternals/bb963902). Try the following procedure: * download autoruns from the above link and run it straight from the zip archive * let it scan (if it can) * look for two types of entries - ones with **no signature** and more importantly entries which say '**file not found**'. The second kind is typical for viruses that insert themselves into various parts of the system that get executed during start time (but upon startup they temporarily remove the infected file and make it accessible only on the next restart). By unticking the problematic/suspicious entries you can cripple the malware to the point that it will not be active in the system anymore (and if you untick something that is needed you can always tick it back on). Now, if you can not run autoruns that would be due to the virus already blocking it - however viruses will rarely do that. This procedure is surprisingly efficient, but of course this is only due to viruses not targeting it. You can always try it. After going through it you can use * [process explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653) to check if there are strange processes running on you system * [tcpview](http://technet.microsoft.com/en-us/sysinternals/bb897437) to audit and monitor your network activity Using these tools is not trivial (does require knowledge of the normal system behavior), but in case that * the regular anti-virus software does not recognize the threat yet neither will booting to linux and trying to clean with clamav * you really want to try to clean it and try to avoid re-format you can try to follow the procedure I gave.
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
As it's been said over and over again, the *only* sure-fire way to ensure that a virus is gone is to format your computer, and re-install things one by one. That said, this isn't technically a virus, but a new kind of malware that makes you pay to remove it, which you should not do under any circumstances, because you're contributing to organised crime.
It seems to be the [BKA Trojan](http://www.google.com/search?q=bka%20trojan) (the first couple of results are links to the scareware’s site, so don’t use those). It seems that the [consensus](http://translate.google.com/translate?hl=en&sl=auto&tl=en&twu=1&u=http://www.computerbase.de/forum/showthread.php?t=940165) is to either reinstall, or use more anti-malware software. Re-installing should be a last resort; trying to remove it is better. The worst that can happen is that you end up re-installing anyway and “waste” some time learning some stuff. It may seem silly/obvious, but have you tried pressing Alt+F4 on the window? --- I can suggest trying a few more softwares to try (run them in safe-mode to for better results): * [SUPERAntiSpyware](http://www.superantispyware.com/) (use the portable version) * [Autoruns](http://technet.microsoft.com/en-us/sysinternals/bb963902) (to weed out where it is running from) * [HijackThis](http://free.antivirus.com/hijackthis/) (to analyze the system fairly throughly) * [WinSpy++](http://catch22.net/software/winspy) (to remove the topmost attribute from the window, though it may reset it every couple of seconds) * [ComboFix](http://www.bleepingcomputer.com/combofix/how-to-use-combofix) (scorched-Earth last resort) Another thing to try is to quickly look in the Task Manager’s Processes tab to try to figure out which process(es) the trojan is running from, and try to kill it (you don’t need to see it the Task Manager to kill it, you can type out the first several letters of the EXE name, and press `Del`, then `Space`), though make sure that the Task Manager’s Always-On-Top option is selected; just in case. --- (Side note: I find it amusing that the trojan is using the Windows 7 logo even though the Alex has indicated that it is an XP system. *sigh*)
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
So, after spending several days fighting this thing, I finally got rid of it. I'm pretty sure I got the right one, but along the way I found some suspicious items that could have contributed. Here's the steps it took to clean it up. First thing I did was to check all of the autostart locations on windows. I followed this article [here](http://www.bleepingcomputer.com/tutorials/tutorial44.html). Most of the locations where clean except for: 1. `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit` * This key had a second path on it pointing to `C:\Documents and Settings\NetworkService\Application Data\09A52917-B4FC-4f02-AE3B-BF55D9351F4A\msvcs.exe` 2. `HKLM\Software\Microsoft\Windows\CurrentVersion\Run` * This node had a `REG_SZ` key named `2C508BD5-F9C6-4955-B93A-09B835EC3C64` which was pointing to the msvcs.exe file in the `Userinit` key. 3. `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify` * This node had two other nodes that looked suspicious to me. They were named `\toldvw32` and `torlfsvses`. Both nodes had keys that pointed to a `toldvw32.dll` file and were set with a `WlStartupEvent` event. Looking these up on Google didn't produce any meaningful results at the time, so I went ahead an removed them. There doesn't seem to be problems with having done that yet. The real issue is that `msvcs.exe` file. If one manages to survive it will replicate it self across all user profiles on the machine. Since it was hooked up into the `NetworkService` profile it would always make sure it existed in the other profiles. There's three locations where `msvcs.exe` exists. They are: 1. `{PROFILE}/Application Data/09A52917-B4FC-4f02-AE3B-BF55D9351F4A` 2. `{PROFILE}/Start Menu/Programs/Startup` 3. `WINDOWS\Prefetch` * Not 100% sure on this one, but I did find two suspicious files: `MSVCS.EXE-0CA809BA.pf` and `MSVCS.EXE-301B4EC0.pf`. I went ahead and removed them without issues (so far at-least). I hope this helps someone in the future. It worked for me. If you have a computer that had/has this and it's hooked up to a domain make sure to check the user's profile folder on the server as well, there's a copy there too. Needless to say, ***don't*** login into that profile directly on the server because you're just going to have a very fun time after that... Also, you can't clean it through Safe Mode if the profile you're logging into has been infected. I used [UBCD4Win](http://www.ubcd4win.com/) to clean up what I saw, then I did the rest through Safe Mode. Now, I know the general consensus is to nuke the computer and start from scratch, but that is not always possible in a business environment. After I had it cleaned up and confirmed clean by several antivirus tools I ran `chkdsk /f /r` on the drive, defragmented it with [MyDefrag (4.3.1)](http://mydefrag.com/) and the computer works perfectly as if it never happened. So, nuking the computer is not always the best course of action as @Synetech pointed out him/her self. Lastly, Kaspersky was installed on the computer, but somehow was turned off and that's how the virus (malware?) got through and did what it did. I'm not a fan of antivirus software at all, in fact I don't have any on my 6 or so machines that I have, but in an environment where you have technically challenged personel, it is a good idea to have it and its also a very good idea to make sure it's actually turned *on* and updated. That is all fellow awesome people. I hope someone else can benefit from this answer in the future.
It seems to be the [BKA Trojan](http://www.google.com/search?q=bka%20trojan) (the first couple of results are links to the scareware’s site, so don’t use those). It seems that the [consensus](http://translate.google.com/translate?hl=en&sl=auto&tl=en&twu=1&u=http://www.computerbase.de/forum/showthread.php?t=940165) is to either reinstall, or use more anti-malware software. Re-installing should be a last resort; trying to remove it is better. The worst that can happen is that you end up re-installing anyway and “waste” some time learning some stuff. It may seem silly/obvious, but have you tried pressing Alt+F4 on the window? --- I can suggest trying a few more softwares to try (run them in safe-mode to for better results): * [SUPERAntiSpyware](http://www.superantispyware.com/) (use the portable version) * [Autoruns](http://technet.microsoft.com/en-us/sysinternals/bb963902) (to weed out where it is running from) * [HijackThis](http://free.antivirus.com/hijackthis/) (to analyze the system fairly throughly) * [WinSpy++](http://catch22.net/software/winspy) (to remove the topmost attribute from the window, though it may reset it every couple of seconds) * [ComboFix](http://www.bleepingcomputer.com/combofix/how-to-use-combofix) (scorched-Earth last resort) Another thing to try is to quickly look in the Task Manager’s Processes tab to try to figure out which process(es) the trojan is running from, and try to kill it (you don’t need to see it the Task Manager to kill it, you can type out the first several letters of the EXE name, and press `Del`, then `Space`), though make sure that the Task Manager’s Always-On-Top option is selected; just in case. --- (Side note: I find it amusing that the trojan is using the Windows 7 logo even though the Alex has indicated that it is an XP system. *sigh*)
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
It seems to be the [BKA Trojan](http://www.google.com/search?q=bka%20trojan) (the first couple of results are links to the scareware’s site, so don’t use those). It seems that the [consensus](http://translate.google.com/translate?hl=en&sl=auto&tl=en&twu=1&u=http://www.computerbase.de/forum/showthread.php?t=940165) is to either reinstall, or use more anti-malware software. Re-installing should be a last resort; trying to remove it is better. The worst that can happen is that you end up re-installing anyway and “waste” some time learning some stuff. It may seem silly/obvious, but have you tried pressing Alt+F4 on the window? --- I can suggest trying a few more softwares to try (run them in safe-mode to for better results): * [SUPERAntiSpyware](http://www.superantispyware.com/) (use the portable version) * [Autoruns](http://technet.microsoft.com/en-us/sysinternals/bb963902) (to weed out where it is running from) * [HijackThis](http://free.antivirus.com/hijackthis/) (to analyze the system fairly throughly) * [WinSpy++](http://catch22.net/software/winspy) (to remove the topmost attribute from the window, though it may reset it every couple of seconds) * [ComboFix](http://www.bleepingcomputer.com/combofix/how-to-use-combofix) (scorched-Earth last resort) Another thing to try is to quickly look in the Task Manager’s Processes tab to try to figure out which process(es) the trojan is running from, and try to kill it (you don’t need to see it the Task Manager to kill it, you can type out the first several letters of the EXE name, and press `Del`, then `Space`), though make sure that the Task Manager’s Always-On-Top option is selected; just in case. --- (Side note: I find it amusing that the trojan is using the Windows 7 logo even though the Alex has indicated that it is an XP system. *sigh*)
Most, but not all, malware can be **manually** removed with [autoruns](http://technet.microsoft.com/en-us/sysinternals/bb963902). Try the following procedure: * download autoruns from the above link and run it straight from the zip archive * let it scan (if it can) * look for two types of entries - ones with **no signature** and more importantly entries which say '**file not found**'. The second kind is typical for viruses that insert themselves into various parts of the system that get executed during start time (but upon startup they temporarily remove the infected file and make it accessible only on the next restart). By unticking the problematic/suspicious entries you can cripple the malware to the point that it will not be active in the system anymore (and if you untick something that is needed you can always tick it back on). Now, if you can not run autoruns that would be due to the virus already blocking it - however viruses will rarely do that. This procedure is surprisingly efficient, but of course this is only due to viruses not targeting it. You can always try it. After going through it you can use * [process explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653) to check if there are strange processes running on you system * [tcpview](http://technet.microsoft.com/en-us/sysinternals/bb897437) to audit and monitor your network activity Using these tools is not trivial (does require knowledge of the normal system behavior), but in case that * the regular anti-virus software does not recognize the threat yet neither will booting to linux and trying to clean with clamav * you really want to try to clean it and try to avoid re-format you can try to follow the procedure I gave.
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
As it's been said over and over again, the *only* sure-fire way to ensure that a virus is gone is to format your computer, and re-install things one by one. That said, this isn't technically a virus, but a new kind of malware that makes you pay to remove it, which you should not do under any circumstances, because you're contributing to organised crime.
How much time have you spent already trying to fix the PC? You may just find that booting with something like an Ubuntu live CD to copy all data to a removable USB hard drive, then formatting the disk and re-installing is actually the fastest way to solve this problem. I've seen it happen time and time again where so many more hours are spent trying to remove viruses or malware than what it takes to simply backup, format and re-install. I know you don't want to do this, you would rather use a tool to fix the problem, but I think you'll save time by doing a clean install and you'll also know that the malware is really gone. You computer will probably run faster as well as this is usually the case on a fresh install.
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
This seems to be a brand new scareware. As far as I see, it has not been described by the antivirus specialists yet. It threatens to delete the contents of the disk and sue you for using an illegal copy of Windows. I propose you turn off the infected computer, remove the disk and copy the contents of the disk to some safe spot. Then you can also retry a virusscan while attached to a different computer (not booting this infected disk). Personally, I would backup the data and go for a fresh install. Once a malware was on a windows, there is no way to make sure all traces have been removed, because once they have a hold of your computer they will continue to try and use it / your data / your bank account. In cases like this, it seems to be usual to load more malware onto the computer. Users of this computer should change their passwords, if banking has been done, check their bank accounts and set a new PIN. Oh, and dont pay. If you do, it might ask for admin permissions to "fix" your windows, and then rootkit you for good.
Most, but not all, malware can be **manually** removed with [autoruns](http://technet.microsoft.com/en-us/sysinternals/bb963902). Try the following procedure: * download autoruns from the above link and run it straight from the zip archive * let it scan (if it can) * look for two types of entries - ones with **no signature** and more importantly entries which say '**file not found**'. The second kind is typical for viruses that insert themselves into various parts of the system that get executed during start time (but upon startup they temporarily remove the infected file and make it accessible only on the next restart). By unticking the problematic/suspicious entries you can cripple the malware to the point that it will not be active in the system anymore (and if you untick something that is needed you can always tick it back on). Now, if you can not run autoruns that would be due to the virus already blocking it - however viruses will rarely do that. This procedure is surprisingly efficient, but of course this is only due to viruses not targeting it. You can always try it. After going through it you can use * [process explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653) to check if there are strange processes running on you system * [tcpview](http://technet.microsoft.com/en-us/sysinternals/bb897437) to audit and monitor your network activity Using these tools is not trivial (does require knowledge of the normal system behavior), but in case that * the regular anti-virus software does not recognize the threat yet neither will booting to linux and trying to clean with clamav * you really want to try to clean it and try to avoid re-format you can try to follow the procedure I gave.
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
How much time have you spent already trying to fix the PC? You may just find that booting with something like an Ubuntu live CD to copy all data to a removable USB hard drive, then formatting the disk and re-installing is actually the fastest way to solve this problem. I've seen it happen time and time again where so many more hours are spent trying to remove viruses or malware than what it takes to simply backup, format and re-install. I know you don't want to do this, you would rather use a tool to fix the problem, but I think you'll save time by doing a clean install and you'll also know that the malware is really gone. You computer will probably run faster as well as this is usually the case on a fresh install.
This seems to be a brand new scareware. As far as I see, it has not been described by the antivirus specialists yet. It threatens to delete the contents of the disk and sue you for using an illegal copy of Windows. I propose you turn off the infected computer, remove the disk and copy the contents of the disk to some safe spot. Then you can also retry a virusscan while attached to a different computer (not booting this infected disk). Personally, I would backup the data and go for a fresh install. Once a malware was on a windows, there is no way to make sure all traces have been removed, because once they have a hold of your computer they will continue to try and use it / your data / your bank account. In cases like this, it seems to be usual to load more malware onto the computer. Users of this computer should change their passwords, if banking has been done, check their bank accounts and set a new PIN. Oh, and dont pay. If you do, it might ask for admin permissions to "fix" your windows, and then rootkit you for good.
326,253
**UPDATE** I've posted my solution below. --- This thing popped up on the computer of one of my employees on Friday. I've spent most of the weekend scanning the computer with Avira AntiVir, Avira Boot Sector Repair Tool, Kaspersky Virus Removal Tool, Malwarebytes, Spybot, McAfee Stinger, and something else I forgot and all of them found something. Overall they all cleaned about 400 malicious items, except for this one. This screen shows up right after the computer boots up and the user logs in. There's a slight lag while the OS is loading the profile and after that this pops up. I think it's something along the lines of a browser hack because I saw Firefox (3.6.18 I think) start up right before it appeared. I can do CTRL+ALT+DEL and bring up Task Manager, but as soon as I do the virus screen overlays it. What is this virus and how can I get rid of it? ![enter image description here](https://i.stack.imgur.com/NRBDG.jpg)
2011/08/22
[ "https://superuser.com/questions/326253", "https://superuser.com", "https://superuser.com/users/31673/" ]
So, after spending several days fighting this thing, I finally got rid of it. I'm pretty sure I got the right one, but along the way I found some suspicious items that could have contributed. Here's the steps it took to clean it up. First thing I did was to check all of the autostart locations on windows. I followed this article [here](http://www.bleepingcomputer.com/tutorials/tutorial44.html). Most of the locations where clean except for: 1. `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit` * This key had a second path on it pointing to `C:\Documents and Settings\NetworkService\Application Data\09A52917-B4FC-4f02-AE3B-BF55D9351F4A\msvcs.exe` 2. `HKLM\Software\Microsoft\Windows\CurrentVersion\Run` * This node had a `REG_SZ` key named `2C508BD5-F9C6-4955-B93A-09B835EC3C64` which was pointing to the msvcs.exe file in the `Userinit` key. 3. `HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify` * This node had two other nodes that looked suspicious to me. They were named `\toldvw32` and `torlfsvses`. Both nodes had keys that pointed to a `toldvw32.dll` file and were set with a `WlStartupEvent` event. Looking these up on Google didn't produce any meaningful results at the time, so I went ahead an removed them. There doesn't seem to be problems with having done that yet. The real issue is that `msvcs.exe` file. If one manages to survive it will replicate it self across all user profiles on the machine. Since it was hooked up into the `NetworkService` profile it would always make sure it existed in the other profiles. There's three locations where `msvcs.exe` exists. They are: 1. `{PROFILE}/Application Data/09A52917-B4FC-4f02-AE3B-BF55D9351F4A` 2. `{PROFILE}/Start Menu/Programs/Startup` 3. `WINDOWS\Prefetch` * Not 100% sure on this one, but I did find two suspicious files: `MSVCS.EXE-0CA809BA.pf` and `MSVCS.EXE-301B4EC0.pf`. I went ahead and removed them without issues (so far at-least). I hope this helps someone in the future. It worked for me. If you have a computer that had/has this and it's hooked up to a domain make sure to check the user's profile folder on the server as well, there's a copy there too. Needless to say, ***don't*** login into that profile directly on the server because you're just going to have a very fun time after that... Also, you can't clean it through Safe Mode if the profile you're logging into has been infected. I used [UBCD4Win](http://www.ubcd4win.com/) to clean up what I saw, then I did the rest through Safe Mode. Now, I know the general consensus is to nuke the computer and start from scratch, but that is not always possible in a business environment. After I had it cleaned up and confirmed clean by several antivirus tools I ran `chkdsk /f /r` on the drive, defragmented it with [MyDefrag (4.3.1)](http://mydefrag.com/) and the computer works perfectly as if it never happened. So, nuking the computer is not always the best course of action as @Synetech pointed out him/her self. Lastly, Kaspersky was installed on the computer, but somehow was turned off and that's how the virus (malware?) got through and did what it did. I'm not a fan of antivirus software at all, in fact I don't have any on my 6 or so machines that I have, but in an environment where you have technically challenged personel, it is a good idea to have it and its also a very good idea to make sure it's actually turned *on* and updated. That is all fellow awesome people. I hope someone else can benefit from this answer in the future.
How much time have you spent already trying to fix the PC? You may just find that booting with something like an Ubuntu live CD to copy all data to a removable USB hard drive, then formatting the disk and re-installing is actually the fastest way to solve this problem. I've seen it happen time and time again where so many more hours are spent trying to remove viruses or malware than what it takes to simply backup, format and re-install. I know you don't want to do this, you would rather use a tool to fix the problem, but I think you'll save time by doing a clean install and you'll also know that the malware is really gone. You computer will probably run faster as well as this is usually the case on a fresh install.
34,367,700
This is my HTML code. ``` <img src="images/maxicon.png" class="iconimg" width="100%" alt=""> <a href="#"><img src="images/link.png" class="linkimg" alt=""></a> ``` This is the CSS: ``` .linkimg { display: none; } .iconimg:hover .linkimg { display: block; } ``` I have tried several solutions available on stackoverflow, but it just wouldn't work. I tried the ~ and + approach as well. I am not sure why it doesn't work. What I want to do is, when I hover over .iconimg, I want .linkimg to show up. Initially .linkimg is hidden.
2015/12/19
[ "https://Stackoverflow.com/questions/34367700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4246306/" ]
I think you can use only Ninja Forms without extensions, and hook directly in 'ninja\_forms\_after\_submission' that fires after submission and allow you to use data submitted and perform actions. This is a starter codebase to achieve your result, but needs to be customized on your needs and your form structure. ``` add_action( 'ninja_forms_after_submission', 'create_page_from_ninjaform' ); function create_page_from_ninjaform( $form_data ){ // your fields data $form_fields = $form_data[ 'fields' ]; // !!! this is an example, it depends form fields in your form $title = $form_fields[ 1 ][ 'value' ]; $content = $form_fields[ 2 ][ 'value' ]; $sample_meta_field = $form_fields[ 3 ][ 'value' ]; $new_post = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'publish', 'post_type' => 'listing', // be sure this is the post type name ); $new_post_id = wp_insert_post( $new_post ); update_post_meta( $new_post_id, 'your_meta_key', $sample_meta_field ); } ``` This code should be copied in functions.php file Not tested of course. Good luck ;)
The Ninja Forms Front-end Posting extension isn't really meant for displaying form submission data on the front end. From: <https://ninjaforms.com/extensions/front-end-posting/> "The Ninja Forms Front-end Posting extension gives you the power of the WordPress post editor on any publicly viewable page you choose." If you want to show Ninja Forms submission data on the front end, you will have to retrieve them from the database with code in functions.php or by writing a plugin (recommended). You could then parse and manipulate them and create a shortcode that would allow you to insert your formatted submission data easily in Wordpress posts or pages. Here's a link to a feature request, asking for the same thing. The author of that request posted a link to a plugin (click Download as Plugin) they wrote which may do what you want or give you further insights as to how you could implement this. <https://github.com/wpninjas/ninja-forms/issues/892>
34,367,700
This is my HTML code. ``` <img src="images/maxicon.png" class="iconimg" width="100%" alt=""> <a href="#"><img src="images/link.png" class="linkimg" alt=""></a> ``` This is the CSS: ``` .linkimg { display: none; } .iconimg:hover .linkimg { display: block; } ``` I have tried several solutions available on stackoverflow, but it just wouldn't work. I tried the ~ and + approach as well. I am not sure why it doesn't work. What I want to do is, when I hover over .iconimg, I want .linkimg to show up. Initially .linkimg is hidden.
2015/12/19
[ "https://Stackoverflow.com/questions/34367700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4246306/" ]
I think you can use only Ninja Forms without extensions, and hook directly in 'ninja\_forms\_after\_submission' that fires after submission and allow you to use data submitted and perform actions. This is a starter codebase to achieve your result, but needs to be customized on your needs and your form structure. ``` add_action( 'ninja_forms_after_submission', 'create_page_from_ninjaform' ); function create_page_from_ninjaform( $form_data ){ // your fields data $form_fields = $form_data[ 'fields' ]; // !!! this is an example, it depends form fields in your form $title = $form_fields[ 1 ][ 'value' ]; $content = $form_fields[ 2 ][ 'value' ]; $sample_meta_field = $form_fields[ 3 ][ 'value' ]; $new_post = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'publish', 'post_type' => 'listing', // be sure this is the post type name ); $new_post_id = wp_insert_post( $new_post ); update_post_meta( $new_post_id, 'your_meta_key', $sample_meta_field ); } ``` This code should be copied in functions.php file Not tested of course. Good luck ;)
If you do not mind paying a little money for a plugin I would recommend using gravity forms rather then ninja forms for more advanced stuff like this. I manually create a custom post type "oproep" and used a gravityforms plugin to create a custom post from type oproep when an user submits the form. Because you use custom post type archive pages www.mysite.com/oproep will be automatically created so you already have a list of "Listings". The singe pages www.mysite.com/oproep/title will also be created for you by default, you could override these templates as well if you would like depending on your theme. The only thing you have to do is add a few php lines to your functions.php (or write your own plugin) that adds the custom post type. The rest all works automatically. I went so far as writing code to make users able to edit their submissions, read custom taxonomy tags in dropdowns etc. You got lots and lots of more options using gravity forms.
34,367,700
This is my HTML code. ``` <img src="images/maxicon.png" class="iconimg" width="100%" alt=""> <a href="#"><img src="images/link.png" class="linkimg" alt=""></a> ``` This is the CSS: ``` .linkimg { display: none; } .iconimg:hover .linkimg { display: block; } ``` I have tried several solutions available on stackoverflow, but it just wouldn't work. I tried the ~ and + approach as well. I am not sure why it doesn't work. What I want to do is, when I hover over .iconimg, I want .linkimg to show up. Initially .linkimg is hidden.
2015/12/19
[ "https://Stackoverflow.com/questions/34367700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4246306/" ]
I think you can use only Ninja Forms without extensions, and hook directly in 'ninja\_forms\_after\_submission' that fires after submission and allow you to use data submitted and perform actions. This is a starter codebase to achieve your result, but needs to be customized on your needs and your form structure. ``` add_action( 'ninja_forms_after_submission', 'create_page_from_ninjaform' ); function create_page_from_ninjaform( $form_data ){ // your fields data $form_fields = $form_data[ 'fields' ]; // !!! this is an example, it depends form fields in your form $title = $form_fields[ 1 ][ 'value' ]; $content = $form_fields[ 2 ][ 'value' ]; $sample_meta_field = $form_fields[ 3 ][ 'value' ]; $new_post = array( 'post_title' => $title, 'post_content' => $content, 'post_status' => 'publish', 'post_type' => 'listing', // be sure this is the post type name ); $new_post_id = wp_insert_post( $new_post ); update_post_meta( $new_post_id, 'your_meta_key', $sample_meta_field ); } ``` This code should be copied in functions.php file Not tested of course. Good luck ;)
FrancescoCarlucci's answer is correct, but just adding an additional comment: in case you want to specify by form field IDs which fields should go where in your post, NinjaForms passes the ID as a number (in my case for example, I needed field 136 for my post title). It may have been obvious but I racked my brain for a while until I figured it out. ``` function create_post($form_data) { $form_fields = $form_data[ 'fields' ]; $post_fields = array( 'post_content' => '', 'post_content_filtered' => '', 'post_title' => '', 'post_excerpt' => '', 'post_status' => 'pending', 'post_type' => 'post', ); foreach ($form_fields as $field) { $field_id = $field[ 'id' ]; $field_key = $field[ 'key' ]; $field_value = $field[ 'value' ]; if ($field_id == 136) { $post_fields['post_title'] = $field_value; } } wp_insert_post($post_fields, true); } ```
298,907
I'm new to Magento(2) and I'm trying to display Stock Status, stock count, and quantity field in category view like in product view. I don't know where to get theses values and where to put it... I'm using magento 2.2.10 and I'm using the default luma theme I found that if i comment some containers in `catalog_product_view.xml` at rootFolder/vendor/magento/module-catalog/view/frontend/layout, it disable it from the product page, so i suppose that i need to copy this code to some other file but i can't figure it out... Thanks in advance for your help guys Where I want to add information: [![My category view here, where i want to add some informations](https://i.stack.imgur.com/LSu0o.jpg)](https://i.stack.imgur.com/LSu0o.jpg) Where I want to copy values into category view: [![My Product View, where I want to copy values into category view](https://i.stack.imgur.com/OjpIL.jpg)](https://i.stack.imgur.com/OjpIL.jpg)
2019/12/16
[ "https://magento.stackexchange.com/questions/298907", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/84912/" ]
I have seen this error when the install does not have enough memory. Check your hosting settings. `memory_limit` should be 768 mb +
**Solutions** You have to delete an order grid entry from the `ui_bookmark` table. In a `ui_bookmark` table, delete the row where you want to reset the filter. or if you don't know which entry of order then you can truncate this table.
54,187,408
I have a list of combinations of companies, cities, and states in excel, each a string. I would like to split the string of words based on a given word (the city name) and the result to be two columns, one with with company name, one with the city and state. Splitting on space or symbol delimiters doesn't work because the companies don't all have one word names, and similar for cities. I have thousands of records and would like to loop this as well. I've tried the SPLIT() function in VBA but not sure how to loop it. ``` Initial Splitting word Result 1 Result 2 Clean Choc Detroit MI Detroit Clean Choc Detroit MI Space Kites Des Moines IA Des Moines Space Kites Des Moines IA Tattoosie Chicago IL Chicago Tattoosie Chicago IL One for Two New York City NYNew York City One for Two New York City NY Limonistas Carlsbad CA Carlsbad Limonistas Carlsbad CA ```
2019/01/14
[ "https://Stackoverflow.com/questions/54187408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6460510/" ]
If you want to avoid VBA, the following formulas could work for you: ``` =LEFT(A2,FIND(B2,A2)-2) =RIGHT(A2,LEN(A2)-FIND(B2,A2)+1) ```
You can use this as two functions (one returns the left part, other returns the right part): ``` Function split1(str As String, dlmtr As String) As String Dim pt1() As String pt1 = Split(str, dlmtr) split1 = pt1(0) End Function Function split2(str As String, dlmtr As String) As String Dim pt2() As String pt2 = Split(str, dlmtr) split2 = dlmtr & " " & pt2(1) End Function ``` Note that the Delimiter expected is *case sensitive* [![enter image description here](https://i.stack.imgur.com/ZjVDw.jpg)](https://i.stack.imgur.com/ZjVDw.jpg) Or as a Subroutine (tweak as necessary): ``` Sub split_strings() Dim rng As Range Dim dmltr As String: dmltr = "Detroit" Set rng = Range("A1") Dim splt() As String splt = Split(rng.Value, dmltr) rng.Offset(0, 1).Value = splt(0) rng.Offset(0, 2).Value = dmltr & " " & splt(1) End Sub ```
47,914,409
Is it possible to form a query where table1.first\_name + " " + table1.last\_name matches table2.customer\_name? IE: customers.first\_name = "John" customers.last\_name = "Doe" orders.customer\_name = "John Doe" It seems to me this would be a common query, but just can't come up with the syntax intuitively. Also, I am led to believe that this would not be a 'best practice' solution (using id fields would be better), but if I can't control the schema, I just want to know if something like my approach is even possible.
2017/12/20
[ "https://Stackoverflow.com/questions/47914409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8621188/" ]
You are looking for `concat` ``` where concat(customers.first_name,' ',customers.last_name) = orders.customer_name ```
You can concatenate the values and compare the result as so: ``` (customers.first_name || ' ' || customers.last_name) = orders.customer_name ``` Brackets only for readability
48,271,741
This appears to only happen when I'm using the `generic/arch` box. I've tried several ubuntu boxes and everything works fine. Host OS is Manjaro. It's freezing with output: ``` INFO interface: info: ==> default: Waiting for domain to get an IP address... ==> default: Waiting for domain to get an IP address... INFO retryable: Retryable exception raised: #<Fog::Errors::TimeoutError: The specified wait_for timeout (2 seconds) was exceeded> ``` libvirt/virsh version 3.10.0 vagrant version 2.0.1 OS `4.9.76-1-MANJARO` Vagrantfile: ``` Vagrant.configure("2") do |config| config.vm.box = "generic/arch" end ``` Below is what I think the relevant output is from `VAGRANT_LOG=debug vagrant up` ``` ==> default: Creating shared folders metadata... INFO warden: Calling IN action: #<VagrantPlugins::ProviderLibvirt::Action::CreateNetworks:0x0000560dfaea3450> INFO create_networks: Using vagrant-libvirt at 192.168.121.0/24 as the management network nat is the mode DEBUG create_networks: In config found network type forwarded_port options {:guest=>22, :host=>2222, :host_ip=>"127.0.0.1", :id=>"ssh", :auto_correct=>true, :p rotocol=>"tcp"} DEBUG create_networks: Searching for network with options {:iface_type=>:private_network, :network_name=>"vagrant-libvirt", :ip=>"192.168.121.0", :netmask=>"25 5.255.255.0", :dhcp_enabled=>true, :forward_mode=>"nat", :guest_ipv6=>"yes", :autostart=>false} /home/eihli/.vagrant.d/gems/2.4.3/gems/nokogiri-1.6.8.1/lib/nokogiri/xml/document.rb:44: warning: constant ::Fixnum is deprecated DEBUG create_networks: looking up network with ip == 192.168.121.0 DEBUG create_networks: Checking that network name does not clash with ip DEBUG create_networks: looking up network named vagrant-libvirt DEBUG create_networks: generating name for bridge DEBUG create_networks: looking up bridge named virbr0 DEBUG create_networks: looking up bridge named virbr1 DEBUG create_networks: found available bridge name virbr1 DEBUG create_networks: created network INFO create_networks: Saving information about created network vagrant-libvirt, UUID=71c9f6dd-4b2d-48f2-a787-5a0439d2e587 to file /home/eihli/code/vagrant_te$ t/.vagrant/machines/default/libvirt/created_networks. INFO warden: Calling IN action: #<VagrantPlugins::ProviderLibvirt::Action::CreateNetworkInterfaces:0x0000560dfb42cae8> INFO create_network_interfaces: Using vagrant-libvirt at 192.168.121.0/24 as the management network nat is the mode DEBUG create_network_interfaces: In config found network type forwarded_port options {:guest=>22, :host=>2222, :host_ip=>"127.0.0.1", :id=>"ssh", :auto_correc$ =>true, :protocol=>"tcp"} DEBUG create_network_interfaces: Adapter not specified so found slot 0 DEBUG create_network_interfaces: Found network by name INFO create_network_interfaces: Creating network interface eth0 connected to network vagrant-libvirt. INFO warden: Calling IN action: #<VagrantPlugins::ProviderLibvirt::Action::SetBootOrder:0x0000560dfb30af70> INFO warden: Calling IN action: #<VagrantPlugins::ProviderLibvirt::Action::StartDomain:0x0000560dfafc46e0> INFO interface: info: Starting domain. INFO interface: info: ==> default: Starting domain. ==> default: Starting domain. INFO warden: Calling IN action: #<VagrantPlugins::ProviderLibvirt::Action::WaitTillUp:0x0000560dfab82de8> DEBUG wait_till_up: Searching for IP for MAC address: 52:54:00:62:61:1d INFO interface: info: Waiting for domain to get an IP address... INFO interface: info: ==> default: Waiting for domain to get an IP address... ==> default: Waiting for domain to get an IP address... ``` I checked wireshark using `tshark -i virbr1` and I don't get any output. I wasn't sure which device I should be listening to though, so I also checked on `tshark -i vnet0` and I did get some output but nothing that looked DHCP related. Below is the output of `tshark -i vnet0` ``` Capturing on 'vnet0' 1 0.000000000 fe80::fc54:ff:fe45:368d → ff02::fb MDNS 201 Standard query response 0x0000 PTR, cache flush Ophelia.local AAAA, cache flush fe80::fc54:ff:fe45:368d 2 0.745989853 fe:54:00:45:36:8d → Spanning-tree-(for-bridges)_00 STP 52 Conf. TC + Root = 32768/0/52:54:00:78:b4:d1 Cost = 0 Port = 0x8002 3 1.599338528 fe80::fc54:ff:fe45:368d → ff02::2 ICMPv6 70 Router Solicitation from fe:54:00:45:36:8d 4 2.190388300 fe80::fc54:ff:fe45:368d → ff02::fb MDNS 201 Standard query response 0x0000 PTR, cache flush Ophelia.local AAAA, cache flush fe80::fc54:ff:fe45:368d 5 2.666024617 fe:54:00:45:36:8d → Spanning-tree-(for-bridges)_00 STP 52 Conf. TC + Root = 32768/0/52:54:00:78:b4:d1 Cost = 0 Port = 0x8002 6 4.799357852 fe:54:00:45:36:8d → Spanning-tree-(for-bridges)_00 STP 52 Conf. TC + Root = 32768/0/52:54:00:78:b4:d1 Cost = 0 Port = 0x8002 ``` Below is the result of `dmesg -w` from the time when I `vagrant up` to the time I `ctrl-c` ``` [ 2048.355424] virbr1: port 2(vnet0) entered disabled state [ 2048.358280] device vnet0 left promiscuous mode [ 2048.358287] virbr1: port 2(vnet0) entered disabled state [ 2048.578278] device virbr1-nic left promiscuous mode [ 2048.578287] virbr1: port 1(virbr1-nic) entered disabled state [ 2059.394512] virbr1: port 1(virbr1-nic) entered blocking state [ 2059.394516] virbr1: port 1(virbr1-nic) entered disabled state [ 2059.394598] device virbr1-nic entered promiscuous mode [ 2059.532014] virbr1: port 1(virbr1-nic) entered blocking state [ 2059.532017] virbr1: port 1(virbr1-nic) entered listening state [ 2059.567010] virbr1: port 1(virbr1-nic) entered disabled state [ 2059.694140] virbr1: port 2(vnet0) entered blocking state [ 2059.694156] virbr1: port 2(vnet0) entered disabled state [ 2059.694377] device vnet0 entered promiscuous mode [ 2059.695080] virbr1: port 2(vnet0) entered blocking state [ 2059.695083] virbr1: port 2(vnet0) entered listening state [ 2061.871278] virbr1: port 2(vnet0) entered learning state [ 2064.004553] virbr1: port 2(vnet0) entered forwarding state [ 2064.004555] virbr1: topology change detected, propagating [ 2065.750798] kvm [5143]: vcpu0, guest rIP: 0xffffffff86061ce6 unhandled rdmsr: 0x140 [ 2065.821598] kvm [5143]: vcpu1, guest rIP: 0xffffffff86061ce6 unhandled rdmsr: 0x140 [ 2065.861278] kvm: zapping shadow pages for mmio generation wraparound [ 2065.863039] kvm: zapping shadow pages for mmio generation wraparound [ 2066.017675] kvm [5143]: vcpu0, guest rIP: 0xffffffff86061ce6 unhandled rdmsr: 0x34 [ 2068.941350] virbr1: port 2(vnet0) entered disabled state [ 2068.943507] device vnet0 left promiscuous mode [ 2068.943511] virbr1: port 2(vnet0) entered disabled state [ 2069.163524] device virbr1-nic left promiscuous mode [ 2069.163532] virbr1: port 1(virbr1-nic) entered disabled state ``` Below is the output of `ip addr show` (with the exception that this is the umpteenth time I've run vagrant up and each time the number of the virtual network interface goes up. ``` 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: wlp3s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000 link/ether 3c:a9:f4:4c:7b:3c brd ff:ff:ff:ff:ff:ff inet 10.7.74.120/18 brd 10.7.127.255 scope global dynamic noprefixroute wlp3s0 valid_lft 599674sec preferred_lft 599674sec inet6 fe80::3d00:e921:d2e6:d9d5/64 scope link noprefixroute valid_lft forever preferred_lft forever 3: enp0s25: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc fq_codel state DOWN group default qlen 1000 link/ether 28:d2:44:17:62:46 brd ff:ff:ff:ff:ff:ff 34: virbr1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000 link/ether 52:54:00:ff:e1:a6 brd ff:ff:ff:ff:ff:ff inet 192.168.121.1/24 brd 192.168.121.255 scope global virbr1 valid_lft forever preferred_lft forever 35: virbr1-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr1 state DOWN group default qlen 1000 link/ether 52:54:00:ff:e1:a6 brd ff:ff:ff:ff:ff:ff 36: vnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel master virbr1 state UNKNOWN group default qlen 1000 link/ether fe:54:00:81:4a:63 brd ff:ff:ff:ff:ff:ff inet6 fe80::fc54:ff:fe81:4a63/64 scope link valid_lft forever preferred_lft forever ```
2018/01/15
[ "https://Stackoverflow.com/questions/48271741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3937773/" ]
Since you are using the libvirt provider, you should be able to check out the state of the virtual machine with `virt-manager`. The rest of the answer is written under the two assumptions that my system is not so different from yours and that I have run into the same problem using vagrant-libvirt and generic/arch (v1.3.40) Opening the VM in virt-manager, I've found out that the system cannot detect the root filesystem and also boots into an emergency shell. That's because the `initramfs-linux.img` provided by the *generic/arch* box does not include the necessary kernel modules for the default settings that the libvirt-provider with QEMU/kvm uses. If it's somehow important to boot this box, you should be able to start the box by using the fallback image because it ships more modules. To make it rebootable without intervention, you can run `sudo mkinitcpio -p linux` to add the missing modules in the guest. Alternatively, you could also change the SCSI controller from *Hypervisor Defaults* to *VirtIO SCSI* (eg. with virt-manager) on the host. For a more permanent solution (nothing of the aforementioned would survive a `vagrant destroy`), there ist not much to be done - besides maybe waiting for a "fixed" release of the box or [patching](https://github.com/vagrant-libvirt/vagrant-libvirt/issues/633) the plugin. ps. The easiest solution would probably be to pick another box (e.g. [archlinux/archlinux](https://app.vagrantup.com/archlinux/boxes/archlinux/)).
In my case, I had overly restrictive `iptables` rules preventing the NAT which is set up for the virtual network bridge(s) `virbr*` by Vagrant via libvirt. As an experiment, I disabled all firewall rules before starting the Vagrant machine and it was able to get an IP address.
6,214,722
I have some videos and I want to test their with automation. Could you tell, how does `selenium-webdriver` work with video? How does it recognize it?
2011/06/02
[ "https://Stackoverflow.com/questions/6214722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449397/" ]
You can reshape or delete the cells themselves using ()-addressing. ``` model(:,2) = []; ```
You have to transpose the two pieces, and change some parentheses: ``` temp= [{ model{:,1:i-1}}' {model{:,i+1:size(model,2)}}'] ```
6,214,722
I have some videos and I want to test their with automation. Could you tell, how does `selenium-webdriver` work with video? How does it recognize it?
2011/06/02
[ "https://Stackoverflow.com/questions/6214722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/449397/" ]
You can reshape or delete the cells themselves using ()-addressing. ``` model(:,2) = []; ```
there is a function called fun\_removecellrowcols, which removes specific row/columns indicated by the user. This affects the dimensions of the cell, due to the row/cols removal. <http://www.mathworks.com/matlabcentral/fileexchange/46196-fun-removecellrowcols> Regards, José
129,542
I've spent a good part of the day searching, writing and finally scrapping a script that I can use with my Inno Setup install script that will download and install the appropriate .NET 2.0 Framework if needed. There are definitely a number of examples out there, but they: 1. Want to install Internet Explorer if needed which I wouldn't dare to in an automated way 2. Only handle x86 .NET distributions, no x64 and IA64 support 3. Don't install the appropriate language pack when needed -- a tough problem (when I saw there were different language packs for different x86/x64/language combos I threw in the towel) 4. Don't handle getting the .NET 2.0 SP1 (maybe Windows Update will handle that once 2.0 is installed?) This seems like such a common problem that *someone* must have solved it. All I found though were 20 different posts all pointing to the same two or three code snippets. Insight welcomed :)
2008/09/24
[ "https://Stackoverflow.com/questions/129542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442/" ]
[.NET Framework 1.1/2.0/3.5 Installer for InnoSetup](http://www.codeproject.com/KB/install/dotnetfx_innosetup_instal.aspx)
I have recently been looking into this issue but without the same requirements that you have. I haven't seen a script that does what you want but have you considered instead checking if .NET 2.0 is installed and if not then prompt them to download it. You can open a URL in the default browser and get the user to attempt the install again once the framework has been installed. This is not an ideal situation from a user perspective but i think going with what your planning you will have to write some complex stuff to handle the different language constraints just to get it working. Just my 2 cents.
5,237,005
Say I have a table `customers` with the following fields and records: ``` id first_name last_name email phone ------------------------------------------------------------------------ 1 Michael Turley [email protected] 555-123-4567 2 John Dohe [email protected] 3 Jack Smith [email protected] 555-555-5555 4 Johnathan Doe 123-456-7890 ``` There are several other tables, such as `orders`, `rewards`, `receipts` which have foreign keys `customer_id` relating to this table's `customers.id`. As you can see, in their infinite wisdom, my users have created duplicate records for John Doe, complete with inconsistent spelling and missing data. An administrator notices this, selects customers 2 and 4, and clicks "Merge". They are then prompted to select which value is correct for each field, etc etc and my PHP determines that the merged record should look like this: ``` id first_name last_name email phone ------------------------------------------------------------------------ ? John Doe [email protected] 123-456-7890 ``` Let's assume Mr. Doe has placed several orders, earned rewards, generated receipts.. but some of these have been associated with id 2, and some have been associated with id 4. The merged row needs to match all of the foreign keys in other tables that matched the original rows. Here's where I'm not sure what to do. My instinct is to do this: ``` DELETE FROM customers WHERE id = 4; UPDATE customers SET first_name = 'John', last_name = 'Doe', email = '[email protected]', phone = '123-456-7890' WHERE id = 2; UPDATE orders, rewards, receipts SET customer_id = 2 WHERE customer_id = 4; ``` I think that would work, but if later on I add another table that has a customer\_id foreign key, I have to remember to go back and add that table to the second UPDATE query in my merge function, or risk loss of integrity. There has to be a better way to do this.
2011/03/08
[ "https://Stackoverflow.com/questions/5237005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354065/" ]
The short answer is, no there isn't a better way (that I can think of). It's a trade off. If you find there are a lot of these instances, it might be worthwhile to invest some time writing a more robust algorithm for checking existing customers prior to adding a new one (i.e. checking variations on first / last names, presenting them to whoever is adding the customer, asking them 2 or 3 times if they are REALLY sure they want to add this new customer, etc.). If there are not a lot of these instances, it might not be worth investing that time. Short of that, your approach is the only way I can think of. I would actually delete both records, and create a new one with the merged data, resulting in a new customer id rather than re-using an old one, but that's just personal preference - functionally it's the same as your approach. You still have to remember to go back and modify your merge function to reflect new relationships on the customer.id field.
As an update to my comment: ``` use information_schema; select table_name from columns where column_name = 'customer_id'; ``` Then loop through the resulting tables and update accordingly. Personally, I would use your instinctive solution, as this one may be dangerous if there are tables containing customer\_id columns that need to be exempt.
5,237,005
Say I have a table `customers` with the following fields and records: ``` id first_name last_name email phone ------------------------------------------------------------------------ 1 Michael Turley [email protected] 555-123-4567 2 John Dohe [email protected] 3 Jack Smith [email protected] 555-555-5555 4 Johnathan Doe 123-456-7890 ``` There are several other tables, such as `orders`, `rewards`, `receipts` which have foreign keys `customer_id` relating to this table's `customers.id`. As you can see, in their infinite wisdom, my users have created duplicate records for John Doe, complete with inconsistent spelling and missing data. An administrator notices this, selects customers 2 and 4, and clicks "Merge". They are then prompted to select which value is correct for each field, etc etc and my PHP determines that the merged record should look like this: ``` id first_name last_name email phone ------------------------------------------------------------------------ ? John Doe [email protected] 123-456-7890 ``` Let's assume Mr. Doe has placed several orders, earned rewards, generated receipts.. but some of these have been associated with id 2, and some have been associated with id 4. The merged row needs to match all of the foreign keys in other tables that matched the original rows. Here's where I'm not sure what to do. My instinct is to do this: ``` DELETE FROM customers WHERE id = 4; UPDATE customers SET first_name = 'John', last_name = 'Doe', email = '[email protected]', phone = '123-456-7890' WHERE id = 2; UPDATE orders, rewards, receipts SET customer_id = 2 WHERE customer_id = 4; ``` I think that would work, but if later on I add another table that has a customer\_id foreign key, I have to remember to go back and add that table to the second UPDATE query in my merge function, or risk loss of integrity. There has to be a better way to do this.
2011/03/08
[ "https://Stackoverflow.com/questions/5237005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354065/" ]
I got here form google this is my 2 cents: ``` SELECT `TABLE_NAME` FROM `information_schema`.`KEY_COLUMN_USAGE` WHERE REFERENCED_TABLE_SCHEMA='DATABASE' AND REFERENCED_TABLE_NAME='customers' AND REFERENCED_COLUMN_NAME='customer_id' ``` add the db for insurance (you'll never know when somebody copies the db). Instead of looking for a column name, here we look at the foreign keys themselves If you change the on delete restrictions to restrict nothing can be deleted before the children are deleted/migrated
The short answer is, no there isn't a better way (that I can think of). It's a trade off. If you find there are a lot of these instances, it might be worthwhile to invest some time writing a more robust algorithm for checking existing customers prior to adding a new one (i.e. checking variations on first / last names, presenting them to whoever is adding the customer, asking them 2 or 3 times if they are REALLY sure they want to add this new customer, etc.). If there are not a lot of these instances, it might not be worth investing that time. Short of that, your approach is the only way I can think of. I would actually delete both records, and create a new one with the merged data, resulting in a new customer id rather than re-using an old one, but that's just personal preference - functionally it's the same as your approach. You still have to remember to go back and modify your merge function to reflect new relationships on the customer.id field.
5,237,005
Say I have a table `customers` with the following fields and records: ``` id first_name last_name email phone ------------------------------------------------------------------------ 1 Michael Turley [email protected] 555-123-4567 2 John Dohe [email protected] 3 Jack Smith [email protected] 555-555-5555 4 Johnathan Doe 123-456-7890 ``` There are several other tables, such as `orders`, `rewards`, `receipts` which have foreign keys `customer_id` relating to this table's `customers.id`. As you can see, in their infinite wisdom, my users have created duplicate records for John Doe, complete with inconsistent spelling and missing data. An administrator notices this, selects customers 2 and 4, and clicks "Merge". They are then prompted to select which value is correct for each field, etc etc and my PHP determines that the merged record should look like this: ``` id first_name last_name email phone ------------------------------------------------------------------------ ? John Doe [email protected] 123-456-7890 ``` Let's assume Mr. Doe has placed several orders, earned rewards, generated receipts.. but some of these have been associated with id 2, and some have been associated with id 4. The merged row needs to match all of the foreign keys in other tables that matched the original rows. Here's where I'm not sure what to do. My instinct is to do this: ``` DELETE FROM customers WHERE id = 4; UPDATE customers SET first_name = 'John', last_name = 'Doe', email = '[email protected]', phone = '123-456-7890' WHERE id = 2; UPDATE orders, rewards, receipts SET customer_id = 2 WHERE customer_id = 4; ``` I think that would work, but if later on I add another table that has a customer\_id foreign key, I have to remember to go back and add that table to the second UPDATE query in my merge function, or risk loss of integrity. There has to be a better way to do this.
2011/03/08
[ "https://Stackoverflow.com/questions/5237005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354065/" ]
At a minimum, to prevent any triggers on deletions causing some cascading effect, I would FIRST do update SomeTable set CustomerID = CorrectValue where CustomerID = WrongValue (do that across all tables)... THEN Delete from Customers where CustomerID = WrongValue As for duplicate data... Try to figure out which "Will Smith, Bill Smith, William Smith" if you are lacking certain information... Some could be completely legitimate different people.
As an update to my comment: ``` use information_schema; select table_name from columns where column_name = 'customer_id'; ``` Then loop through the resulting tables and update accordingly. Personally, I would use your instinctive solution, as this one may be dangerous if there are tables containing customer\_id columns that need to be exempt.
5,237,005
Say I have a table `customers` with the following fields and records: ``` id first_name last_name email phone ------------------------------------------------------------------------ 1 Michael Turley [email protected] 555-123-4567 2 John Dohe [email protected] 3 Jack Smith [email protected] 555-555-5555 4 Johnathan Doe 123-456-7890 ``` There are several other tables, such as `orders`, `rewards`, `receipts` which have foreign keys `customer_id` relating to this table's `customers.id`. As you can see, in their infinite wisdom, my users have created duplicate records for John Doe, complete with inconsistent spelling and missing data. An administrator notices this, selects customers 2 and 4, and clicks "Merge". They are then prompted to select which value is correct for each field, etc etc and my PHP determines that the merged record should look like this: ``` id first_name last_name email phone ------------------------------------------------------------------------ ? John Doe [email protected] 123-456-7890 ``` Let's assume Mr. Doe has placed several orders, earned rewards, generated receipts.. but some of these have been associated with id 2, and some have been associated with id 4. The merged row needs to match all of the foreign keys in other tables that matched the original rows. Here's where I'm not sure what to do. My instinct is to do this: ``` DELETE FROM customers WHERE id = 4; UPDATE customers SET first_name = 'John', last_name = 'Doe', email = '[email protected]', phone = '123-456-7890' WHERE id = 2; UPDATE orders, rewards, receipts SET customer_id = 2 WHERE customer_id = 4; ``` I think that would work, but if later on I add another table that has a customer\_id foreign key, I have to remember to go back and add that table to the second UPDATE query in my merge function, or risk loss of integrity. There has to be a better way to do this.
2011/03/08
[ "https://Stackoverflow.com/questions/5237005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354065/" ]
I got here form google this is my 2 cents: ``` SELECT `TABLE_NAME` FROM `information_schema`.`KEY_COLUMN_USAGE` WHERE REFERENCED_TABLE_SCHEMA='DATABASE' AND REFERENCED_TABLE_NAME='customers' AND REFERENCED_COLUMN_NAME='customer_id' ``` add the db for insurance (you'll never know when somebody copies the db). Instead of looking for a column name, here we look at the foreign keys themselves If you change the on delete restrictions to restrict nothing can be deleted before the children are deleted/migrated
At a minimum, to prevent any triggers on deletions causing some cascading effect, I would FIRST do update SomeTable set CustomerID = CorrectValue where CustomerID = WrongValue (do that across all tables)... THEN Delete from Customers where CustomerID = WrongValue As for duplicate data... Try to figure out which "Will Smith, Bill Smith, William Smith" if you are lacking certain information... Some could be completely legitimate different people.
5,237,005
Say I have a table `customers` with the following fields and records: ``` id first_name last_name email phone ------------------------------------------------------------------------ 1 Michael Turley [email protected] 555-123-4567 2 John Dohe [email protected] 3 Jack Smith [email protected] 555-555-5555 4 Johnathan Doe 123-456-7890 ``` There are several other tables, such as `orders`, `rewards`, `receipts` which have foreign keys `customer_id` relating to this table's `customers.id`. As you can see, in their infinite wisdom, my users have created duplicate records for John Doe, complete with inconsistent spelling and missing data. An administrator notices this, selects customers 2 and 4, and clicks "Merge". They are then prompted to select which value is correct for each field, etc etc and my PHP determines that the merged record should look like this: ``` id first_name last_name email phone ------------------------------------------------------------------------ ? John Doe [email protected] 123-456-7890 ``` Let's assume Mr. Doe has placed several orders, earned rewards, generated receipts.. but some of these have been associated with id 2, and some have been associated with id 4. The merged row needs to match all of the foreign keys in other tables that matched the original rows. Here's where I'm not sure what to do. My instinct is to do this: ``` DELETE FROM customers WHERE id = 4; UPDATE customers SET first_name = 'John', last_name = 'Doe', email = '[email protected]', phone = '123-456-7890' WHERE id = 2; UPDATE orders, rewards, receipts SET customer_id = 2 WHERE customer_id = 4; ``` I think that would work, but if later on I add another table that has a customer\_id foreign key, I have to remember to go back and add that table to the second UPDATE query in my merge function, or risk loss of integrity. There has to be a better way to do this.
2011/03/08
[ "https://Stackoverflow.com/questions/5237005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354065/" ]
I got here form google this is my 2 cents: ``` SELECT `TABLE_NAME` FROM `information_schema`.`KEY_COLUMN_USAGE` WHERE REFERENCED_TABLE_SCHEMA='DATABASE' AND REFERENCED_TABLE_NAME='customers' AND REFERENCED_COLUMN_NAME='customer_id' ``` add the db for insurance (you'll never know when somebody copies the db). Instead of looking for a column name, here we look at the foreign keys themselves If you change the on delete restrictions to restrict nothing can be deleted before the children are deleted/migrated
As an update to my comment: ``` use information_schema; select table_name from columns where column_name = 'customer_id'; ``` Then loop through the resulting tables and update accordingly. Personally, I would use your instinctive solution, as this one may be dangerous if there are tables containing customer\_id columns that need to be exempt.
30,458,408
I'm trying to post a new record in a table with `<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">`. But every row in my table has an unique id, and that id is put next to every `name`. So I'm trying to get the id with `$_GET` but it's been unsuccesful so far. Is the method I'm trying wrong or am I doing something else wrong? If anybody can tell me what's going wrong, I'd appreciatie. **PHP that gets placed above `<html>`** ``` <?php if (isset($_POST['saveRecord'])) { if (isset($_POST["newRecord"]) && !empty($_POST["newRecord"])) { $id = $_GET['record']; $klant=$_POST['newRecord'].$id; $query = "INSERT INTO table2 (recordid, recordname) VALUES (NULL, '$record')"; mysqli_query($con, $query); } } ?> ``` **Markup** ``` <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table> <?php $query = ("select * from table1"); $result = mysqli_query($con, $query) or die (mysqli_error()); while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ $id = $row['rowid']; ?> <tr> <td> <input class="newRecord<?php echo $id; ?>" type="text" name="newRecord<?php echo $id; ?>" /> <a href="?record=<?php echo $id; ?>"> <button class="saveRecord<?php echo $id; ?>" name="saveRecord<?php echo $id; ?>">Save</button> </a> </td> </tr> <?php } ?> </table> </form> ```
2015/05/26
[ "https://Stackoverflow.com/questions/30458408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3095385/" ]
Your button name is ``` name="saveRecord<?php echo $id; ?> ``` SO this condition need `$id` ``` if (isset($_POST['saveRecord'])) {// your id missing ```
move your opening and closing form tags in while loop,it will submit only 1 form at a time,otherwise all the inputs will be submitted.
30,458,408
I'm trying to post a new record in a table with `<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">`. But every row in my table has an unique id, and that id is put next to every `name`. So I'm trying to get the id with `$_GET` but it's been unsuccesful so far. Is the method I'm trying wrong or am I doing something else wrong? If anybody can tell me what's going wrong, I'd appreciatie. **PHP that gets placed above `<html>`** ``` <?php if (isset($_POST['saveRecord'])) { if (isset($_POST["newRecord"]) && !empty($_POST["newRecord"])) { $id = $_GET['record']; $klant=$_POST['newRecord'].$id; $query = "INSERT INTO table2 (recordid, recordname) VALUES (NULL, '$record')"; mysqli_query($con, $query); } } ?> ``` **Markup** ``` <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table> <?php $query = ("select * from table1"); $result = mysqli_query($con, $query) or die (mysqli_error()); while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ $id = $row['rowid']; ?> <tr> <td> <input class="newRecord<?php echo $id; ?>" type="text" name="newRecord<?php echo $id; ?>" /> <a href="?record=<?php echo $id; ?>"> <button class="saveRecord<?php echo $id; ?>" name="saveRecord<?php echo $id; ?>">Save</button> </a> </td> </tr> <?php } ?> </table> </form> ```
2015/05/26
[ "https://Stackoverflow.com/questions/30458408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3095385/" ]
Don't bother trying to do both at once (the $\_GET variables will only be passed if it is included in the action of the form). The script won't pick up the the records from the $\_POST as the names of the field have the ID included in them. Either create each record as an individual form (move the whole lot inside the WHILE loop), or you could use the ID held within the field name, like this: ``` $newdata = array(); foreach($_POST as $k => $v) { if ((substr($k,0,9) == 'newRecord') && (!empty($v)) { $id = substr($k,9); $klant = $v; $newdata[$id] = $klant; } } ``` Which should extract the ID from the field name and associate it with the data entered to the form.
Your button name is ``` name="saveRecord<?php echo $id; ?> ``` SO this condition need `$id` ``` if (isset($_POST['saveRecord'])) {// your id missing ```
30,458,408
I'm trying to post a new record in a table with `<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">`. But every row in my table has an unique id, and that id is put next to every `name`. So I'm trying to get the id with `$_GET` but it's been unsuccesful so far. Is the method I'm trying wrong or am I doing something else wrong? If anybody can tell me what's going wrong, I'd appreciatie. **PHP that gets placed above `<html>`** ``` <?php if (isset($_POST['saveRecord'])) { if (isset($_POST["newRecord"]) && !empty($_POST["newRecord"])) { $id = $_GET['record']; $klant=$_POST['newRecord'].$id; $query = "INSERT INTO table2 (recordid, recordname) VALUES (NULL, '$record')"; mysqli_query($con, $query); } } ?> ``` **Markup** ``` <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table> <?php $query = ("select * from table1"); $result = mysqli_query($con, $query) or die (mysqli_error()); while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ $id = $row['rowid']; ?> <tr> <td> <input class="newRecord<?php echo $id; ?>" type="text" name="newRecord<?php echo $id; ?>" /> <a href="?record=<?php echo $id; ?>"> <button class="saveRecord<?php echo $id; ?>" name="saveRecord<?php echo $id; ?>">Save</button> </a> </td> </tr> <?php } ?> </table> </form> ```
2015/05/26
[ "https://Stackoverflow.com/questions/30458408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3095385/" ]
Don't bother trying to do both at once (the $\_GET variables will only be passed if it is included in the action of the form). The script won't pick up the the records from the $\_POST as the names of the field have the ID included in them. Either create each record as an individual form (move the whole lot inside the WHILE loop), or you could use the ID held within the field name, like this: ``` $newdata = array(); foreach($_POST as $k => $v) { if ((substr($k,0,9) == 'newRecord') && (!empty($v)) { $id = substr($k,9); $klant = $v; $newdata[$id] = $klant; } } ``` Which should extract the ID from the field name and associate it with the data entered to the form.
move your opening and closing form tags in while loop,it will submit only 1 form at a time,otherwise all the inputs will be submitted.
5,235,868
I have just set up a test that checks that I am able to insert entries into my database using Hibernate. The thing that drives me crazy is that Hibernate does not actually delete the entries, although it reports that they are gone! The test below runs successfully, but when I check my DB afterwards the entries that were inserted are still there! I even try to check it using *assert* (yes I have -ea as vm parameter). Does anyone have a clue why the entries are not deleted? ``` public class HibernateExportStatisticDaoIntegrationTest { HibernateExportStatisticDao dao; Transaction transaction; @Before public void setUp(){ assert numberOfStatisticRowsInDB() == 0; dao = new HibernateExportStatisticDao(HibernateUtil.getSessionFactory()); } @After public void deleteAllEntries(){ assert numberOfStatisticRowsInDB() != 0; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); for(PersistableStatisticItem item:allStatisticItemsInDB()) { session.delete(item); } session.flush(); assert numberOfStatisticRowsInDB() == 0; } @Test public void exportAllSavesEntriesToDatabase(){ int expectedNumberOfStatistics = 20; dao.exportAll(StatisticItemFactory.createTestStatistics(expectedNumberOfStatistics)); assertEquals(expectedNumberOfStatistics, numberOfStatisticRowsInDB()); } private int numberOfStatisticRowsInDB() { return allStatisticItemsInDB().size(); } @SuppressWarnings("unchecked") private List<PersistableStatisticItem> allStatisticItemsInDB(){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); transaction = session.beginTransaction(); Query q = session.createQuery("FROM PersistableStatisticItem item"); return q.list(); } } ``` The console is filled with ``` Hibernate: delete from UPTIME_STATISTICS where logDate=? and serviceId=? ``` but nothing has been deleted when I check it.
2011/03/08
[ "https://Stackoverflow.com/questions/5235868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200987/" ]
I guess it's related to inconsistent use of transactions (note that `beginTransaction()` in `allStatisticItemsInDB()` is called several times without corresponding commits). Try to manage transactions in proper way, for example, like this: ``` Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); for(PersistableStatisticItem item: session.createQuery("FROM PersistableStatisticItem item").list()) { session.delete(item); } session.flush(); assert session.createQuery("FROM PersistableStatisticItem item").list().size() == 0; tx.commit(); ``` **See also:** * [13.2. Database transaction demarcation](http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/transactions.html#transactions-demarcation)
Can you post your DB schema and HBM or Fluent maps? One thing that got me a while back was I had a ReadOnly() in my Fluent map. It never threw an error and I too saw the "delete from blah where blahblah=..." in the logs.
5,235,868
I have just set up a test that checks that I am able to insert entries into my database using Hibernate. The thing that drives me crazy is that Hibernate does not actually delete the entries, although it reports that they are gone! The test below runs successfully, but when I check my DB afterwards the entries that were inserted are still there! I even try to check it using *assert* (yes I have -ea as vm parameter). Does anyone have a clue why the entries are not deleted? ``` public class HibernateExportStatisticDaoIntegrationTest { HibernateExportStatisticDao dao; Transaction transaction; @Before public void setUp(){ assert numberOfStatisticRowsInDB() == 0; dao = new HibernateExportStatisticDao(HibernateUtil.getSessionFactory()); } @After public void deleteAllEntries(){ assert numberOfStatisticRowsInDB() != 0; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); for(PersistableStatisticItem item:allStatisticItemsInDB()) { session.delete(item); } session.flush(); assert numberOfStatisticRowsInDB() == 0; } @Test public void exportAllSavesEntriesToDatabase(){ int expectedNumberOfStatistics = 20; dao.exportAll(StatisticItemFactory.createTestStatistics(expectedNumberOfStatistics)); assertEquals(expectedNumberOfStatistics, numberOfStatisticRowsInDB()); } private int numberOfStatisticRowsInDB() { return allStatisticItemsInDB().size(); } @SuppressWarnings("unchecked") private List<PersistableStatisticItem> allStatisticItemsInDB(){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); transaction = session.beginTransaction(); Query q = session.createQuery("FROM PersistableStatisticItem item"); return q.list(); } } ``` The console is filled with ``` Hibernate: delete from UPTIME_STATISTICS where logDate=? and serviceId=? ``` but nothing has been deleted when I check it.
2011/03/08
[ "https://Stackoverflow.com/questions/5235868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200987/" ]
I guess it's related to inconsistent use of transactions (note that `beginTransaction()` in `allStatisticItemsInDB()` is called several times without corresponding commits). Try to manage transactions in proper way, for example, like this: ``` Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Transaction tx = session.beginTransaction(); for(PersistableStatisticItem item: session.createQuery("FROM PersistableStatisticItem item").list()) { session.delete(item); } session.flush(); assert session.createQuery("FROM PersistableStatisticItem item").list().size() == 0; tx.commit(); ``` **See also:** * [13.2. Database transaction demarcation](http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/transactions.html#transactions-demarcation)
I have the same problem. Although I was not using transaction at all. I was using namedQuery like this : ``` Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES); int rows = query.executeUpdate(); session.close(); ``` It was returning 2 rows but the database still had all the records. Then I wrap up the above code with this : ``` Transaction transaction = session.beginTransaction(); Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES); int rows = query.executeUpdate(); transaction.commit(); session.close(); ``` Then it started working fine. I was using SQL server. But I think if we use h2, above code (without transaction) will also work fine. One more observation : To insert and get records usage of transaction is not mandatory but for deletion of records we will have to use transaction. (only tested in SQL server)
5,235,868
I have just set up a test that checks that I am able to insert entries into my database using Hibernate. The thing that drives me crazy is that Hibernate does not actually delete the entries, although it reports that they are gone! The test below runs successfully, but when I check my DB afterwards the entries that were inserted are still there! I even try to check it using *assert* (yes I have -ea as vm parameter). Does anyone have a clue why the entries are not deleted? ``` public class HibernateExportStatisticDaoIntegrationTest { HibernateExportStatisticDao dao; Transaction transaction; @Before public void setUp(){ assert numberOfStatisticRowsInDB() == 0; dao = new HibernateExportStatisticDao(HibernateUtil.getSessionFactory()); } @After public void deleteAllEntries(){ assert numberOfStatisticRowsInDB() != 0; Session session = HibernateUtil.getSessionFactory().getCurrentSession(); for(PersistableStatisticItem item:allStatisticItemsInDB()) { session.delete(item); } session.flush(); assert numberOfStatisticRowsInDB() == 0; } @Test public void exportAllSavesEntriesToDatabase(){ int expectedNumberOfStatistics = 20; dao.exportAll(StatisticItemFactory.createTestStatistics(expectedNumberOfStatistics)); assertEquals(expectedNumberOfStatistics, numberOfStatisticRowsInDB()); } private int numberOfStatisticRowsInDB() { return allStatisticItemsInDB().size(); } @SuppressWarnings("unchecked") private List<PersistableStatisticItem> allStatisticItemsInDB(){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); transaction = session.beginTransaction(); Query q = session.createQuery("FROM PersistableStatisticItem item"); return q.list(); } } ``` The console is filled with ``` Hibernate: delete from UPTIME_STATISTICS where logDate=? and serviceId=? ``` but nothing has been deleted when I check it.
2011/03/08
[ "https://Stackoverflow.com/questions/5235868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200987/" ]
I have the same problem. Although I was not using transaction at all. I was using namedQuery like this : ``` Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES); int rows = query.executeUpdate(); session.close(); ``` It was returning 2 rows but the database still had all the records. Then I wrap up the above code with this : ``` Transaction transaction = session.beginTransaction(); Query query = session.getNamedQuery(EmployeeNQ.DELETE_EMPLOYEES); int rows = query.executeUpdate(); transaction.commit(); session.close(); ``` Then it started working fine. I was using SQL server. But I think if we use h2, above code (without transaction) will also work fine. One more observation : To insert and get records usage of transaction is not mandatory but for deletion of records we will have to use transaction. (only tested in SQL server)
Can you post your DB schema and HBM or Fluent maps? One thing that got me a while back was I had a ReadOnly() in my Fluent map. It never threw an error and I too saw the "delete from blah where blahblah=..." in the logs.
9,392,951
I've been successfully able to generate a `.docx` document with <https://github.com/djpate/docxgen> but as soon as i try to include TinyMCE text, i no longer can open the document. (non valid char). Is there a way to convert the HTML text before giving it to docxgen to avoid such error?
2012/02/22
[ "https://Stackoverflow.com/questions/9392951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318071/" ]
I've decided to go with the pro version of the library <http://www.phpdocx.com/> as it simplifies the whole process. I hope it'll fill my needs.
Another solution is using <http://htmltodocx.codeplex.com/> which just recently came out. I, however, tried it and it messed up my invoice (granted I used tables where I shouldn't have) Jim
9,392,951
I've been successfully able to generate a `.docx` document with <https://github.com/djpate/docxgen> but as soon as i try to include TinyMCE text, i no longer can open the document. (non valid char). Is there a way to convert the HTML text before giving it to docxgen to avoid such error?
2012/02/22
[ "https://Stackoverflow.com/questions/9392951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318071/" ]
Finally, I settled with this answer to create a doc (simply output html and Word will recognize it): ``` header( 'Content-Type: application/msword' ); header("Content-disposition: attachment; filename=" .date("Y-m-d").".doc"); /* header("Content-type: application/vnd.ms-word"); header("Content-disposition: attachment; filename=" .date("Y-m-d").".rtf"); */ $html = preg_replace('%/[^\\s]+\\.(jpg|jpeg|png|gif)%i', 'http://www.akubocrm.com\\0', $html); print "<html xmlns:v=\"urn:schemas-microsoft-com:vml\""; print "xmlns:o=\"urn:schemas-microsoft-com:office:office\""; print "xmlns:w=\"urn:schemas-microsoft-com:office:word\""; print "xmlns=\"http://www.w3.org/TR/REC-html40\">"; print "<xml> <w:WordDocument> <w:View>Print</w:View> <w:DoNotHyphenateCaps/> <w:PunctuationKerning/> <w:DrawingGridHorizontalSpacing>9.35 pt</w:DrawingGridHorizontalSpacing> <w:DrawingGridVerticalSpacing>9.35 pt</w:DrawingGridVerticalSpacing> </w:WordDocument> </xml> "; die($html); ```
Another solution is using <http://htmltodocx.codeplex.com/> which just recently came out. I, however, tried it and it messed up my invoice (granted I used tables where I shouldn't have) Jim
4,156,378
How can we find the Jordan Canonical form given the minimal polynomial and the dimension of the kernel? I know how we could find it if either the matrix or the characteristic polynomial was given, but how does knowing the dimension of the kernel help us? $$ B: \mathbb{R}^4\rightarrow \mathbb{R}^4 $$ $$ m\_B(x) = (x-2)^2\*x $$ $$\newcommand{\Ker}{{\operatorname{Ker}}} \dim\_{\mathbb{R}}\Ker(B)=2 $$ Using the minimal polynomial I found that the Jordan form should be either $$ \begin{pmatrix} 2 & 1 & 0 & 0\\ 0 & 2 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ \end{pmatrix} $$ or $$ \begin{pmatrix} 2 & 1 & 0 & 0\\ 0 & 2 & 0 & 0 \\ 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & 0 \\ \end{pmatrix} $$ I suppose that the statement about the kernel should tell us which of this matrices is the right one. (assuming I found the right matrices in the first place :) ) Any help would be appreciated! Thanks
2021/05/31
[ "https://math.stackexchange.com/questions/4156378", "https://math.stackexchange.com", "https://math.stackexchange.com/users/933806/" ]
There exists a bounded, non-entire function on the complex plane that is analytic/holomorphic in some region. > > One possible example is $g(z) = \max\bigl(0, \frac{|z|-1}{|z|+1}\bigr)$. The verification of properties is left as an exercise. > > >
As meromorphic functions diverge to infinity at the pole, the answer to your question is negative. Next best I can think of is examples of the following kind: Define $g(z) = z^n$ inside the unit disc and outside the unit disc as $z^n/|z|^n$. On the boundary of the unit disc both definitions agree and so we get a continuous function on the whole complex plane. This is analytic in the unit disc.
4,156,378
How can we find the Jordan Canonical form given the minimal polynomial and the dimension of the kernel? I know how we could find it if either the matrix or the characteristic polynomial was given, but how does knowing the dimension of the kernel help us? $$ B: \mathbb{R}^4\rightarrow \mathbb{R}^4 $$ $$ m\_B(x) = (x-2)^2\*x $$ $$\newcommand{\Ker}{{\operatorname{Ker}}} \dim\_{\mathbb{R}}\Ker(B)=2 $$ Using the minimal polynomial I found that the Jordan form should be either $$ \begin{pmatrix} 2 & 1 & 0 & 0\\ 0 & 2 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 \\ \end{pmatrix} $$ or $$ \begin{pmatrix} 2 & 1 & 0 & 0\\ 0 & 2 & 0 & 0 \\ 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & 0 \\ \end{pmatrix} $$ I suppose that the statement about the kernel should tell us which of this matrices is the right one. (assuming I found the right matrices in the first place :) ) Any help would be appreciated! Thanks
2021/05/31
[ "https://math.stackexchange.com/questions/4156378", "https://math.stackexchange.com", "https://math.stackexchange.com/users/933806/" ]
There exists a bounded, non-entire function on the complex plane that is analytic/holomorphic in some region. > > One possible example is $g(z) = \max\bigl(0, \frac{|z|-1}{|z|+1}\bigr)$. The verification of properties is left as an exercise. > > >
You can even go further and prescribe an arbitrary region and an arbitrary analytic function thereon (as long as the latter is bounded on the former). If you do not require continuity you can just continue your function by 0 (or any other value you wish for). But you can also work with a smooth cutoff function in the style of Urysohn (or its smooth version). Suppose you have (what you call) a "region" $A$, then for any closed set $K$ such that $K\subset A^°$ (=interior) you find a smooth function which is constantly 1 on $K$ and constantly 0 on $\mathbb{C}\backslash \bar{A}$. Then you can multiply your "prescribed analytical values" by this function and the result is analytic on $K^°$. I'm not sure though, whether you can extend this approach to replace $A$ by an open neighborhood of $A$ and $K$ by $\bar{A}$ to receive such a function on all of $A$. Certainly, you have to claim that your prescribed values are analytically continuable to such an open neighborhood, which maybe imposes some niceness properties of the boundary of $A$.
24,320,502
This is my first trial in translating `pygtk` `glade`; I have created Rockdome.mo file on the following dir:`./locale/ar/LC_MESSAGES/Rockdome.mo` ``` def apply_locale(self , lang): domain = "Rockdome" local_path = basefolder+"/locale" # basefolder is the current dir lang = gettext.translation('Rockdome', local_path , languages=['%s'%lang]) lang.install() _ = lang.gettext print _("Close") # the output is اغلاق which is correct arabic translation!! ``` but the application still appear in the default system lamnguage `EN`; What I missing ?? EDIT ---- After searching in pygtk and buider tutoial; I found 2 methods to tell `gtk` & `builder` How to bring text : the first from [here](http://faq.pygtk.org/index.py?req=show&file=faq22.002.htp) : ``` for module in (gettext, gtk.glade): module.bindtextdomain(APP_NAME, LOCALE_DIR) module.textdomain(APP_NAME) ``` which fail. --- The second from [here](https://developer.gnome.org/gtk3/3.9/GtkBuilder.html#gtk-builder-set-translation-domain) ``` self.builder.set_translation_domain('Rockdome') print self.builder.get_translation_domain() # the output is "Rockdome" ``` which also fail !!, the application still untranslated !! > > N.B: I guess that `builder` needs to know the location for my local path to search in it not in the default paths > so I copied `./local/ar/LC_MESSAGES/Rockdome.mo` to `/usr/share/locale/ar/LC_MESSAGES/Rockdome.mo` which also failed. > > >
2014/06/20
[ "https://Stackoverflow.com/questions/24320502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3231979/" ]
the following method works succefully with me > 1. use `locale` module not `gettext`. 2. execute `locale.setlocale(category , language )` 3. Set the `translation_domain` of `gtk.Builder` by `gtk.Builder.set_translation_domain()` before loading glade file by : EX:`gtk.Builder.add_from_file` Code ## ------- ``` import locale from locale import gettext as _ def apply_locale(self , current_lang ): domain = "Rockdome" local_path = basefolder+"/data/locale" locale.bindtextdomain(domain , local_path ) locale.textdomain(domain) locale.setlocale(locale.LC_ALL, 'ar_AE.utf8') # note that language is "ar_AE.utf8" not "ar" or "ar_AE" self.builder.set_translation_domain(domain ) ``` --- Why we should replace gettext with locale ----------------------------------------- > > Thanks to Juha Sahakangas on the #gtk+ IRC channel for providing the explanation: > For this particular case the locale module needs to be used instead of gettext. > Python's gettext module is pure python, it doesn't actually set the text domain in a way that the C library can read, but locale does (by calling libc). > So long as that's done, GtkBuilder already works the way you're asking it to. > > > --- Notes ----- to avoid `locale.Error: unsupported locale setting` 1. In the function locale.setlocale(locale.LC\_ALL, language ); `language` should be one the supported languages. 2. to get list of supported languages; `locale -a` command. 3. The name of the language should be equal to its name in the output of the command `locale -a`; ie. don't strip the encode if it included in the language name, ie:. `ar_AE.utf8` doesn't equal to `ar_AE`. 4. If the `language` doesn't supported; we can install it. 5. To install unsupported language: > > sudo apt-get install language-pack-en-base > > > sudo dpkg-reconfigure locales > > > Thanks for this links --------------------- [how to make glade load translation](https://askubuntu.com/questions/140552/how-to-make-glade-load-translations-from-opt) [locale error : unsupported locale setting](https://stackoverflow.com/questions/14547631/python-locale-error-unsupported-locale-setting) [locale module doc](https://docs.python.org/2/library/locale.html#access-to-message-catalogs) [install unsupported locale](https://askubuntu.com/questions/17001/how-to-set-locale)
You are only changing the `lang` object within the scope of the function. You have to return it to set it properly. You need to call your function like this: `my_lang = apply_locale(lang)` or you could set `lang` as a property of the class. ``` def apply_locale(self , lang): domain = "Rockdome" local_path = basefolder+"/locale" # basefolder is the current dir lang = gettext.translation('Rockdome', local_path , languages=['%s'%lang]) lang.install() _ = lang.gettext return lang # Here you return the value and set it to the object you passed to your function. ``` Your use of the variable name here is confusing. You are changing the argument to a completely different type of object, you might want to differentiate between the two.
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
A one-liner, people love one-liners ``` var names = emailList.map(function(e){ return e.split('@').shift(); }).sort(); ``` If you want to take specifically the `@yahoo*` out, change split param to '@yahoo' ``` var names = emailList.map(function(e){ return e.split('@yahoo').shift(); }).sort(); ``` This will leave non-yahoo addresses untouched.
Try this following code ``` Array.prototype.remove = function(replaceString){ this.join('#').replace(replaceString,'').split('#').sort(); } emailList.remove('@yahoo.com'); ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
You can use the **map** function to transform your current list to one without the yahoo part. ``` var myEmailList = emailList.map(function(email){ return email.replace("@yahoo.com", ""); }); ``` and then you can sort it. ``` myEmailList.sort(); ``` you might also consider joining the list so it looks pretty before putting it back in html. ``` myEmailList.join(","); // joins the elements with a , in between ```
Try this following code ``` Array.prototype.remove = function(replaceString){ this.join('#').replace(replaceString,'').split('#').sort(); } emailList.remove('@yahoo.com'); ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
A one-liner, people love one-liners ``` var names = emailList.map(function(e){ return e.split('@').shift(); }).sort(); ``` If you want to take specifically the `@yahoo*` out, change split param to '@yahoo' ``` var names = emailList.map(function(e){ return e.split('@yahoo').shift(); }).sort(); ``` This will leave non-yahoo addresses untouched.
You can use the **map** function to transform your current list to one without the yahoo part. ``` var myEmailList = emailList.map(function(email){ return email.replace("@yahoo.com", ""); }); ``` and then you can sort it. ``` myEmailList.sort(); ``` you might also consider joining the list so it looks pretty before putting it back in html. ``` myEmailList.join(","); // joins the elements with a , in between ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
You need to loop through each item in the array and replace the string: ``` function myFunction() { for (var i = 0; i < emailList.length; i++) { emailList[i] = emailList[i].replace("@yahoo.com", ""); } emailList.sort(); } ``` Don't forget to call the function when you need it: ``` myFunction(); ``` If you want to append each item in the array onto a DOM element in a `div` tag: ``` function appendToDemo() { emailList.map(function(email) { document.getElemendById("demo").append(<div>email</div>); } } ``` (or something else to this effect)
Try this following code ``` Array.prototype.remove = function(replaceString){ this.join('#').replace(replaceString,'').split('#').sort(); } emailList.remove('@yahoo.com'); ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
A one-liner, people love one-liners ``` var names = emailList.map(function(e){ return e.split('@').shift(); }).sort(); ``` If you want to take specifically the `@yahoo*` out, change split param to '@yahoo' ``` var names = emailList.map(function(e){ return e.split('@yahoo').shift(); }).sort(); ``` This will leave non-yahoo addresses untouched.
Use array methods: * [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to remove the email host * [`sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to sort alphabetically * [`filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) ro remove duplicates Like this: ```js var emailList = [ "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n","[email protected]\n", "[email protected]\n", "[email protected]\n" ]; emailList = emailList .map(function(address){ return address.replace(/@yahoo\.edu\n/,''); }) .sort(function(a, b){ return a < b ? -1 : a > b ? 1 : 0; }) .filter(function(address, index, array){ return array.indexOf(address) == index; }); document.write(JSON.stringify(emailList)); // === ["adam", "david", "henry", "hunger", "john", "madison", "myhome", "sally"] ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
You can use the **map** function to transform your current list to one without the yahoo part. ``` var myEmailList = emailList.map(function(email){ return email.replace("@yahoo.com", ""); }); ``` and then you can sort it. ``` myEmailList.sort(); ``` you might also consider joining the list so it looks pretty before putting it back in html. ``` myEmailList.join(","); // joins the elements with a , in between ```
You can use either a for loop: ``` for (var i in myEmailList) { myEmailList[i] = myEmailList[i].replace("@yahoo.com"); } ``` or the map function: ``` myEmailList.map(function(email){return email.replace("@yahoo.com", "");}) ``` to get rid of every occurrence of "@yahoo.com" in the strings in the list. Then, sort the list: ``` myEmailList.sort(); ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
You need to loop through each item in the array and replace the string: ``` function myFunction() { for (var i = 0; i < emailList.length; i++) { emailList[i] = emailList[i].replace("@yahoo.com", ""); } emailList.sort(); } ``` Don't forget to call the function when you need it: ``` myFunction(); ``` If you want to append each item in the array onto a DOM element in a `div` tag: ``` function appendToDemo() { emailList.map(function(email) { document.getElemendById("demo").append(<div>email</div>); } } ``` (or something else to this effect)
You can use either a for loop: ``` for (var i in myEmailList) { myEmailList[i] = myEmailList[i].replace("@yahoo.com"); } ``` or the map function: ``` myEmailList.map(function(email){return email.replace("@yahoo.com", "");}) ``` to get rid of every occurrence of "@yahoo.com" in the strings in the list. Then, sort the list: ``` myEmailList.sort(); ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
You can use the **map** function to transform your current list to one without the yahoo part. ``` var myEmailList = emailList.map(function(email){ return email.replace("@yahoo.com", ""); }); ``` and then you can sort it. ``` myEmailList.sort(); ``` you might also consider joining the list so it looks pretty before putting it back in html. ``` myEmailList.join(","); // joins the elements with a , in between ```
Use array methods: * [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to remove the email host * [`sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to sort alphabetically * [`filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) ro remove duplicates Like this: ```js var emailList = [ "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n","[email protected]\n", "[email protected]\n", "[email protected]\n" ]; emailList = emailList .map(function(address){ return address.replace(/@yahoo\.edu\n/,''); }) .sort(function(a, b){ return a < b ? -1 : a > b ? 1 : 0; }) .filter(function(address, index, array){ return array.indexOf(address) == index; }); document.write(JSON.stringify(emailList)); // === ["adam", "david", "henry", "hunger", "john", "madison", "myhome", "sally"] ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
A one-liner, people love one-liners ``` var names = emailList.map(function(e){ return e.split('@').shift(); }).sort(); ``` If you want to take specifically the `@yahoo*` out, change split param to '@yahoo' ``` var names = emailList.map(function(e){ return e.split('@yahoo').shift(); }).sort(); ``` This will leave non-yahoo addresses untouched.
You can use either a for loop: ``` for (var i in myEmailList) { myEmailList[i] = myEmailList[i].replace("@yahoo.com"); } ``` or the map function: ``` myEmailList.map(function(email){return email.replace("@yahoo.com", "");}) ``` to get rid of every occurrence of "@yahoo.com" in the strings in the list. Then, sort the list: ``` myEmailList.sort(); ```
32,277,451
``` <p id="demo"></p> <script> //This is the email list var emailList =["[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", "[email protected]\n", ]; document.getElementById("demo").innerHTML = emailList; //I want to remove the @yahoo.com and then sort the list function myFunction() { var myEmailList = emailList.replace("@yahoo.com", " "); myEmailList.sort(); document.getElementById("demo").innerHTML = myEmailList; } </script> </body> </html> ```
2015/08/28
[ "https://Stackoverflow.com/questions/32277451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5277453/" ]
A one-liner, people love one-liners ``` var names = emailList.map(function(e){ return e.split('@').shift(); }).sort(); ``` If you want to take specifically the `@yahoo*` out, change split param to '@yahoo' ``` var names = emailList.map(function(e){ return e.split('@yahoo').shift(); }).sort(); ``` This will leave non-yahoo addresses untouched.
You need to loop through each item in the array and replace the string: ``` function myFunction() { for (var i = 0; i < emailList.length; i++) { emailList[i] = emailList[i].replace("@yahoo.com", ""); } emailList.sort(); } ``` Don't forget to call the function when you need it: ``` myFunction(); ``` If you want to append each item in the array onto a DOM element in a `div` tag: ``` function appendToDemo() { emailList.map(function(email) { document.getElemendById("demo").append(<div>email</div>); } } ``` (or something else to this effect)
1,955,895
I'm trying to calculate the radius of convergence of $\displaystyle\sum (1-1/n)^n\sin (n \alpha) z^{n}$ and my idea was to use the Hadamard formula, but I have no idea what to do about the $\sin$ and then I noticed that $\sin(n\alpha) = -i Im(e^{in\alpha})$ and then I thought that if the ratio would be the same as $\displaystyle\sum (1-1/n)^ne^{in\alpha} z^{n}$.
2016/10/06
[ "https://math.stackexchange.com/questions/1955895", "https://math.stackexchange.com", "https://math.stackexchange.com/users/306462/" ]
This is like asking "is $2$ equal to $4/2$ or $6/3$?" You have come across two equivalent ways of phrasing the same number. They're the same because $\cos(3\pi/2) = \cos(-\pi/2)$ and $\sin(3\pi/2) = \sin(-\pi/2)$. Think of this as two sets of directions to the same address ($-5j$). The representation $-5j = 5(\cos(3\pi/2) + j\sin(3\pi/2))$ says "start at $1$ and walk counter-clockwise three quarters of the way around the unit circle. Then face away from the origin and walk five steps." The representation $-5j = 5(\cos(-\pi/2) + j\sin(-\pi/2))$ says "start at $1$ and walk *clockwise* one quarter of the way around the unit circle. Then face away from the origin and walk five steps." Same number, two more ways of writing it.
Both are equivalent. $$\frac{3}{2}\pi - (- \frac{1}{2}\pi)2 =2\pi$$ and trigonometry function has a period of $2 \pi$.
42,497,896
In short, I need to test some functions by creating 100 random integer lists of each specified length (500, 1000, 10000) and store the results. Eventually, I need to be able to calculate an average execution time for each test but I've yet to get that far with the code. I assumed the following was the best way to approach this: 1. Create a dictionary to store the required list length values. 2. For each value in that dictionary, generate a new list of random integers (list\_tests). 3. Create another dictionary for storing the results of each function test (test\_results). 4. Use a while loop to create 100 lists of each length. 5. Run the tests by calling each function in the while loop and storing each result in the results dictionary. The program appears to run but I have a couple problems: * It never reaches the other list\_tests values; never proceeds beyond 500. * It's overwriting the values for the test\_results dictionary I don't quite understand where I've gone wrong with the loop in main(). Is my process to test these functions feasible? If so, I'm lost as to how I can fix this looping problem. Thank you in advance for any assistance you can offer! Here is my program: ``` import time import random def sequential_search(a_list, item): start = time.time() pos = 0 found = False while pos < len(a_list) and not found: if a_list[pos] == item: found = True else: pos = pos+1 end = time.time() return found, end-start def ordered_sequential_search(a_list, item): start = time.time() pos = 0 found = False stop = False while pos < len(a_list) and not found and not stop: if a_list[pos] == item: found == True else: if a_list[pos] > item: stop = True else: pos = pos+1 end = time.time() return found, end-start def num_gen(value): myrandom = random.sample(xrange(0, value), value) return myrandom def main(): #new_list = num_gen(10000) #print(sequential_search(new_list, -1)) list_tests = {'t500': 500, 't1000': 1000, 't10000': 10000} for i in list_tests.values(): new_list = num_gen(i) count = 0 test_results = {'seq': 0, 'ordseq': 0} while count < 100: test_results['seq'] += sequential_search(new_list, -1)[1] test_results['ordseq'] += ordered_sequential_search(new_list, -1)[1] count += 1 if __name__ == '__main__': main() ```
2017/02/27
[ "https://Stackoverflow.com/questions/42497896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7630431/" ]
I think you meant ``` found = True ``` Instead of ``` found == True ``` On line 47 Also a for loop is much cleaner try this, it should be what your looking for: ``` def ordered_sequential_search(a_list, item): start = time.time() found = False stop = False for i in range(len(a_list)): if a_list[i] == item: found = True else: if a_list[i] > item: stop = True if found: break if stop: break end = time.time() return found, end-start ```
It is overwriting values in the dictionary because you have specified the key to overwrite values. You are not appending to the dictionary which you should have done. Your while loop might not be breaking, that why your for loop cannot iterate to another value.
279,710
Consider the following data: ``` TableDat = {{0.1, 0.1}, {0.2, 0.3}, {0.3, 0.55}, {0.5, 1}, {0.6, 1.17}, {0.8, 1.5}, {0.9, 1.6}, {1, 1.5}, {1.1, 1.3}, {1.25, 1.}, {1.35, 0.8}, {1.5, 0.5}}; ListPlot[TableDat] ``` I would like to fit it with a smooth function: ``` fit = NonlinearModelFit[TableDat, a*x + b*x^2 + c, {a, b, c}, x] Show[Plot[fit[x], {x, 0.1, 1.5}], ListPlot[TableDat]] ``` [![enter image description here](https://i.stack.imgur.com/lkWLt.png)](https://i.stack.imgur.com/lkWLt.png) However, additionally, I want the value of the fitting function at x = 0.9 to match the data exactly. Is there a possibility to modify `NonlinearModelFit` to include this condition? A naive way would be to manually express c as a function of a,b from the condition `a*x+b*x^2+c==1.6` at x = 0.9, but what about an automated way?
2023/02/08
[ "https://mathematica.stackexchange.com/questions/279710", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/41058/" ]
Just add a constraint ``` fit = NonlinearModelFit[TableDat, {a*x + b*x^2 + c, 1.6 == (a*x + b*x^2 + c /. x -> 0.9)}, {a, b, c}, x] Show[Plot[fit[x], {x, 0.1, 1.5}], ListPlot[TableDat]] ``` [![enter image description here](https://i.stack.imgur.com/or1qE.jpg)](https://i.stack.imgur.com/or1qE.jpg) Hope it helps!
The right way ============= You say your model is ``` model = ( y == a*x + b*x^2 + c ) ``` that is, three free parameters `{a,b,c}`. But in reality, given the constraint `{ 0.9, 1.6 }` your model has only two parameters `{a,b}` ``` model2 = FullSimplify[ model/. First@Solve[ model /. { x -> 0.9, y -> 1.6 }, c ] ] ``` [![enter image description here](https://i.stack.imgur.com/NdVql.png)](https://i.stack.imgur.com/NdVql.png) ``` $PlotTheme = {"Scientific", "LargeLabels", "BoldScheme","DarkColor"}; fit = NonlinearModelFit[ tableDat , Last@model2 , {a, b} , x ]; Show[ Plot[ fit[x] , {x, 0.1, 1.5} ] , ListPlot[tableDat] , Epilog -> Inset["⚓",{ 0.9, 1.6 }] ] ``` [![enter image description here](https://i.stack.imgur.com/eHyDa.png)](https://i.stack.imgur.com/eHyDa.png) After @JimB's comment --------------------- > > Note that while the estimates for the slope and intercept don't change > if one leaves in `{0.9, 1.6}`, the values for many of the summary > statistics ("EstimatedVariance", "AIC", "AICc", "ParameterTable", > etc,) differ depending on if one keeps or removes that one data point. > I'd argue that if the choice the fixed point is selected from the > observed points (as opposed to knowing that fixed point beforehand), > I'd leave out that point to obtain more proper summary statistics. > > > therefore use ``` fit = NonlinearModelFit[ DeleteCases[tableDat, {0.9, 1.6}] , Last@model2 , {a, b} , x ]; ``` Your way ======== I would say that the previous solution is the correct way to do it, but given that you ask differently, refer to [the answer](https://mathematica.stackexchange.com/a/279711/10397) by [@UlrichNeumann](https://mathematica.stackexchange.com/users/53677/ulrich-neumann) (+1).
20,226,802
I managed to successfully silence the CrashReport dialog, but when my application crashes and I restart it, I get the annoying dialog as from Title. Is there a way to prevent it to appear, and just let the application run without interruption?
2013/11/26
[ "https://Stackoverflow.com/questions/20226802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
Try this to get rid of the reopening windows: ``` defaults write -app "Application Name" NSQuitAlwaysKeepsWindows -bool false ``` You may also disable it for every application by selecting this option in the preferences: "Close windows when quitting an application" And for others reading this thread, to remove the CrashReport do this: ``` defaults write com.apple.CrashReporter DialogType none ``` Also note that in the [source](https://apple.stackexchange.com/questions/80900/suppressing-reopen-windows-dialog-when-restarting-a-crashed-program-in-mountai) of this information they say: > > For this to work one needs to check the box, open the program in > question and immediately close it. On the next re-opening it will work > without Resume. > > > You may also have to delete: ``` /Users/…/Library/Saved\ Application\ State/org.python.python.savedState/ ```
You can disable this for a specific Xcode scheme by going to Edit Scheme, choosing the Options tab, and checking the box labeled "Launch application without state restoration." ![](https://i.stack.imgur.com/RyooI.png) However, this will *only* apply when you actually launch the application from Xcode; it won't disable the dialog when launching by double-clicking in Finder, or when launching from the terminal. (As best I can tell, there no way for AppKit/NSApplication-based apps to do what UIKit apps can do with [UIApplicationDelegate's `application:shouldRestoreApplicationState:`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622987-application?language=objc) and disable persistent state entirely for the application.)
20,226,802
I managed to successfully silence the CrashReport dialog, but when my application crashes and I restart it, I get the annoying dialog as from Title. Is there a way to prevent it to appear, and just let the application run without interruption?
2013/11/26
[ "https://Stackoverflow.com/questions/20226802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
Try this to get rid of the reopening windows: ``` defaults write -app "Application Name" NSQuitAlwaysKeepsWindows -bool false ``` You may also disable it for every application by selecting this option in the preferences: "Close windows when quitting an application" And for others reading this thread, to remove the CrashReport do this: ``` defaults write com.apple.CrashReporter DialogType none ``` Also note that in the [source](https://apple.stackexchange.com/questions/80900/suppressing-reopen-windows-dialog-when-restarting-a-crashed-program-in-mountai) of this information they say: > > For this to work one needs to check the box, open the program in > question and immediately close it. On the next re-opening it will work > without Resume. > > > You may also have to delete: ``` /Users/…/Library/Saved\ Application\ State/org.python.python.savedState/ ```
I was having a similar problem with google chrome and I could solve it by reading the following link: <https://support.google.com/chrome/thread/22716083?hl=en> Drew Z recommends the following solution there which worked for me: > > 1. In the Mac menu bar at the top of the screen, click Go. > 2. Select Go to Folder. > 3. Enter ~/Library/Application Support/Google/Chrome/ in the text field, then press Go. > 4. Locate the folder called "Default" in the directory window that opens and rename it as "Backup default." > 5. Try opening Google Chrome again. A new "Default" folder is automatically created as you start using the browser. > > >
20,226,802
I managed to successfully silence the CrashReport dialog, but when my application crashes and I restart it, I get the annoying dialog as from Title. Is there a way to prevent it to appear, and just let the application run without interruption?
2013/11/26
[ "https://Stackoverflow.com/questions/20226802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
Try this to get rid of the reopening windows: ``` defaults write -app "Application Name" NSQuitAlwaysKeepsWindows -bool false ``` You may also disable it for every application by selecting this option in the preferences: "Close windows when quitting an application" And for others reading this thread, to remove the CrashReport do this: ``` defaults write com.apple.CrashReporter DialogType none ``` Also note that in the [source](https://apple.stackexchange.com/questions/80900/suppressing-reopen-windows-dialog-when-restarting-a-crashed-program-in-mountai) of this information they say: > > For this to work one needs to check the box, open the program in > question and immediately close it. On the next re-opening it will work > without Resume. > > > You may also have to delete: ``` /Users/…/Library/Saved\ Application\ State/org.python.python.savedState/ ```
Voila! I've just solved this problem by deleting all Unity-related files inside ~Library/Caches folder on my Mac!
20,226,802
I managed to successfully silence the CrashReport dialog, but when my application crashes and I restart it, I get the annoying dialog as from Title. Is there a way to prevent it to appear, and just let the application run without interruption?
2013/11/26
[ "https://Stackoverflow.com/questions/20226802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
Try this to get rid of the reopening windows: ``` defaults write -app "Application Name" NSQuitAlwaysKeepsWindows -bool false ``` You may also disable it for every application by selecting this option in the preferences: "Close windows when quitting an application" And for others reading this thread, to remove the CrashReport do this: ``` defaults write com.apple.CrashReporter DialogType none ``` Also note that in the [source](https://apple.stackexchange.com/questions/80900/suppressing-reopen-windows-dialog-when-restarting-a-crashed-program-in-mountai) of this information they say: > > For this to work one needs to check the box, open the program in > question and immediately close it. On the next re-opening it will work > without Resume. > > > You may also have to delete: ``` /Users/…/Library/Saved\ Application\ State/org.python.python.savedState/ ```
For those trying to accomplish this `defaults write -app "Application Name" NSQuitAlwaysKeepsWindows -bool false` with Python, you may get the error `Couldn't find an application named "Python"; defaults unchanged`. To solve this, repeat the process to get the "reopen windows?" pop-up again, but do not choose an option in the pop-up – leave it alone for now. Right-click on the Python application's icon on the dock and choose "Show in Finder". Right-click on the application icon within Finder, hold the option key, and click `Copy "Python" as pathname"`. Paste that in as the "Application Name" for the command above and it should work.
20,226,802
I managed to successfully silence the CrashReport dialog, but when my application crashes and I restart it, I get the annoying dialog as from Title. Is there a way to prevent it to appear, and just let the application run without interruption?
2013/11/26
[ "https://Stackoverflow.com/questions/20226802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
I was having a similar problem with google chrome and I could solve it by reading the following link: <https://support.google.com/chrome/thread/22716083?hl=en> Drew Z recommends the following solution there which worked for me: > > 1. In the Mac menu bar at the top of the screen, click Go. > 2. Select Go to Folder. > 3. Enter ~/Library/Application Support/Google/Chrome/ in the text field, then press Go. > 4. Locate the folder called "Default" in the directory window that opens and rename it as "Backup default." > 5. Try opening Google Chrome again. A new "Default" folder is automatically created as you start using the browser. > > >
You can disable this for a specific Xcode scheme by going to Edit Scheme, choosing the Options tab, and checking the box labeled "Launch application without state restoration." ![](https://i.stack.imgur.com/RyooI.png) However, this will *only* apply when you actually launch the application from Xcode; it won't disable the dialog when launching by double-clicking in Finder, or when launching from the terminal. (As best I can tell, there no way for AppKit/NSApplication-based apps to do what UIKit apps can do with [UIApplicationDelegate's `application:shouldRestoreApplicationState:`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622987-application?language=objc) and disable persistent state entirely for the application.)
20,226,802
I managed to successfully silence the CrashReport dialog, but when my application crashes and I restart it, I get the annoying dialog as from Title. Is there a way to prevent it to appear, and just let the application run without interruption?
2013/11/26
[ "https://Stackoverflow.com/questions/20226802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
Voila! I've just solved this problem by deleting all Unity-related files inside ~Library/Caches folder on my Mac!
You can disable this for a specific Xcode scheme by going to Edit Scheme, choosing the Options tab, and checking the box labeled "Launch application without state restoration." ![](https://i.stack.imgur.com/RyooI.png) However, this will *only* apply when you actually launch the application from Xcode; it won't disable the dialog when launching by double-clicking in Finder, or when launching from the terminal. (As best I can tell, there no way for AppKit/NSApplication-based apps to do what UIKit apps can do with [UIApplicationDelegate's `application:shouldRestoreApplicationState:`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622987-application?language=objc) and disable persistent state entirely for the application.)
20,226,802
I managed to successfully silence the CrashReport dialog, but when my application crashes and I restart it, I get the annoying dialog as from Title. Is there a way to prevent it to appear, and just let the application run without interruption?
2013/11/26
[ "https://Stackoverflow.com/questions/20226802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78374/" ]
For those trying to accomplish this `defaults write -app "Application Name" NSQuitAlwaysKeepsWindows -bool false` with Python, you may get the error `Couldn't find an application named "Python"; defaults unchanged`. To solve this, repeat the process to get the "reopen windows?" pop-up again, but do not choose an option in the pop-up – leave it alone for now. Right-click on the Python application's icon on the dock and choose "Show in Finder". Right-click on the application icon within Finder, hold the option key, and click `Copy "Python" as pathname"`. Paste that in as the "Application Name" for the command above and it should work.
You can disable this for a specific Xcode scheme by going to Edit Scheme, choosing the Options tab, and checking the box labeled "Launch application without state restoration." ![](https://i.stack.imgur.com/RyooI.png) However, this will *only* apply when you actually launch the application from Xcode; it won't disable the dialog when launching by double-clicking in Finder, or when launching from the terminal. (As best I can tell, there no way for AppKit/NSApplication-based apps to do what UIKit apps can do with [UIApplicationDelegate's `application:shouldRestoreApplicationState:`](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1622987-application?language=objc) and disable persistent state entirely for the application.)
7,266,915
Consider the following: ``` class A { private: A() {} public: A(int x = 0) {} }; int main() { A a(1); return 0; } ``` I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler doesn't produce one. Even when I don't create an instance of `A`, it doesn't produce an ambiguity error either. ``` int main() { return 0; } ``` Why is that?
2011/09/01
[ "https://Stackoverflow.com/questions/7266915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911575/" ]
There is no compilation error because no error exists in your code. Just like defining two functions: they need to have different signatures, other than that, it's possible. The ambiguity compilation error appears only when you try to call one of those functions. Same will happen trying to call the default constructor of `A`, even if it is private: ``` class A { private: A() {} public: A(int x = 0) {} void f() {} void f(int x = 0) {} }; ``` This compiles, trying to call `f()` with no parameters fails, which makes sense. Also try: ``` class A { private: A() {} public: A(int x = 0) {} void f() {} void f() const {} }; ``` Should this give an error? No, because the two `f`'s have different signatures. In this case the compiler can resolve the ambiguity, if you call `f` on a `const` object, the `const` method will get called, and vice-versa.
Here is a slightly modified example that I have tested with GCC on cygwin: ``` #include <iostream> class A { private: A(); public: A(int x = 0); }; A::A() { std::cout << "Constructor 1.\n" << std::endl; } A::A(int x) { std::cout << "Constructor 2 with x = " << x << std::endl; } int main() { A a1(1); A a2; return 0; } ``` The compiler gives the following error message: ``` $ g++ test.cc test.cc: In function `int main()': test.cc:28: error: call of overloaded `A()' is ambiguous test.cc:20: note: candidates are: A::A(int) test.cc:14: note: A::A() ``` **Update** I understand how the C++ compiler works (thanks for the explanations given by others): the two declarations are different and therefore accepted, but when trying to reference the default constructor, the compiler cannot decide which of the two it should use. However, the fact that the default constructor A() can never be invoked can be inferred from the declarations already. Apparently you have two functions with different signatures ``` A() A(int x = 0) ``` but, in fact, A(int x = 0) implicitly defines two functions: A(int x) and A(). In the second function x is just an initialized local variable. Instead of writing ``` A(int x = 0) { ... } ``` you could write two functions: ``` A(int x) { ... } A() { int x = 0; ... } ``` with the same body. The second of these two functions has the same signature as the default constructor A(). That's why you will always have a compilation error when you try to instantiate class A using the A() constructor. This could be detected even without an explicit declaration such as ``` A a; ``` So I totally agree with Ron\_s that I would expect an ambiguity error in his example. IMHO it would be more consistent.
7,266,915
Consider the following: ``` class A { private: A() {} public: A(int x = 0) {} }; int main() { A a(1); return 0; } ``` I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler doesn't produce one. Even when I don't create an instance of `A`, it doesn't produce an ambiguity error either. ``` int main() { return 0; } ``` Why is that?
2011/09/01
[ "https://Stackoverflow.com/questions/7266915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911575/" ]
There is no compilation error because no error exists in your code. Just like defining two functions: they need to have different signatures, other than that, it's possible. The ambiguity compilation error appears only when you try to call one of those functions. Same will happen trying to call the default constructor of `A`, even if it is private: ``` class A { private: A() {} public: A(int x = 0) {} void f() {} void f(int x = 0) {} }; ``` This compiles, trying to call `f()` with no parameters fails, which makes sense. Also try: ``` class A { private: A() {} public: A(int x = 0) {} void f() {} void f() const {} }; ``` Should this give an error? No, because the two `f`'s have different signatures. In this case the compiler can resolve the ambiguity, if you call `f` on a `const` object, the `const` method will get called, and vice-versa.
Ambiguity doesn't arise because the private constructor is not even considered when you write `A a(1)`, as you pass an argument to it, and the private constructor doesn't take any argument. However, if you write `A a`, then there will be ambiguity, because both constructors are candidates, and the compiler cannot decide which one to invoke.
7,266,915
Consider the following: ``` class A { private: A() {} public: A(int x = 0) {} }; int main() { A a(1); return 0; } ``` I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler doesn't produce one. Even when I don't create an instance of `A`, it doesn't produce an ambiguity error either. ``` int main() { return 0; } ``` Why is that?
2011/09/01
[ "https://Stackoverflow.com/questions/7266915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911575/" ]
There is no compilation error because no error exists in your code. Just like defining two functions: they need to have different signatures, other than that, it's possible. The ambiguity compilation error appears only when you try to call one of those functions. Same will happen trying to call the default constructor of `A`, even if it is private: ``` class A { private: A() {} public: A(int x = 0) {} void f() {} void f(int x = 0) {} }; ``` This compiles, trying to call `f()` with no parameters fails, which makes sense. Also try: ``` class A { private: A() {} public: A(int x = 0) {} void f() {} void f() const {} }; ``` Should this give an error? No, because the two `f`'s have different signatures. In this case the compiler can resolve the ambiguity, if you call `f` on a `const` object, the `const` method will get called, and vice-versa.
Declaring potentially ambiguous functions in C++ does not produce any ambiguity errors. Ambiguity takes place when you attempt to *refer* to these functions in an ambiguous way. In your example ambiguity will occur if you try to default-construct your object. Strictly speaking, it is perfectly normal to have declarations in C++ program that are potentially ambiguous (i.e. that can be referred to in an ambiguous way). For example, at the first sight these overloaded functions look fine ``` void foo(double); void foo(int); ``` but calling `foo(1u)` will trigger ambiguity error. So, once again, ambiguity is the property of the way you refer to the previously declared functions, not the property of the function declarations themselves.
7,266,915
Consider the following: ``` class A { private: A() {} public: A(int x = 0) {} }; int main() { A a(1); return 0; } ``` I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler doesn't produce one. Even when I don't create an instance of `A`, it doesn't produce an ambiguity error either. ``` int main() { return 0; } ``` Why is that?
2011/09/01
[ "https://Stackoverflow.com/questions/7266915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911575/" ]
Here is a slightly modified example that I have tested with GCC on cygwin: ``` #include <iostream> class A { private: A(); public: A(int x = 0); }; A::A() { std::cout << "Constructor 1.\n" << std::endl; } A::A(int x) { std::cout << "Constructor 2 with x = " << x << std::endl; } int main() { A a1(1); A a2; return 0; } ``` The compiler gives the following error message: ``` $ g++ test.cc test.cc: In function `int main()': test.cc:28: error: call of overloaded `A()' is ambiguous test.cc:20: note: candidates are: A::A(int) test.cc:14: note: A::A() ``` **Update** I understand how the C++ compiler works (thanks for the explanations given by others): the two declarations are different and therefore accepted, but when trying to reference the default constructor, the compiler cannot decide which of the two it should use. However, the fact that the default constructor A() can never be invoked can be inferred from the declarations already. Apparently you have two functions with different signatures ``` A() A(int x = 0) ``` but, in fact, A(int x = 0) implicitly defines two functions: A(int x) and A(). In the second function x is just an initialized local variable. Instead of writing ``` A(int x = 0) { ... } ``` you could write two functions: ``` A(int x) { ... } A() { int x = 0; ... } ``` with the same body. The second of these two functions has the same signature as the default constructor A(). That's why you will always have a compilation error when you try to instantiate class A using the A() constructor. This could be detected even without an explicit declaration such as ``` A a; ``` So I totally agree with Ron\_s that I would expect an ambiguity error in his example. IMHO it would be more consistent.
Ambiguity doesn't arise because the private constructor is not even considered when you write `A a(1)`, as you pass an argument to it, and the private constructor doesn't take any argument. However, if you write `A a`, then there will be ambiguity, because both constructors are candidates, and the compiler cannot decide which one to invoke.
7,266,915
Consider the following: ``` class A { private: A() {} public: A(int x = 0) {} }; int main() { A a(1); return 0; } ``` I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler doesn't produce one. Even when I don't create an instance of `A`, it doesn't produce an ambiguity error either. ``` int main() { return 0; } ``` Why is that?
2011/09/01
[ "https://Stackoverflow.com/questions/7266915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911575/" ]
Declaring potentially ambiguous functions in C++ does not produce any ambiguity errors. Ambiguity takes place when you attempt to *refer* to these functions in an ambiguous way. In your example ambiguity will occur if you try to default-construct your object. Strictly speaking, it is perfectly normal to have declarations in C++ program that are potentially ambiguous (i.e. that can be referred to in an ambiguous way). For example, at the first sight these overloaded functions look fine ``` void foo(double); void foo(int); ``` but calling `foo(1u)` will trigger ambiguity error. So, once again, ambiguity is the property of the way you refer to the previously declared functions, not the property of the function declarations themselves.
Here is a slightly modified example that I have tested with GCC on cygwin: ``` #include <iostream> class A { private: A(); public: A(int x = 0); }; A::A() { std::cout << "Constructor 1.\n" << std::endl; } A::A(int x) { std::cout << "Constructor 2 with x = " << x << std::endl; } int main() { A a1(1); A a2; return 0; } ``` The compiler gives the following error message: ``` $ g++ test.cc test.cc: In function `int main()': test.cc:28: error: call of overloaded `A()' is ambiguous test.cc:20: note: candidates are: A::A(int) test.cc:14: note: A::A() ``` **Update** I understand how the C++ compiler works (thanks for the explanations given by others): the two declarations are different and therefore accepted, but when trying to reference the default constructor, the compiler cannot decide which of the two it should use. However, the fact that the default constructor A() can never be invoked can be inferred from the declarations already. Apparently you have two functions with different signatures ``` A() A(int x = 0) ``` but, in fact, A(int x = 0) implicitly defines two functions: A(int x) and A(). In the second function x is just an initialized local variable. Instead of writing ``` A(int x = 0) { ... } ``` you could write two functions: ``` A(int x) { ... } A() { int x = 0; ... } ``` with the same body. The second of these two functions has the same signature as the default constructor A(). That's why you will always have a compilation error when you try to instantiate class A using the A() constructor. This could be detected even without an explicit declaration such as ``` A a; ``` So I totally agree with Ron\_s that I would expect an ambiguity error in his example. IMHO it would be more consistent.
7,266,915
Consider the following: ``` class A { private: A() {} public: A(int x = 0) {} }; int main() { A a(1); return 0; } ``` I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler doesn't produce one. Even when I don't create an instance of `A`, it doesn't produce an ambiguity error either. ``` int main() { return 0; } ``` Why is that?
2011/09/01
[ "https://Stackoverflow.com/questions/7266915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911575/" ]
Your code compiles because there is no ambiguity. You created a class with two constructors, one which always takes 0 arguments, and one which always takes one argument, an int. You then unambiguously called the constructor taking an int value. That this int has a default value does not matter, it is still a completely different signature. That the constructors are potentially ambiguous doesn't matter, the compiler only complains when a particular call is actually ambiguous. When you create an instance of A with no arguments, it doesn't know which constructor you want to call: the default constructor, or the constructor taking an int with a parameter value of 0. In this case it would be nice if C++ notices that the private constructor is ineligible, but that is not always possible. This behavior ends up being useful in some circumstances (e.g. if you have a few overloads involving templates, some of which will overlap if given the right types), though for simple cases like this, I would just make the single constructor with the default argument (preferably marked explicit unless you have a really really good reason to leave it implicit, and then I would second guess that reason just to be sure!) -- EDIT -- Let's have some fun with this and try to explore further what is happening. ``` // A.h class A { public: A(); // declare that somewhere out there, there exists a constructor that takes no args. Note that actually figuring out where this constructor is defined is the linker's job A(int x = 10); // declare that somewhere out there, there exists a constructor that take one arg, an integer. Figuring out where it is defined is still the linker's job. (this line does _not_ declare two constructors.) int x; }; // A.cpp #include "A.h" A::A() { ... } // OK, provide a definition for A::A() A::A(int x) { ... } // OK, provide a definition for A::A(int) -- but wait, where is our default param?? // Foo.cpp #include "A.h" void Foo() { A a1(24); // perfectly fine A a2; // Ambigious! } // Bar.cpp class A // What's going on? We are redefining A?!?! { public: A(); A(int x); // this definition doesn't have a default param! int x; }; void Bar() { A a; // This works! The default constructor is called! } // Baz.cpp class A // What's going on? We are redefining A again?!?! { public: //A(); // no default constructor! A(int x = 42); // this definition has a default param again, but wait, it's different! int x; }; void Baz() { A a; // This works! A::A(int) is call! (but with what parameter?) } ``` Note that we are taking advantage of the fact that the compiler doesn't know about headers; by the time it looks at a .cpp file, the preprocessor has already substituted #includes with the body of the header. I am playing at being my own preprocessor, doing some dangerous things like providing multiple, different definitions of a class. Later on, one of the linker's jobs is to throw out all but one of these definitions. If they do not align up in the exact right way, all kinds of bad things will happen, as you will be in the twilight zone of undefined behavior. Note that I was careful to provide the exact same layout for my class in every compilation unit; every definition has exactly 1 int and 0 virtual methods. Note that I did not introduce any extra methods (though that might work; still doing things like this should be looked on with great suspicion), the only thing that changed were some non-virtual member functions (well constructors really) and then only to remove the default constructor. Changing and removing the default value changed nothing about the definition of A::A(int). I don't have a copy of the spec on me, so I can't say if my careful changes fall under undefined behavior or implementation specific behavior, but I would treat it as such for production code and avoid leveraging such tricks. And the ultimate answer to what argument is used inside of Baz is,.... 42!
Here is a slightly modified example that I have tested with GCC on cygwin: ``` #include <iostream> class A { private: A(); public: A(int x = 0); }; A::A() { std::cout << "Constructor 1.\n" << std::endl; } A::A(int x) { std::cout << "Constructor 2 with x = " << x << std::endl; } int main() { A a1(1); A a2; return 0; } ``` The compiler gives the following error message: ``` $ g++ test.cc test.cc: In function `int main()': test.cc:28: error: call of overloaded `A()' is ambiguous test.cc:20: note: candidates are: A::A(int) test.cc:14: note: A::A() ``` **Update** I understand how the C++ compiler works (thanks for the explanations given by others): the two declarations are different and therefore accepted, but when trying to reference the default constructor, the compiler cannot decide which of the two it should use. However, the fact that the default constructor A() can never be invoked can be inferred from the declarations already. Apparently you have two functions with different signatures ``` A() A(int x = 0) ``` but, in fact, A(int x = 0) implicitly defines two functions: A(int x) and A(). In the second function x is just an initialized local variable. Instead of writing ``` A(int x = 0) { ... } ``` you could write two functions: ``` A(int x) { ... } A() { int x = 0; ... } ``` with the same body. The second of these two functions has the same signature as the default constructor A(). That's why you will always have a compilation error when you try to instantiate class A using the A() constructor. This could be detected even without an explicit declaration such as ``` A a; ``` So I totally agree with Ron\_s that I would expect an ambiguity error in his example. IMHO it would be more consistent.
7,266,915
Consider the following: ``` class A { private: A() {} public: A(int x = 0) {} }; int main() { A a(1); return 0; } ``` I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler doesn't produce one. Even when I don't create an instance of `A`, it doesn't produce an ambiguity error either. ``` int main() { return 0; } ``` Why is that?
2011/09/01
[ "https://Stackoverflow.com/questions/7266915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911575/" ]
Declaring potentially ambiguous functions in C++ does not produce any ambiguity errors. Ambiguity takes place when you attempt to *refer* to these functions in an ambiguous way. In your example ambiguity will occur if you try to default-construct your object. Strictly speaking, it is perfectly normal to have declarations in C++ program that are potentially ambiguous (i.e. that can be referred to in an ambiguous way). For example, at the first sight these overloaded functions look fine ``` void foo(double); void foo(int); ``` but calling `foo(1u)` will trigger ambiguity error. So, once again, ambiguity is the property of the way you refer to the previously declared functions, not the property of the function declarations themselves.
Ambiguity doesn't arise because the private constructor is not even considered when you write `A a(1)`, as you pass an argument to it, and the private constructor doesn't take any argument. However, if you write `A a`, then there will be ambiguity, because both constructors are candidates, and the compiler cannot decide which one to invoke.
7,266,915
Consider the following: ``` class A { private: A() {} public: A(int x = 0) {} }; int main() { A a(1); return 0; } ``` I have two constructors, one is a default and the other one is converting constructor with a default argument. When I try to compile the code, I expected an ambiguity error, but the compiler doesn't produce one. Even when I don't create an instance of `A`, it doesn't produce an ambiguity error either. ``` int main() { return 0; } ``` Why is that?
2011/09/01
[ "https://Stackoverflow.com/questions/7266915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/911575/" ]
Your code compiles because there is no ambiguity. You created a class with two constructors, one which always takes 0 arguments, and one which always takes one argument, an int. You then unambiguously called the constructor taking an int value. That this int has a default value does not matter, it is still a completely different signature. That the constructors are potentially ambiguous doesn't matter, the compiler only complains when a particular call is actually ambiguous. When you create an instance of A with no arguments, it doesn't know which constructor you want to call: the default constructor, or the constructor taking an int with a parameter value of 0. In this case it would be nice if C++ notices that the private constructor is ineligible, but that is not always possible. This behavior ends up being useful in some circumstances (e.g. if you have a few overloads involving templates, some of which will overlap if given the right types), though for simple cases like this, I would just make the single constructor with the default argument (preferably marked explicit unless you have a really really good reason to leave it implicit, and then I would second guess that reason just to be sure!) -- EDIT -- Let's have some fun with this and try to explore further what is happening. ``` // A.h class A { public: A(); // declare that somewhere out there, there exists a constructor that takes no args. Note that actually figuring out where this constructor is defined is the linker's job A(int x = 10); // declare that somewhere out there, there exists a constructor that take one arg, an integer. Figuring out where it is defined is still the linker's job. (this line does _not_ declare two constructors.) int x; }; // A.cpp #include "A.h" A::A() { ... } // OK, provide a definition for A::A() A::A(int x) { ... } // OK, provide a definition for A::A(int) -- but wait, where is our default param?? // Foo.cpp #include "A.h" void Foo() { A a1(24); // perfectly fine A a2; // Ambigious! } // Bar.cpp class A // What's going on? We are redefining A?!?! { public: A(); A(int x); // this definition doesn't have a default param! int x; }; void Bar() { A a; // This works! The default constructor is called! } // Baz.cpp class A // What's going on? We are redefining A again?!?! { public: //A(); // no default constructor! A(int x = 42); // this definition has a default param again, but wait, it's different! int x; }; void Baz() { A a; // This works! A::A(int) is call! (but with what parameter?) } ``` Note that we are taking advantage of the fact that the compiler doesn't know about headers; by the time it looks at a .cpp file, the preprocessor has already substituted #includes with the body of the header. I am playing at being my own preprocessor, doing some dangerous things like providing multiple, different definitions of a class. Later on, one of the linker's jobs is to throw out all but one of these definitions. If they do not align up in the exact right way, all kinds of bad things will happen, as you will be in the twilight zone of undefined behavior. Note that I was careful to provide the exact same layout for my class in every compilation unit; every definition has exactly 1 int and 0 virtual methods. Note that I did not introduce any extra methods (though that might work; still doing things like this should be looked on with great suspicion), the only thing that changed were some non-virtual member functions (well constructors really) and then only to remove the default constructor. Changing and removing the default value changed nothing about the definition of A::A(int). I don't have a copy of the spec on me, so I can't say if my careful changes fall under undefined behavior or implementation specific behavior, but I would treat it as such for production code and avoid leveraging such tricks. And the ultimate answer to what argument is used inside of Baz is,.... 42!
Ambiguity doesn't arise because the private constructor is not even considered when you write `A a(1)`, as you pass an argument to it, and the private constructor doesn't take any argument. However, if you write `A a`, then there will be ambiguity, because both constructors are candidates, and the compiler cannot decide which one to invoke.