qid
int64
1
74.7M
question
stringlengths
1
70k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
0
60.5k
31,284,003
**Updated with Code:** I have a string array in my controller like below, ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About']; }; }); ``` I need to display it in the navigation pane (navigation should be on the leftside) Below is my html code. ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ``` I did get the string values bound to the navigation pane. It is showing text like {{x}}. Kindly help
2015/07/08
[ "https://Stackoverflow.com/questions/31284003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419549/" ]
1. In your javascript code `};` is unnecessary. 2. You haven't attached `controller` to the `div`. Code. Javascript: ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems = ['Home', 'About']; //}; // REMOVE THIS }); ``` HTML: ``` <div class="col-md-2" ng-controller="mycontroller"> <!-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> ```
Edit: Since you didn't post the whole code. I am expecting the all the necessary directives like ng-app and ng-controller are in place already in your code. If you are using HTML5 by using `<!DOCTYPE html>`, then syntax might give trouble sometimes. I gave it a try. Observe the line that I have marked with asterisks. I didn't end the script tag properly. And so I also got the {{x}} thing on the browser. When I replaced that line with properly ended script tags . It worked for me. You can may be try this way out. It worked for me. ``` <!DOCTYPE html> <html> <head> <title> StackOverflow </title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> ***** <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"/> <script type="text/javascript" src="app.js"></script> <script src="soCtrl.js"></script> </head> <body ng-app="soApp"> <div class="col-md-2" ng-controller="soCtrl"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> </html> ```
31,284,003
**Updated with Code:** I have a string array in my controller like below, ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About']; }; }); ``` I need to display it in the navigation pane (navigation should be on the leftside) Below is my html code. ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ``` I did get the string values bound to the navigation pane. It is showing text like {{x}}. Kindly help
2015/07/08
[ "https://Stackoverflow.com/questions/31284003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419549/" ]
Try the below code: ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" > <li ng-repeat="x in menuitems">{{x}}</li> </ul> </div> </body> ```
You haven't specified to make use of `mycontroller` in your html code. ``` <body class="container-fluid"> <div class="col-md-2" ng-controller='mycontroller'> <ul class="nav nav-pills nav-stacked" ng-repeat = "x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ```
31,284,003
**Updated with Code:** I have a string array in my controller like below, ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About']; }; }); ``` I need to display it in the navigation pane (navigation should be on the leftside) Below is my html code. ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ``` I did get the string values bound to the navigation pane. It is showing text like {{x}}. Kindly help
2015/07/08
[ "https://Stackoverflow.com/questions/31284003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419549/" ]
Try the below code: ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" > <li ng-repeat="x in menuitems">{{x}}</li> </ul> </div> </body> ```
Hey i guess the mistake is you should give the ng-repeat in li tag try it . It should work
31,284,003
**Updated with Code:** I have a string array in my controller like below, ``` var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About']; }; }); ``` I need to display it in the navigation pane (navigation should be on the leftside) Below is my html code. ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> ``` I did get the string values bound to the navigation pane. It is showing text like {{x}}. Kindly help
2015/07/08
[ "https://Stackoverflow.com/questions/31284003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419549/" ]
Try the below code: ``` <body class="container-fluid"> <div class="col-md-2"> <ul class="nav nav-pills nav-stacked" > <li ng-repeat="x in menuitems">{{x}}</li> </ul> </div> </body> ```
Edit: Since you didn't post the whole code. I am expecting the all the necessary directives like ng-app and ng-controller are in place already in your code. If you are using HTML5 by using `<!DOCTYPE html>`, then syntax might give trouble sometimes. I gave it a try. Observe the line that I have marked with asterisks. I didn't end the script tag properly. And so I also got the {{x}} thing on the browser. When I replaced that line with properly ended script tags . It worked for me. You can may be try this way out. It worked for me. ``` <!DOCTYPE html> <html> <head> <title> StackOverflow </title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> ***** <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"/> <script type="text/javascript" src="app.js"></script> <script src="soCtrl.js"></script> </head> <body ng-app="soApp"> <div class="col-md-2" ng-controller="soCtrl"> <ul class="nav nav-pills nav-stacked" ng-repeat="x in menuitems track by $index"> <li>{{x}}</li> </ul> </div> </body> </html> ```
47,832,762
I am looking for a convenient, safe python dictionary key access approach. Here are 3 ways came to my mind. ```py data = {'color': 'yellow'} # approach one color_1 = None if 'color' in data: color_1 = data['color'] # approach two color_2 = data['color'] if 'color' in data else None # approach three def safe(obj, key): if key in obj: return obj[key] else: return None color_3 = safe(data, 'color') #output print("{},{},{}".format(color_1, color_2, color_3)) ``` All three methods work, of-course. But is there any simple out of the box way to achieve this without having to use excess `if`s or custom functions? I believe there should be, because this is a very common usage.
2017/12/15
[ "https://Stackoverflow.com/questions/47832762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4112088/" ]
You missed the canonical method, [`dict.get()`](https://docs.python.org/3/library/stdtypes.html#dict.get): ``` color_1 = data.get('color') ``` It'll return `None` if the key is missing. You can set a different default as a second argument: ``` color_2 = data.get('color', 'red') ```
Check out [`dict.get()`](https://docs.python.org/3.6/library/stdtypes.html#dict.get). You can supply a value to return if the key is not found in the dictionary, otherwise it will return `None`. ``` >>> data = {'color': 'yellow'} >>> data.get('color') 'yellow' >>> data.get('name') is None True >>> data.get('name', 'nothing') 'nothing' ```
606,293
I don't see why the custom (temperature) command `\newcommand{\deg}{$^\circ$F}` returns a `"missing $ inserted"` error when writing something like `350\deg` in text mode. More confusingly, it compiles if I use `\renewcommand`, suggesting the command name `\deg` has already been used. But the same error is returned no matter the command name.
2021/07/25
[ "https://tex.stackexchange.com/questions/606293", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/35910/" ]
A bit off-topic, however: * Fahrenheit are not standard unit, instead it is correct to use Celsius degrees. * If you for some reason persist to use it, than is sensible to define them as part od `siunitx` package: ``` \documentclass{article} \usepackage{siunitx} % <--- \DeclareSIUnit{\fahrenheit}{^\circ\mkern-1mu\mathrm{F}} % <--- \begin{document} proposed solution: \qty{350}{\fahrenheit}; by your solution: 350$^\circ$F \end{document} ``` since its use gives typographical more correct form than it would be with your intended definition: [![enter image description here](https://i.stack.imgur.com/d2egd.png)](https://i.stack.imgur.com/d2egd.png)
With `\newcommand`, I get ``` ! LaTeX Error: Command \deg already defined. Or name \end... illegal, see p.192 of the manual. ``` which I'm assuming you ignored when running with that version of the command. `\deg` is one of the text operator symbols provided by LaTeX. It's used in graph theory to say things like > > βˆ‘*v* ∈ *V* deg(*v*) = 2|*E*| > > > When you ran past the error, `\deg` was not redefined but instead you got the original math command and thus the error. When I changed to `\renewcommand` I didn't get the error.
606,293
I don't see why the custom (temperature) command `\newcommand{\deg}{$^\circ$F}` returns a `"missing $ inserted"` error when writing something like `350\deg` in text mode. More confusingly, it compiles if I use `\renewcommand`, suggesting the command name `\deg` has already been used. But the same error is returned no matter the command name.
2021/07/25
[ "https://tex.stackexchange.com/questions/606293", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/35910/" ]
With `\newcommand`, I get ``` ! LaTeX Error: Command \deg already defined. Or name \end... illegal, see p.192 of the manual. ``` which I'm assuming you ignored when running with that version of the command. `\deg` is one of the text operator symbols provided by LaTeX. It's used in graph theory to say things like > > βˆ‘*v* ∈ *V* deg(*v*) = 2|*E*| > > > When you ran past the error, `\deg` was not redefined but instead you got the original math command and thus the error. When I changed to `\renewcommand` I didn't get the error.
You can use also `gensymb` package or `siunitx` as this example without to declare a predefinite command named `\deg`. ``` \documentclass[12pt]{article} \usepackage{amsmath} \usepackage{siunitx} \usepackage{gensymb} \begin{document} Your angle is \ang{350} (siunitx package) or 350{\degree} (gensymb package). \end{document} ``` [![enter image description here](https://i.stack.imgur.com/mm71l.png)](https://i.stack.imgur.com/mm71l.png) The MWE work also in math-mode: `$\ang{350}$, $350{\degree}$`.
606,293
I don't see why the custom (temperature) command `\newcommand{\deg}{$^\circ$F}` returns a `"missing $ inserted"` error when writing something like `350\deg` in text mode. More confusingly, it compiles if I use `\renewcommand`, suggesting the command name `\deg` has already been used. But the same error is returned no matter the command name.
2021/07/25
[ "https://tex.stackexchange.com/questions/606293", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/35910/" ]
A bit off-topic, however: * Fahrenheit are not standard unit, instead it is correct to use Celsius degrees. * If you for some reason persist to use it, than is sensible to define them as part od `siunitx` package: ``` \documentclass{article} \usepackage{siunitx} % <--- \DeclareSIUnit{\fahrenheit}{^\circ\mkern-1mu\mathrm{F}} % <--- \begin{document} proposed solution: \qty{350}{\fahrenheit}; by your solution: 350$^\circ$F \end{document} ``` since its use gives typographical more correct form than it would be with your intended definition: [![enter image description here](https://i.stack.imgur.com/d2egd.png)](https://i.stack.imgur.com/d2egd.png)
You can use also `gensymb` package or `siunitx` as this example without to declare a predefinite command named `\deg`. ``` \documentclass[12pt]{article} \usepackage{amsmath} \usepackage{siunitx} \usepackage{gensymb} \begin{document} Your angle is \ang{350} (siunitx package) or 350{\degree} (gensymb package). \end{document} ``` [![enter image description here](https://i.stack.imgur.com/mm71l.png)](https://i.stack.imgur.com/mm71l.png) The MWE work also in math-mode: `$\ang{350}$, $350{\degree}$`.
553,857
I need to create a PCB with a transformer on it, and in this case, I unfortunately can't solder on a regular one. I was wondering if there was anything akin to a 2d transformer, or just generally a coil I could print onto my PCB. I know that spirals are used in Radio-Applications, but I'm not sure if you could use something like this as a regular coil.
2021/03/18
[ "https://electronics.stackexchange.com/questions/553857", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/232664/" ]
They are called "Planar transformers" and they are used in the Telecom industry. <https://www.electronicproducts.com/wp-content/uploads/passive-components-magnetics-inductors-transformers-wcjh-1s-jan201618.jpg> They need a multi-layer PCB because the windings are PCB traces. In the following picture you can see the multi-layer structure of the PCB. I saw, time ago, a planar transformer printed on a 24-layer PCB. <https://upload.wikimedia.org/wikipedia/commons/thumb/5/5e/Planar_Transformer.jpg/1024px-Planar_Transformer.jpg> The soft-ferrite core is than manually added by the worker after the PCB gets populated. Often, they are manufactured and sold as single products. That is, it's very rare that people print planar transformers on the very same PCB of your final product.
Maybe it's a matter of semantics, but what people are calling planar transformers here(or more generally, planar magnetics) we refer to as embedded magnetics. Planar magnetics, as we use the term, is still a discrete component that is mounted to a PCB. What makes it a planar magnetic is that the windings are all in the same plane. The pictures below illustrate this technology. This is an expanded view of a typical planar transformer. [![enter image description here](https://i.stack.imgur.com/0qJMP.png)](https://i.stack.imgur.com/0qJMP.png) It then gets dropped into a cutout in the PCB and the leads solder to pads on the board. See picture below. [![enter image description here](https://i.stack.imgur.com/LzV0P.png)](https://i.stack.imgur.com/LzV0P.png)
24,829,726
I'm attempting to create a simple python function which will return the same value as javascript `new Date().getTime()` method. As written [here](http://www.w3schools.com/js/js_dates.asp), javascript getTime() method returns number of milliseconds from 1/1/1970 So I simply wrote this python function: ``` def jsGetTime(dtime): diff = datetime.datetime(1970,1,1) return (dtime-diff).total_seconds()*1000 ``` while the parameter dtime is a python datetime object. yet I get wrong result. what is the problem with my calculation?
2014/07/18
[ "https://Stackoverflow.com/questions/24829726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3599803/" ]
One thing I feel compelled to point out here is: If you are trying to sync your client time and your server time you are going to need to pass the server time to the client and use that as an offset. Otherwise you are always going to be a bit out of sync as your clients/web-browsers will be running on various machines which have there own clock. However it is a common pattern to reference time in a unified manor using epoch milliseconds to sync between the clients and the server. The Python ``` import time, datetime def now_milliseconds(): return int(time.time() * 1000) # reference time.time # Return the current time in seconds since the Epoch. # Fractions of a second may be present if the system clock provides them. # Note: if your system clock provides fractions of a second you can end up # with results like: 1405821684785.2 # our conversion to an int prevents this def date_time_milliseconds(date_time_obj): return int(time.mktime(date_time_obj.timetuple()) * 1000) # reference: time.mktime() will # Convert a time tuple in local time to seconds since the Epoch. mstimeone = now_milliseconds() mstimetwo = date_time_milliseconds(datetime.datetime.utcnow()) # value of mstimeone # 1405821684785 # value of mstimetwo # 1405839684000 ``` The Javascript ``` d = new Date() d.getTime() ``` See this post for more reference on [javascript date manipulation](https://stackoverflow.com/a/221297/1184492).
Javascript's Date does not work like you expect. But your python code is correct. According to [The epoch time listing](http://www.epochconverter.com/epoch/timestamp-list.php), the epoch time for January 1, 2010 should be > > 1262304000 > > > Python: (appears to be correct) ``` >>> (datetime(2010,1,1) - datetime(1970,1,1)).total_seconds() 1262304000.0 ``` Javascript (appears to be wrong) ``` > new Date(2010,1,1).getTime() 1265011200000 ``` or ``` > new Date(2010,1,1).getTime()/1000 1265011200 ``` This is because Javascript date is not creating the date the way you expect. First, it creates the date in your current timezone, and not in UTC. So a "get current time" in javascript would be the clients time, whereas python would return the utc time. Also note that there is a bug in JS Date where the month is actually 0 based and not 1 based. ``` > new Date(2010,1,1,0,0,0,0) Date 2010-02-01T08:00:00.000Z > new Date(2010,0,1,0,0,0,0) Date 2010-01-01T08:00:00.000Z ``` Javascript can create a date from an epoch time: ``` > new Date(1262304000000) Date 2010-01-01T00:00:00.000Z ``` Which is correct. **Alternatively you could use the following JS function to get a more accurate time** please note that the month still starts at 0 and not 1 ``` > Date.UTC(2010,0,1) 1262304000000 ```
6,697,220
I'm writing a simple eclipse plugin, which is a code generator. User can choose an existing method, then generate a new test method in corresponding test file, with JDT. Assume the test files is already existed, and it's content is: ``` public class UserTest extends TestCase { public void setUp(){} public void tearDown(){} public void testCtor(){} } ``` Now I have generate some test code: ``` /** complex javadoc */ public void testSetName() { .... // complex logic } ``` What I want to do is to append it to the existing `UserTest`. I have to code: ``` String sourceContent = FileUtils.readFileToString("UserTest.java", "UTF-8"); ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setSource(content.toCharArray()); CompilationUnit testUnit = (CompilationUnit) parser.createAST(null); String newTestCode = "public void testSetName() { .... }"; // get the first type final List<TypeDeclaration> list = new ArrayList<TypeDeclaration>(); testUnit .accept(new ASTVisitor() { @Override public boolean visit(TypeDeclaration node) { list.add(node); return false; } }); TypeDeclaration type = list.get(0); type.insertMethod(newTestCode); // ! no this method: insertMethod ``` But there is no such a method `insertMethod`. I know two options now: 1. Do not use `jdt`, just to insert the new code to the test file, before last `}` 2. use `testUnit.getAST().newMethodDeclaration()` to create a method, then update it. But I don't like these two options, I hope there is something like `insertMethod`, which can let me append some text to the test compilation unit, or convert the test code to a MethodDeclaration, then append to the test compilation unit. --- **UPDATE** I see [nonty's answer](https://stackoverflow.com/questions/6697220/how-to-add-a-method-source-to-an-existing-java-file-with-jdt/6697997#6697997), and found there are two `CompilationUnit` in jdt. One is `org.eclipse.jdt.internal.core.CompilationUnit`, another is `org.eclipse.jdt.core.dom.CompilationUnit`. I used the second one, and nonty used the first one. I need to supplement my question: At first I want to create a eclipse-plugin, but later I found it hard to create a complex UI by swt, so I decided to create a web app to generate the code. I copied those jdt jars from eclipse, so I can just use `org.eclipse.jdt.core.dom.CompilationUnit`. Is there a way to use `org.eclipse.jdt.internal.core.CompilationUnit` outside eclipse?
2011/07/14
[ "https://Stackoverflow.com/questions/6697220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342235/" ]
A MS SQL Server version... ``` WITH sorted_data AS ( SELECT ROW_NUMBER() OVER (PARTITION BY item_id ORDER BY item_date DESC) AS row_id, * FROM item_data WHERE item_date <= getDate() ) SELECT * FROM sorted_data WHERE row_id = 1 ```
selct \* from table where This = that Group by something having This. order by date desc. having "THIS" should be in the query itself. hope this helps.. Cheers
60,190,666
I am just playing around with the setInterval function in JavaScript. I am wondering if there is a way to toggle the setInterval with an HTML button This is my code. ``` let x = 0; const listener = document.getElementById('listener'); const numberPlace = document.getElementById('numberPlace'); const numberCounter = setInterval(() => { x++; numberPlace.innerHTML = x; }, 100); listener.addEventListener('click', numberCounter); ``` The problem is that the number starts counting when the page loads and not on a button click. Please help
2020/02/12
[ "https://Stackoverflow.com/questions/60190666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12322204/" ]
``` const numberCounter = () => setInterval(() => { x++; numberPlace.innerHTML = x; }, 100); ```
[`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) can be cancelled using [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) and the integer identifier returned when `setInterval` was called. To toggle a `setInterval`-based counter, you simply need to toggle on the presence (or absence) of this identifier. ```js let counter = 0; let intervalId = null; const btn = document.getElementById('btn'); const numberPlace = document.getElementById('numberPlace'); const numberCounter = () => intervalId === null ? intervalId = setInterval(() => numberPlace.innerHTML = ++counter, 100) : (clearInterval(intervalId), intervalId = null) btn.addEventListener('click', numberCounter); ``` ```html <button id="btn">toggle</button> <div id="numberPlace"></div> ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
Apparently this is not possible. This behaviour is supported by GNU getopt() (`man getopt`, `man 3 getopt`). `man getopt` says: > > If the [long] option has an optional argument, it must be written directly after the long option name, separated by '=', if present > > > The Python `getopt` module, however, is clear that it doesn't support this: > > Optional arguments [in long options] are not supported. > > > For `argparse` I don't find any specific reference in the manual, but I would be surprised if it supported it. In fact, I'm surprised GNU getopt supports it and that `ls` works the way you described. User interfaces should be simple, and this behaviour is far from simple.
maybe `nargs` would be help. ``` >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--color', nargs='?', const='c', default='d') >>> parser.parse_args(['XX', '--color', 'always']) Namespace(bar='XX', color='always') >>> parser.parse_args(['XX', '--color']) Namespace(bar='XX', color='c') >>> parser.parse_args([]) Namespace(bar='d', color='d') ``` with nargs, you get different args and you will know what the input type is. by the way, I think `--color` option could use `action='store_true'`. ``` parser.add_argument('--color', action='store_true') ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
Here's a workaround: ``` #!/usr/bin/python import argparse parser = argparse.ArgumentParser() parser.add_argument("files", nargs="*", help="List of files", type=str) parser.add_argument('--color', dest='color', action='store_true') parser.add_argument('--color=ALWAYS', dest='color_always', action='store_true') args = parser.parse_args() print args ``` Results: ``` [~]$ ./test.py xyz --color Namespace(color=True, color_always=False, files=['xyz']) [~]$ ./test.py xyz --color=ALWAYS Namespace(color=False, color_always=True, files=['xyz']) ```
maybe `nargs` would be help. ``` >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--color', nargs='?', const='c', default='d') >>> parser.parse_args(['XX', '--color', 'always']) Namespace(bar='XX', color='always') >>> parser.parse_args(['XX', '--color']) Namespace(bar='XX', color='c') >>> parser.parse_args([]) Namespace(bar='d', color='d') ``` with nargs, you get different args and you will know what the input type is. by the way, I think `--color` option could use `action='store_true'`. ``` parser.add_argument('--color', action='store_true') ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
You've probably already tried the `?` optional followed by required positional: ``` p=argparse.ArgumentParser() p.add_argument('--foo', nargs='?',default='one', const='two') p.add_argument('bar') ``` which fails with ``` In [7]: p.parse_args('--foo 1'.split()) usage: ipython3 [-h] [--foo [FOO]] bar ipython3: error: the following arguments are required: bar ``` `--foo` consumes the `1`, leaving nothing for `bar`. <http://bugs.python.org/issue9338> discusses this issue. The `nargs='?'` is greedy, consuming an argument, even though the following positional requires one. But the suggested patch is complicated, so I can't quickly apply it to a parser and test your case. The idea of defining an Action that would work with `--foo==value`, but not consume `value` in `--foo value`, is interesting, but I have no idea of what it would take to implement. Certainly it doesn't work with the current parser. I'd have to review how it handles that explicit `=`. ============================ By changing a deeply nested function in `parse_args`, ``` def consume_optional(....): .... # error if a double-dash option did not use the # explicit argument else: msg = _('ignored explicit argument %r') #raise ArgumentError(action, msg % explicit_arg) # change for stack40989413 print('Warn ',msg) stop = start_index + 1 args = [explicit_arg] action.nargs=None action_tuples.append((action, args, option_string)) break ``` and adding a custom Action class: ``` class MyAction(myparse._StoreConstAction): # requies change in consume_optional def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, self.dest, values) else: setattr(namespace, self.dest, self.const) ``` I can get the desired behavior from: ``` p = myparse.ArgumentParser() p.add_argument('--foo', action=MyAction, const='C', default='D') p.add_argument('bar') ``` Basically I'm modifying `store_const` to save the `=explicit_arg` if present. I don't plan on proposing this as a formal patch, but I'd welcome feedback if it is useful. Use at your own risk. :)
maybe `nargs` would be help. ``` >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--color', nargs='?', const='c', default='d') >>> parser.parse_args(['XX', '--color', 'always']) Namespace(bar='XX', color='always') >>> parser.parse_args(['XX', '--color']) Namespace(bar='XX', color='c') >>> parser.parse_args([]) Namespace(bar='d', color='d') ``` with nargs, you get different args and you will know what the input type is. by the way, I think `--color` option could use `action='store_true'`. ``` parser.add_argument('--color', action='store_true') ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
**Problemo solved!** It's a bit (a lot) hacky, but here you go. The solution revolves around a class that inherits \_StoreConstAction and tweaks it a little, but mainly tricks the help formatter when it tries to get its attributes. I tested this in python3 under windows and linux. ```py import argparse import inspect class GnuStyleLongOption(argparse._StoreConstAction): def __init__(self, **kw): self._real_option_strings = kw['option_strings'] opts = [] for option_string in self._real_option_strings: opts.append(option_string) for choice in kw['choices']: opts.append(f'{option_string}={choice}') kw['option_strings'] = opts self.choices = kw.pop('choices') help_choices = [f"'{choice}'" for choice in self.choices] kw['help'] += f"; {kw['metavar']} is {', or '.join([', '.join(help_choices[:-1]), help_choices[-1]])}" super(GnuStyleLongOption, self).__init__(**kw) def __getattribute__(self, attr): caller_is_argparse_help = False for frame in inspect.stack(): if frame.function == 'format_help' and frame.filename.endswith('argparse.py'): caller_is_argparse_help = True break if caller_is_argparse_help: if attr == 'option_strings': return [f'{i}[=WHEN]' for i in self._real_option_strings] if attr == 'nargs': return 0 if attr == 'metavar': return None return super(GnuStyleLongOption, self).__getattribute__(attr) def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, self.const if '=' not in option_string else option_string[option_string.find('=') + 1:]) p = argparse.ArgumentParser() p.add_argument('--color', '--colour', action=GnuStyleLongOption, choices=['always', 'never', 'auto'], const='always', default='auto', help='use markers to highlight whatever we want', metavar='WHEN') p.add_argument('filenames', metavar='filename', nargs='*', help='file to process') args = p.parse_args() print(f'color = {args.color}, filenames = {args.filenames}') ``` Results: ``` ~ $ ./gnu_argparse.py --help usage: gnu_argparse.py [-h] [--color[=WHEN]] [filename [filename ...]] positional arguments: filename file to process optional arguments: -h, --help show this help message and exit --color[=WHEN], --colour[=WHEN] use markers to highlight whatever we want; WHEN is 'always', 'never', or 'auto' ~ $ ./gnu_argparse.py color = auto, filenames = [] ~ $ ./gnu_argparse.py file color = auto, filenames = ['file'] ~ $ ./gnu_argparse.py --color file color = always, filenames = ['file'] ~ $ ./gnu_argparse.py --color never file color = always, filenames = ['never', 'file'] ~ $ ./gnu_argparse.py --color=never file color = never, filenames = ['file'] ~ $ ./gnu_argparse.py --colour=always file color = always, filenames = ['file'] ```
maybe `nargs` would be help. ``` >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--color', nargs='?', const='c', default='d') >>> parser.parse_args(['XX', '--color', 'always']) Namespace(bar='XX', color='always') >>> parser.parse_args(['XX', '--color']) Namespace(bar='XX', color='c') >>> parser.parse_args([]) Namespace(bar='d', color='d') ``` with nargs, you get different args and you will know what the input type is. by the way, I think `--color` option could use `action='store_true'`. ``` parser.add_argument('--color', action='store_true') ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
Apparently this is not possible. This behaviour is supported by GNU getopt() (`man getopt`, `man 3 getopt`). `man getopt` says: > > If the [long] option has an optional argument, it must be written directly after the long option name, separated by '=', if present > > > The Python `getopt` module, however, is clear that it doesn't support this: > > Optional arguments [in long options] are not supported. > > > For `argparse` I don't find any specific reference in the manual, but I would be surprised if it supported it. In fact, I'm surprised GNU getopt supports it and that `ls` works the way you described. User interfaces should be simple, and this behaviour is far from simple.
Here's a workaround: ``` #!/usr/bin/python import argparse parser = argparse.ArgumentParser() parser.add_argument("files", nargs="*", help="List of files", type=str) parser.add_argument('--color', dest='color', action='store_true') parser.add_argument('--color=ALWAYS', dest='color_always', action='store_true') args = parser.parse_args() print args ``` Results: ``` [~]$ ./test.py xyz --color Namespace(color=True, color_always=False, files=['xyz']) [~]$ ./test.py xyz --color=ALWAYS Namespace(color=False, color_always=True, files=['xyz']) ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
You've probably already tried the `?` optional followed by required positional: ``` p=argparse.ArgumentParser() p.add_argument('--foo', nargs='?',default='one', const='two') p.add_argument('bar') ``` which fails with ``` In [7]: p.parse_args('--foo 1'.split()) usage: ipython3 [-h] [--foo [FOO]] bar ipython3: error: the following arguments are required: bar ``` `--foo` consumes the `1`, leaving nothing for `bar`. <http://bugs.python.org/issue9338> discusses this issue. The `nargs='?'` is greedy, consuming an argument, even though the following positional requires one. But the suggested patch is complicated, so I can't quickly apply it to a parser and test your case. The idea of defining an Action that would work with `--foo==value`, but not consume `value` in `--foo value`, is interesting, but I have no idea of what it would take to implement. Certainly it doesn't work with the current parser. I'd have to review how it handles that explicit `=`. ============================ By changing a deeply nested function in `parse_args`, ``` def consume_optional(....): .... # error if a double-dash option did not use the # explicit argument else: msg = _('ignored explicit argument %r') #raise ArgumentError(action, msg % explicit_arg) # change for stack40989413 print('Warn ',msg) stop = start_index + 1 args = [explicit_arg] action.nargs=None action_tuples.append((action, args, option_string)) break ``` and adding a custom Action class: ``` class MyAction(myparse._StoreConstAction): # requies change in consume_optional def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, self.dest, values) else: setattr(namespace, self.dest, self.const) ``` I can get the desired behavior from: ``` p = myparse.ArgumentParser() p.add_argument('--foo', action=MyAction, const='C', default='D') p.add_argument('bar') ``` Basically I'm modifying `store_const` to save the `=explicit_arg` if present. I don't plan on proposing this as a formal patch, but I'd welcome feedback if it is useful. Use at your own risk. :)
Apparently this is not possible. This behaviour is supported by GNU getopt() (`man getopt`, `man 3 getopt`). `man getopt` says: > > If the [long] option has an optional argument, it must be written directly after the long option name, separated by '=', if present > > > The Python `getopt` module, however, is clear that it doesn't support this: > > Optional arguments [in long options] are not supported. > > > For `argparse` I don't find any specific reference in the manual, but I would be surprised if it supported it. In fact, I'm surprised GNU getopt supports it and that `ls` works the way you described. User interfaces should be simple, and this behaviour is far from simple.
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
Apparently this is not possible. This behaviour is supported by GNU getopt() (`man getopt`, `man 3 getopt`). `man getopt` says: > > If the [long] option has an optional argument, it must be written directly after the long option name, separated by '=', if present > > > The Python `getopt` module, however, is clear that it doesn't support this: > > Optional arguments [in long options] are not supported. > > > For `argparse` I don't find any specific reference in the manual, but I would be surprised if it supported it. In fact, I'm surprised GNU getopt supports it and that `ls` works the way you described. User interfaces should be simple, and this behaviour is far from simple.
**Problemo solved!** It's a bit (a lot) hacky, but here you go. The solution revolves around a class that inherits \_StoreConstAction and tweaks it a little, but mainly tricks the help formatter when it tries to get its attributes. I tested this in python3 under windows and linux. ```py import argparse import inspect class GnuStyleLongOption(argparse._StoreConstAction): def __init__(self, **kw): self._real_option_strings = kw['option_strings'] opts = [] for option_string in self._real_option_strings: opts.append(option_string) for choice in kw['choices']: opts.append(f'{option_string}={choice}') kw['option_strings'] = opts self.choices = kw.pop('choices') help_choices = [f"'{choice}'" for choice in self.choices] kw['help'] += f"; {kw['metavar']} is {', or '.join([', '.join(help_choices[:-1]), help_choices[-1]])}" super(GnuStyleLongOption, self).__init__(**kw) def __getattribute__(self, attr): caller_is_argparse_help = False for frame in inspect.stack(): if frame.function == 'format_help' and frame.filename.endswith('argparse.py'): caller_is_argparse_help = True break if caller_is_argparse_help: if attr == 'option_strings': return [f'{i}[=WHEN]' for i in self._real_option_strings] if attr == 'nargs': return 0 if attr == 'metavar': return None return super(GnuStyleLongOption, self).__getattribute__(attr) def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, self.const if '=' not in option_string else option_string[option_string.find('=') + 1:]) p = argparse.ArgumentParser() p.add_argument('--color', '--colour', action=GnuStyleLongOption, choices=['always', 'never', 'auto'], const='always', default='auto', help='use markers to highlight whatever we want', metavar='WHEN') p.add_argument('filenames', metavar='filename', nargs='*', help='file to process') args = p.parse_args() print(f'color = {args.color}, filenames = {args.filenames}') ``` Results: ``` ~ $ ./gnu_argparse.py --help usage: gnu_argparse.py [-h] [--color[=WHEN]] [filename [filename ...]] positional arguments: filename file to process optional arguments: -h, --help show this help message and exit --color[=WHEN], --colour[=WHEN] use markers to highlight whatever we want; WHEN is 'always', 'never', or 'auto' ~ $ ./gnu_argparse.py color = auto, filenames = [] ~ $ ./gnu_argparse.py file color = auto, filenames = ['file'] ~ $ ./gnu_argparse.py --color file color = always, filenames = ['file'] ~ $ ./gnu_argparse.py --color never file color = always, filenames = ['never', 'file'] ~ $ ./gnu_argparse.py --color=never file color = never, filenames = ['file'] ~ $ ./gnu_argparse.py --colour=always file color = always, filenames = ['file'] ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
You've probably already tried the `?` optional followed by required positional: ``` p=argparse.ArgumentParser() p.add_argument('--foo', nargs='?',default='one', const='two') p.add_argument('bar') ``` which fails with ``` In [7]: p.parse_args('--foo 1'.split()) usage: ipython3 [-h] [--foo [FOO]] bar ipython3: error: the following arguments are required: bar ``` `--foo` consumes the `1`, leaving nothing for `bar`. <http://bugs.python.org/issue9338> discusses this issue. The `nargs='?'` is greedy, consuming an argument, even though the following positional requires one. But the suggested patch is complicated, so I can't quickly apply it to a parser and test your case. The idea of defining an Action that would work with `--foo==value`, but not consume `value` in `--foo value`, is interesting, but I have no idea of what it would take to implement. Certainly it doesn't work with the current parser. I'd have to review how it handles that explicit `=`. ============================ By changing a deeply nested function in `parse_args`, ``` def consume_optional(....): .... # error if a double-dash option did not use the # explicit argument else: msg = _('ignored explicit argument %r') #raise ArgumentError(action, msg % explicit_arg) # change for stack40989413 print('Warn ',msg) stop = start_index + 1 args = [explicit_arg] action.nargs=None action_tuples.append((action, args, option_string)) break ``` and adding a custom Action class: ``` class MyAction(myparse._StoreConstAction): # requies change in consume_optional def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, self.dest, values) else: setattr(namespace, self.dest, self.const) ``` I can get the desired behavior from: ``` p = myparse.ArgumentParser() p.add_argument('--foo', action=MyAction, const='C', default='D') p.add_argument('bar') ``` Basically I'm modifying `store_const` to save the `=explicit_arg` if present. I don't plan on proposing this as a formal patch, but I'd welcome feedback if it is useful. Use at your own risk. :)
Here's a workaround: ``` #!/usr/bin/python import argparse parser = argparse.ArgumentParser() parser.add_argument("files", nargs="*", help="List of files", type=str) parser.add_argument('--color', dest='color', action='store_true') parser.add_argument('--color=ALWAYS', dest='color_always', action='store_true') args = parser.parse_args() print args ``` Results: ``` [~]$ ./test.py xyz --color Namespace(color=True, color_always=False, files=['xyz']) [~]$ ./test.py xyz --color=ALWAYS Namespace(color=False, color_always=True, files=['xyz']) ```
40,989,468
Once the cognito-id is created for a user logging via. google, how to find the email id of the user. [![enter image description here](https://i.stack.imgur.com/hN8s7.png)](https://i.stack.imgur.com/hN8s7.png) As shown in the above picture, I can find the cognito-id, but couldn't find any other information that google could have supplied when the user logged in. Any help is appreciated. Thanks in advance,
2016/12/06
[ "https://Stackoverflow.com/questions/40989468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1422950/" ]
You've probably already tried the `?` optional followed by required positional: ``` p=argparse.ArgumentParser() p.add_argument('--foo', nargs='?',default='one', const='two') p.add_argument('bar') ``` which fails with ``` In [7]: p.parse_args('--foo 1'.split()) usage: ipython3 [-h] [--foo [FOO]] bar ipython3: error: the following arguments are required: bar ``` `--foo` consumes the `1`, leaving nothing for `bar`. <http://bugs.python.org/issue9338> discusses this issue. The `nargs='?'` is greedy, consuming an argument, even though the following positional requires one. But the suggested patch is complicated, so I can't quickly apply it to a parser and test your case. The idea of defining an Action that would work with `--foo==value`, but not consume `value` in `--foo value`, is interesting, but I have no idea of what it would take to implement. Certainly it doesn't work with the current parser. I'd have to review how it handles that explicit `=`. ============================ By changing a deeply nested function in `parse_args`, ``` def consume_optional(....): .... # error if a double-dash option did not use the # explicit argument else: msg = _('ignored explicit argument %r') #raise ArgumentError(action, msg % explicit_arg) # change for stack40989413 print('Warn ',msg) stop = start_index + 1 args = [explicit_arg] action.nargs=None action_tuples.append((action, args, option_string)) break ``` and adding a custom Action class: ``` class MyAction(myparse._StoreConstAction): # requies change in consume_optional def __call__(self, parser, namespace, values, option_string=None): if values: setattr(namespace, self.dest, values) else: setattr(namespace, self.dest, self.const) ``` I can get the desired behavior from: ``` p = myparse.ArgumentParser() p.add_argument('--foo', action=MyAction, const='C', default='D') p.add_argument('bar') ``` Basically I'm modifying `store_const` to save the `=explicit_arg` if present. I don't plan on proposing this as a formal patch, but I'd welcome feedback if it is useful. Use at your own risk. :)
**Problemo solved!** It's a bit (a lot) hacky, but here you go. The solution revolves around a class that inherits \_StoreConstAction and tweaks it a little, but mainly tricks the help formatter when it tries to get its attributes. I tested this in python3 under windows and linux. ```py import argparse import inspect class GnuStyleLongOption(argparse._StoreConstAction): def __init__(self, **kw): self._real_option_strings = kw['option_strings'] opts = [] for option_string in self._real_option_strings: opts.append(option_string) for choice in kw['choices']: opts.append(f'{option_string}={choice}') kw['option_strings'] = opts self.choices = kw.pop('choices') help_choices = [f"'{choice}'" for choice in self.choices] kw['help'] += f"; {kw['metavar']} is {', or '.join([', '.join(help_choices[:-1]), help_choices[-1]])}" super(GnuStyleLongOption, self).__init__(**kw) def __getattribute__(self, attr): caller_is_argparse_help = False for frame in inspect.stack(): if frame.function == 'format_help' and frame.filename.endswith('argparse.py'): caller_is_argparse_help = True break if caller_is_argparse_help: if attr == 'option_strings': return [f'{i}[=WHEN]' for i in self._real_option_strings] if attr == 'nargs': return 0 if attr == 'metavar': return None return super(GnuStyleLongOption, self).__getattribute__(attr) def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, self.const if '=' not in option_string else option_string[option_string.find('=') + 1:]) p = argparse.ArgumentParser() p.add_argument('--color', '--colour', action=GnuStyleLongOption, choices=['always', 'never', 'auto'], const='always', default='auto', help='use markers to highlight whatever we want', metavar='WHEN') p.add_argument('filenames', metavar='filename', nargs='*', help='file to process') args = p.parse_args() print(f'color = {args.color}, filenames = {args.filenames}') ``` Results: ``` ~ $ ./gnu_argparse.py --help usage: gnu_argparse.py [-h] [--color[=WHEN]] [filename [filename ...]] positional arguments: filename file to process optional arguments: -h, --help show this help message and exit --color[=WHEN], --colour[=WHEN] use markers to highlight whatever we want; WHEN is 'always', 'never', or 'auto' ~ $ ./gnu_argparse.py color = auto, filenames = [] ~ $ ./gnu_argparse.py file color = auto, filenames = ['file'] ~ $ ./gnu_argparse.py --color file color = always, filenames = ['file'] ~ $ ./gnu_argparse.py --color never file color = always, filenames = ['never', 'file'] ~ $ ./gnu_argparse.py --color=never file color = never, filenames = ['file'] ~ $ ./gnu_argparse.py --colour=always file color = always, filenames = ['file'] ```
48,855,223
I have tried to remove the issue by installing tether.js and utils.js, it seems when I fix one error 2 more pop up. Here is a link to a similar post but I'm having a slightly different issue, this issue that I'm having spawned out of the previous problem. Is there anything I can do? Or should I just revert back to boostrap3 [how to fix the error bootstrap tooltips require tether HTTP github](https://stackoverflow.com/questions/34567939/how-to-fix-the-error-error-bootstrap-tooltips-require-tether-http-github-h/48855088?noredirect=1#comment84713688_48855088) ``` tether.js:1 Uncaught SyntaxError: Identifier 'getScrollParents' has already been declared at tether.js:1 Uncaught Error: Bootstrap tooltips require Tether (http://tether.io/) at bootstrap.min.js?ver=3.0.0:7 at bootstrap.min.js?ver=3.0.0:7 at bootstrap.min.js?ver=3.0.0:7 ```
2018/02/18
[ "https://Stackoverflow.com/questions/48855223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7989522/" ]
You can use `ViewChildren` to reference the inputs based on index. Add template ref `#inputs` to your input field: ```html <ion-input #inputs type="text"></ion-input> ``` In your component import `ViewChildren` and `QueryList` and... ```ts @ViewChildren('inputs') inputs: QueryList<any>; ``` Then on your button click, where you call `doSomething`, in the code you presented, pass the index and set the focus on that field based on index: ```html <ion-row formArrayName="bicos" *ngFor="let item of homeForm.controls.bicos.controls; let i = index" > <button ion-button (click) = "doSomething(i)"> <!-- ... --> ``` TS: ```ts doSomething(index) { this.inputs.toArray()[index].setFocus(); } ``` [StackBlitz](https://stackblitz.com/edit/ionic-3gwv6g?file=pages%2Fhome%2Fhome.ts) ----------------------------------------------------------------------------------
I'm using Ionic 5. Here is my solution using the input element's id. **in the .html:** ``` <input id="input_{{ listItem?.id }}"> </input> ``` **in the .ts file:** ``` import { Renderer2 } from '@angular/core'; constructor(private renderer: Renderer2) ``` **at the point in the .ts file you want to focus the required input:** ``` setTimeout(() => { this.renderer .selectRootElement(`#input_${listItem.id}`) .focus(); }, 1000); ```
41,468,745
I want to run a function based on a $scope value. In my controller, I have: ``` $scope.value = ""; $scope.selector = function(info) { if ($scope.value === "") { $scope.value = info; } else { $scope.value = ""; } } ``` The function is triggered on ng-click of different images, e.g.: `<img ng-src="..." ng-click="selector(info)">` My problem is the if-operations dont seem to work on the $scope value. I have also tried: ``` $scope.$watch('value', function(val) { if(val === "") { $scope.value = info; } } ``` This works if it is outside a function, but not if I place it in the selector function. Better approaches always welcome. Thanks for any explanations.
2017/01/04
[ "https://Stackoverflow.com/questions/41468745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5919010/" ]
Here is a version of your code. It is a little shorter and probably more straightforward. Also it returns exactly the same result as in the example. ``` let // Data source SourceTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], Data = Table.TransformColumnTypes(SourceTable,{{"Role", type text}, {"From", type datetime}, {"To", type datetime}, {"Value", Int64.Type}}), //Get a list of roles. // Roles = {"A", "B", "C", "D"}, //Example line. Comment it Roles = List.Transform(Table.Distinct(Table.SelectColumns(SourceTable, {"Role"}))[Role], each Text.Trim(Text.Upper(_))), // Create table of all possible intervals UnionTables = Table.TransformColumnTypes( Table.Combine({ Table.SelectColumns(SourceTable, "From"), Table.SelectColumns(Table.AddColumn(Table.SelectColumns(SourceTable, "To"), "From", each Date.AddDays([To], 1)), {"From"}) //Add 1 day to ensure next interval starts at the same date to produce no fake 1-day intervals }), {{"From", type datetime}}), SortDates = Table.Sort(Table.Distinct(UnionTables), {{"From", Order.Ascending}}), AddIndex = Table.AddIndexColumn(SortDates, "Index", 0, 1), AllIntervals = Table.RemoveRowsWithErrors(Table.AddColumn(AddIndex, "To", each Date.AddDays(AddIndex[From]{[Index] + 1}, -1), type datetime)), //Substract 1 day to revert intervals to their original values AddColumns = Table.Combine(List.Transform(Roles, (Role) => Table.AddColumn(Table.SelectColumns(AllIntervals, {"From", "To"}), Role, (x) => List.Sum(Table.SelectRows(Data, (y) => Text.Upper(Text.Trim(y[Role])) = Role and ((y[From] >= x[From] and y[To] <= x[To]) or (y[From] <= x[From] and y[To] >= x[To])))[Value]), type number))), GetDistinctRows = Table.Distinct(AddColumns), FilterOutNulls = Table.SelectRows(GetDistinctRows, each List.MatchesAny(Record.FieldValues(Record.SelectFields(_, Roles)), (x) => x <> null) /*List.Match(Table.ColumnNames(AddColumns), Roles) <> null*/), AddSum = Table.AddColumn(FilterOutNulls, "Sum", each List.Sum(Record.FieldValues(Record.SelectFields(_, Roles)))), ListOfNonNullColumns = List.Select( List.Transform(Roles, (x) => if ( Table.RowCount( Table.SelectRows(AddSum, (y) => List.Sum( Record.FieldValues( Record.SelectFields(y, {x}) ) ) > 0 ) ) ) > 0 then x else null) , each _ <> null), CleanAndReorder = Table.SelectColumns(AddSum, List.Combine({{"From", "To"}, ListOfNonNullColumns, {"Sum"}})), DemoteHeaders = Table.DemoteHeaders(CleanAndReorder), Result = Table.Transpose(DemoteHeaders) in Result ```
I figured out one way to do it, code in M for power query below with comments on individual steps: ``` let // Data source SourceTable = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], Data = Table.TransformColumnTypes(SourceTable,{{"Role", type text}, {"From", type datetime}, {"To", type datetime}, {"Value", Int64.Type}}), // Create table of all possible intervals AllDates = Table.Sort( Table.Distinct( Table.Combine({ Table.RenameColumns(Table.SelectColumns(SourceTable, "From"), {"From", "Date"}), Table.RenameColumns(Table.SelectColumns(SourceTable, "To"), {"To", "Date"}) }) ), {{"Date", Order.Ascending}} ), RenameFrom = Table.RenameColumns( Table.AddIndexColumn(AllDates, "Index", 0, 1), {"Date", "From"} ), AllIntervals = Table.RemoveRowsWithErrors( Table.AddColumn(RenameFrom, "To", each RenameFrom[From]{[Index] + 1})), // Join Data with all possible intervals InsertedCustom = Table.AddColumn(Data, "temp", each AllIntervals), ExpandedTable = Table.ExpandTableColumn(InsertedCustom, "temp", { "From", "To" }, { "From2", "To2" }), ExpandedTableWithValidValue = Table.AddColumn(ExpandedTable, "ValidValue", each ( if ([From] < [To2] and [To] > [From2]) then [Value] else 0) ), ExpandedTableRevised = Table.RenameColumns( Table.RemoveColumns (ExpandedTableWithValidValue , { "Value", "From", "To" } ) , { { "ValidValue", "Value" }, {"From2", "From"}, { "To2", "To" } } ), // Group and sum Data #"Grouped Rows" = Table.Group(ExpandedTableRevised, List.RemoveItems(Table.ColumnNames(ExpandedTableRevised), { "Value" } ), {{"Value", each List.Sum([Value]), type number}}), #"Pivoted Column" = Table.Pivot(#"Grouped Rows", List.Distinct(#"Grouped Rows"[Role]), "Role", "Value", List.Sum), #"Summed By Role" = Table.AddColumn(#"Pivoted Column", "Sum", each List.Sum(Record.ToList(Record.RemoveFields(_, { "From", "To" }))) ), // Transpose data with intervals, values and sum to target result structure ResultDataTable = Table.Transpose(#"Summed By Role"), // Create First column with labels for result structure FirstColumnRoles= Table.Distinct(Table.SelectColumns(SourceTable, "Role")), FirstColumnWithFromToLabels = Table.InsertRows(FirstColumnRoles, 0, { [Role="From"], [Role="To"] }), FirstColumnWithSum = Table.InsertRows ( FirstColumnWithFromToLabels , Table.RowCount(FirstColumnWithFromToLabels ), {[Role="Sum"]}), FirstColumn = Table.AddIndexColumn(FirstColumnWithSum , "Index", 0, 1), // Merge First column of labels with data structure and clean up redundant columns ResultTable = Table.RemoveColumns( Table.ReorderColumns( Table.Join( FirstColumn, "Index", Table.AddIndexColumn(ResultDataTable , "Index", 0, 1), "Index"), { "Index", "Role"}), "Index" ), Custom1 = ResultTable in Custom1 ```
24,955,666
I am trying to search within the values (table names) returned from a query to check if there is a record and some values in that record are null. If they are, then I want to insert the table's name to a temporary table. I get an error: ``` Conversion failed when converting the varchar value 'count(*) FROM step_inusd_20130618 WHERE jobDateClosed IS NULL' to data type int. ``` This is the query: ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count SET @sql = 'SELECT * FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --ERROR is below: select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --PRINT @sql -- EXEC(@sql) IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ``` Any ideas how to convert the result of the count into an integer?
2014/07/25
[ "https://Stackoverflow.com/questions/24955666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2280087/" ]
Check for [sp\_executesql](http://msdn.microsoft.com/en-us/library/ms188001.aspx) where you may define output parameters. ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count DECLARE @SQLString nvarchar(500); DECLARE @ParmDefinition nvarchar(500); SET @SQLString = N'SELECT @test = count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' SET @ParmDefinition = N'@test int OUTPUT'; EXECUTE sp_executesql @SQLString, @ParmDefinition, @test=@test OUTPUT; IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ```
Shouldn't be "SET" instead of "select" ? E.g., changing: ``` select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' ``` for: ``` SET @test = 'select count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' ```
24,955,666
I am trying to search within the values (table names) returned from a query to check if there is a record and some values in that record are null. If they are, then I want to insert the table's name to a temporary table. I get an error: ``` Conversion failed when converting the varchar value 'count(*) FROM step_inusd_20130618 WHERE jobDateClosed IS NULL' to data type int. ``` This is the query: ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count SET @sql = 'SELECT * FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --ERROR is below: select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --PRINT @sql -- EXEC(@sql) IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ``` Any ideas how to convert the result of the count into an integer?
2014/07/25
[ "https://Stackoverflow.com/questions/24955666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2280087/" ]
Check for [sp\_executesql](http://msdn.microsoft.com/en-us/library/ms188001.aspx) where you may define output parameters. ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count DECLARE @SQLString nvarchar(500); DECLARE @ParmDefinition nvarchar(500); SET @SQLString = N'SELECT @test = count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' SET @ParmDefinition = N'@test int OUTPUT'; EXECUTE sp_executesql @SQLString, @ParmDefinition, @test=@test OUTPUT; IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ```
As I see, your problem is, that $test variable is INT and you are trying to assign to it the TEXT value 'count ...' Use aproach like: SELECT somevalue INTO myvar FROM mytable WHERE uid=1;
24,955,666
I am trying to search within the values (table names) returned from a query to check if there is a record and some values in that record are null. If they are, then I want to insert the table's name to a temporary table. I get an error: ``` Conversion failed when converting the varchar value 'count(*) FROM step_inusd_20130618 WHERE jobDateClosed IS NULL' to data type int. ``` This is the query: ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count SET @sql = 'SELECT * FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --ERROR is below: select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --PRINT @sql -- EXEC(@sql) IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ``` Any ideas how to convert the result of the count into an integer?
2014/07/25
[ "https://Stackoverflow.com/questions/24955666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2280087/" ]
Check for [sp\_executesql](http://msdn.microsoft.com/en-us/library/ms188001.aspx) where you may define output parameters. ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count DECLARE @SQLString nvarchar(500); DECLARE @ParmDefinition nvarchar(500); SET @SQLString = N'SELECT @test = count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' SET @ParmDefinition = N'@test int OUTPUT'; EXECUTE sp_executesql @SQLString, @ParmDefinition, @test=@test OUTPUT; IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ```
I trimmed out the stuff not needed to show how to do this, so here it is: ``` DECLARE @table_name VARCHAR(150) DECLARE @CountStatement NVARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count SET @CountStatement = 'select @test = count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' EXECUTE sp_executesql @CountStatement, N'@test INT OUTPUT', @test OUTPUT; SELECT @test ```
24,955,666
I am trying to search within the values (table names) returned from a query to check if there is a record and some values in that record are null. If they are, then I want to insert the table's name to a temporary table. I get an error: ``` Conversion failed when converting the varchar value 'count(*) FROM step_inusd_20130618 WHERE jobDateClosed IS NULL' to data type int. ``` This is the query: ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count SET @sql = 'SELECT * FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --ERROR is below: select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --PRINT @sql -- EXEC(@sql) IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ``` Any ideas how to convert the result of the count into an integer?
2014/07/25
[ "https://Stackoverflow.com/questions/24955666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2280087/" ]
Shouldn't be "SET" instead of "select" ? E.g., changing: ``` select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' ``` for: ``` SET @test = 'select count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' ```
As I see, your problem is, that $test variable is INT and you are trying to assign to it the TEXT value 'count ...' Use aproach like: SELECT somevalue INTO myvar FROM mytable WHERE uid=1;
24,955,666
I am trying to search within the values (table names) returned from a query to check if there is a record and some values in that record are null. If they are, then I want to insert the table's name to a temporary table. I get an error: ``` Conversion failed when converting the varchar value 'count(*) FROM step_inusd_20130618 WHERE jobDateClosed IS NULL' to data type int. ``` This is the query: ``` DECLARE @table_name VARCHAR(150) DECLARE @sql VARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count SET @sql = 'SELECT * FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --ERROR is below: select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' --PRINT @sql -- EXEC(@sql) IF @test > 0 BEGIN INSERT INTO #temp2 (tablename) VALUES ( @table_name); END SET @count = @count + 1 ``` Any ideas how to convert the result of the count into an integer?
2014/07/25
[ "https://Stackoverflow.com/questions/24955666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2280087/" ]
Shouldn't be "SET" instead of "select" ? E.g., changing: ``` select @test = 'count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' ``` for: ``` SET @test = 'select count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' ```
I trimmed out the stuff not needed to show how to do this, so here it is: ``` DECLARE @table_name VARCHAR(150) DECLARE @CountStatement NVARCHAR(1000) DECLARE @test int SELECT @table_name = tableName FROM #temp WHERE id = @count SET @CountStatement = 'select @test = count(*) FROM ' + @table_name + ' WHERE jobDateClosed IS NULL' EXECUTE sp_executesql @CountStatement, N'@test INT OUTPUT', @test OUTPUT; SELECT @test ```
34,128,799
I have created Azure website ,and upload all OPIGNO files to that website via FTP,so when i am trying to access the `index.php` for OPIGNO project ,it returns **server error 500**????
2015/12/07
[ "https://Stackoverflow.com/questions/34128799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
1. uninstall Cloud Foundry command line... 2. delete your $HOME/.cf/\* 3. run cf installer -- install it to default C: drive download the latest version here: <https://github.com/cloudfoundry/cli/releases>
It seems that the server don't allow you to connect. I remember that I had problems connecting to the USA API. I didn't face the same problem, however, try to connect to the UK API. Change the region in Bluemix UI and use the following command: ``` cf api https://api.eu-gb.bluemix.net ```
34,128,799
I have created Azure website ,and upload all OPIGNO files to that website via FTP,so when i am trying to access the `index.php` for OPIGNO project ,it returns **server error 500**????
2015/12/07
[ "https://Stackoverflow.com/questions/34128799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
1. uninstall Cloud Foundry command line... 2. delete your $HOME/.cf/\* 3. run cf installer -- install it to default C: drive download the latest version here: <https://github.com/cloudfoundry/cli/releases>
As you can see on the [Bluemix Status Page](https://developer.ibm.com/bluemix/support/#status) recently we experienced some issues during login (both via cf and UI). However the issues should now be resolved, so I suggest you to verify that you are using the correct api URL before you log in. The API URLs are the following: * US Region: <https://api.ng.bluemix.net> * UK Region: <https://api.eu-gb.bluemix.net> * AU Region: <https://api.au-syd.bluemix.net>
34,128,799
I have created Azure website ,and upload all OPIGNO files to that website via FTP,so when i am trying to access the `index.php` for OPIGNO project ,it returns **server error 500**????
2015/12/07
[ "https://Stackoverflow.com/questions/34128799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
1. uninstall Cloud Foundry command line... 2. delete your $HOME/.cf/\* 3. run cf installer -- install it to default C: drive download the latest version here: <https://github.com/cloudfoundry/cli/releases>
Generally speaking this kind of error is related to a permission issue. It would be worth to check either the Windows firewall or the user permissions.
16,206,173
I'm trying to generate several files so I wrote this code where `value` get **797** but I only get one file created, why? should not be 797 files instead? what's wrong in my code?: ``` private void button3_Click(object sender, EventArgs e) { int value = bdCleanList.Count() / Int32.Parse(textBox7.Text); MessageBox.Show(value.ToString()); string bases_generadas = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bases_generadas"); for (int i = 1; i < value; i++) { string newFileName = "bases_generadas_" + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ".txt"; using (System.IO.FileStream fs = System.IO.File.Create( System.IO.Path.Combine(bases_generadas, newFileName))) { for (byte j = 0; j < 10; j++) { fs.WriteByte(j); } } } } ``` **EDIT** as @andrey-shchekin suggest I added a `i` to `newFileName` so now the code is this one: ``` string newFileName = "bases_generadas_" + i + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ".txt"; ``` But now I run the code again and `value` takes **4** but just 3 files was created: ``` bases_generadas_124-04-2013-11-45-08.txt bases_generadas_224-04-2013-11-45-08.txt bases_generadas_324-04-2013-11-45-08.txt ``` Why?
2013/04/25
[ "https://Stackoverflow.com/questions/16206173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238121/" ]
``` string str = "123.1.1.QWE"; int index = str.LastIndexOf("."); string[] seqNum = new string[] {str.Substring(0, index), str.Substring(index + 1)}; ```
``` string str = "123.1.1.QWE"; string[] seqnum = new string[2]; foreach (char ch in str) { if (char.IsNumber(ch) || ch == '.') { } else { int indx = str.IndexOf(ch); seqnum[0] = str.Substring(0, indx).ToString(); seqnum[1] = str.Substring(indx,str.Length-indx).ToString(); break; } } // output // seqnum[0]=123.1.1. // seqnum[1]=QWE ```
1,547,172
Let $A,B\in M\_n$ and $\left( {\begin{array}{\*{20}{c}} A & B \\ B & A \\ \end{array}} \right) \ge 0$ Why does $A \ge B$ ?
2015/11/26
[ "https://math.stackexchange.com/questions/1547172", "https://math.stackexchange.com", "https://math.stackexchange.com/users/226800/" ]
Let $x$ be given. Then $$ 0\le \pmatrix{x\\-x}^T\pmatrix{A&B\\B&A}\pmatrix{x\\-x} = 2x^TAx - 2x^TBx, $$ This implies $$ x^T(A-B)x\ge0 $$ for all $x$, hence $A\ge B$.
If you take Determinant of the above matrix, it becomes, $A^2-B^2 \ge 0$ Square of any number is positive and to yield the number greater than zero, A should be always greater than B. Hence $A\ge B$
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
The error `There are multiple modules with names that only differ in casing.` is indicating the wrong import is being targeted with how you are trying to use `Observable`. The import should be with a capital "O" like: `import { Observable } from 'rxjs/Observable';` This will import the individual `Observable` operator, which be used in combination with operators such as `catch` or `throw` on created Observables. ``` import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; ``` To import the full Observable object you'd import it like this: `import { Observable } from 'rxjs/Rx'` **Update:** With newer versions of RxJS (5.5+) operators such as `map()` and `filter()` can used as [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) in combination with `pipe()` rather than chaining. They are imported such as: ``` import { filter, map, catchError } from 'rxjs/operators'; ``` Keep in mind terms such as `throw` are reserved/key words in JavaScript so the RxJS `throw` operator is imported as: ``` import { _throw } from 'rxjs/observable/throw'; ``` **Update:** For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
I was facing the same issue in my `angular 5` application. What I did is, adding a new package. ``` import { throwError } from 'rxjs'; import { filter, map, catchError } from 'rxjs/operators'; ``` And from my `http` service call I return a function. ``` return this.http.request(request) .pipe(map((res: Response) => res.json()), catchError((res: Response) => this.onError(res))); ``` And in `onError` function I am returning the error with `throwError(error)`. ``` onError(res: Response) { const statusCode = res.status; const body = res.json(); const error = { statusCode: statusCode, error: body.error }; return throwError(error); } ```
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
The error `There are multiple modules with names that only differ in casing.` is indicating the wrong import is being targeted with how you are trying to use `Observable`. The import should be with a capital "O" like: `import { Observable } from 'rxjs/Observable';` This will import the individual `Observable` operator, which be used in combination with operators such as `catch` or `throw` on created Observables. ``` import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; ``` To import the full Observable object you'd import it like this: `import { Observable } from 'rxjs/Rx'` **Update:** With newer versions of RxJS (5.5+) operators such as `map()` and `filter()` can used as [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) in combination with `pipe()` rather than chaining. They are imported such as: ``` import { filter, map, catchError } from 'rxjs/operators'; ``` Keep in mind terms such as `throw` are reserved/key words in JavaScript so the RxJS `throw` operator is imported as: ``` import { _throw } from 'rxjs/observable/throw'; ``` **Update:** For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
In RxJS 6, `Observable.throw()` is replaced by `throwError()` which operates very similarly to its predecessor. So, you can replace from `Observable.throw(error)` to only `throwError(error)` by importing: ``` import { throwError } from 'rxjs'; ``` Checkout this link for further reference: <https://www.metaltoad.com/blog/angular-6-upgrading-api-calls-rxjs-6>
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
The error `There are multiple modules with names that only differ in casing.` is indicating the wrong import is being targeted with how you are trying to use `Observable`. The import should be with a capital "O" like: `import { Observable } from 'rxjs/Observable';` This will import the individual `Observable` operator, which be used in combination with operators such as `catch` or `throw` on created Observables. ``` import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; ``` To import the full Observable object you'd import it like this: `import { Observable } from 'rxjs/Rx'` **Update:** With newer versions of RxJS (5.5+) operators such as `map()` and `filter()` can used as [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) in combination with `pipe()` rather than chaining. They are imported such as: ``` import { filter, map, catchError } from 'rxjs/operators'; ``` Keep in mind terms such as `throw` are reserved/key words in JavaScript so the RxJS `throw` operator is imported as: ``` import { _throw } from 'rxjs/observable/throw'; ``` **Update:** For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
\_throw has been discarded in newer versions of RxJS For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
The error `There are multiple modules with names that only differ in casing.` is indicating the wrong import is being targeted with how you are trying to use `Observable`. The import should be with a capital "O" like: `import { Observable } from 'rxjs/Observable';` This will import the individual `Observable` operator, which be used in combination with operators such as `catch` or `throw` on created Observables. ``` import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; ``` To import the full Observable object you'd import it like this: `import { Observable } from 'rxjs/Rx'` **Update:** With newer versions of RxJS (5.5+) operators such as `map()` and `filter()` can used as [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) in combination with `pipe()` rather than chaining. They are imported such as: ``` import { filter, map, catchError } from 'rxjs/operators'; ``` Keep in mind terms such as `throw` are reserved/key words in JavaScript so the RxJS `throw` operator is imported as: ``` import { _throw } from 'rxjs/observable/throw'; ``` **Update:** For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
In Angular9 Observable: 1. if data arrived and status is OK, then send the data 2. If STATUS of the data is NOT OK, then throw an error ``` myObsFunc(): Observable<any> { return this.http.get<any>('/api/something') .pipe( /* Catch a backend error and let the component know */ catchError( err => { /* Rethrow error */ return throwError( err ); }), map( (res)=> { if( res.STATUS == "OK" ) { /* Send DATA to subscriber */ return Object.values( res.DATA) } else { /* Inform subscriber that a functional error occured */ throw ( "getOrphans: Status is not OK but "+ res.STATUS ) ; } }), ) } ```
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
In RxJS 6, `Observable.throw()` is replaced by `throwError()` which operates very similarly to its predecessor. So, you can replace from `Observable.throw(error)` to only `throwError(error)` by importing: ``` import { throwError } from 'rxjs'; ``` Checkout this link for further reference: <https://www.metaltoad.com/blog/angular-6-upgrading-api-calls-rxjs-6>
I was facing the same issue in my `angular 5` application. What I did is, adding a new package. ``` import { throwError } from 'rxjs'; import { filter, map, catchError } from 'rxjs/operators'; ``` And from my `http` service call I return a function. ``` return this.http.request(request) .pipe(map((res: Response) => res.json()), catchError((res: Response) => this.onError(res))); ``` And in `onError` function I am returning the error with `throwError(error)`. ``` onError(res: Response) { const statusCode = res.status; const body = res.json(); const error = { statusCode: statusCode, error: body.error }; return throwError(error); } ```
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
I was facing the same issue in my `angular 5` application. What I did is, adding a new package. ``` import { throwError } from 'rxjs'; import { filter, map, catchError } from 'rxjs/operators'; ``` And from my `http` service call I return a function. ``` return this.http.request(request) .pipe(map((res: Response) => res.json()), catchError((res: Response) => this.onError(res))); ``` And in `onError` function I am returning the error with `throwError(error)`. ``` onError(res: Response) { const statusCode = res.status; const body = res.json(); const error = { statusCode: statusCode, error: body.error }; return throwError(error); } ```
\_throw has been discarded in newer versions of RxJS For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
I was facing the same issue in my `angular 5` application. What I did is, adding a new package. ``` import { throwError } from 'rxjs'; import { filter, map, catchError } from 'rxjs/operators'; ``` And from my `http` service call I return a function. ``` return this.http.request(request) .pipe(map((res: Response) => res.json()), catchError((res: Response) => this.onError(res))); ``` And in `onError` function I am returning the error with `throwError(error)`. ``` onError(res: Response) { const statusCode = res.status; const body = res.json(); const error = { statusCode: statusCode, error: body.error }; return throwError(error); } ```
In Angular9 Observable: 1. if data arrived and status is OK, then send the data 2. If STATUS of the data is NOT OK, then throw an error ``` myObsFunc(): Observable<any> { return this.http.get<any>('/api/something') .pipe( /* Catch a backend error and let the component know */ catchError( err => { /* Rethrow error */ return throwError( err ); }), map( (res)=> { if( res.STATUS == "OK" ) { /* Send DATA to subscriber */ return Object.values( res.DATA) } else { /* Inform subscriber that a functional error occured */ throw ( "getOrphans: Status is not OK but "+ res.STATUS ) ; } }), ) } ```
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
In RxJS 6, `Observable.throw()` is replaced by `throwError()` which operates very similarly to its predecessor. So, you can replace from `Observable.throw(error)` to only `throwError(error)` by importing: ``` import { throwError } from 'rxjs'; ``` Checkout this link for further reference: <https://www.metaltoad.com/blog/angular-6-upgrading-api-calls-rxjs-6>
\_throw has been discarded in newer versions of RxJS For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
In RxJS 6, `Observable.throw()` is replaced by `throwError()` which operates very similarly to its predecessor. So, you can replace from `Observable.throw(error)` to only `throwError(error)` by importing: ``` import { throwError } from 'rxjs'; ``` Checkout this link for further reference: <https://www.metaltoad.com/blog/angular-6-upgrading-api-calls-rxjs-6>
In Angular9 Observable: 1. if data arrived and status is OK, then send the data 2. If STATUS of the data is NOT OK, then throw an error ``` myObsFunc(): Observable<any> { return this.http.get<any>('/api/something') .pipe( /* Catch a backend error and let the component know */ catchError( err => { /* Rethrow error */ return throwError( err ); }), map( (res)=> { if( res.STATUS == "OK" ) { /* Send DATA to subscriber */ return Object.values( res.DATA) } else { /* Inform subscriber that a functional error occured */ throw ( "getOrphans: Status is not OK but "+ res.STATUS ) ; } }), ) } ```
45,464,860
In the index.html page I put a .gif before all the tags that laod the files. Then, with JQuery, I removed that loader. But it didn't work. A blank page was shown, because it was waiting for load some .js files. So, I created a script that load the files dynamically. This is the html code: ``` <!doctype html> <html ng-app="myApp"> <head> ...here I'm loading all css files </head> <body> <!-- This is the loader --> <div id="loader" style="background:url('URL_IN_BASE_64')"></div> <div ng-cloak ng-controller="MyAppController"> <div ui-view></div> </div> <script> (function () { var fileList = [ "vendor/angular/angular.min.js", "vendor/jquery/jquery.min.js", "vendor/angular-aria/angular-aria.min.js", .... ] function loadScripts(index) { return function () { var e = document.createElement('script'); e.src = fileList[index]; document.body.appendChild(e); if (index + 1 < fileList.length) { e.onload = loadScripts(index + 1) } else { var loader = document.getElementById("loader"); if (loader) { loader.remove(); } } } } loadScripts(0)(); })(); </script> </body> </html> ``` Now, the problem is that the page first loads all the css files, then angular.min.js, then my gif, and then the other files. Why? How can I immediatly load the gif and, suddently, all other files? [![enter image description here](https://i.stack.imgur.com/yRpig.png)](https://i.stack.imgur.com/yRpig.png) Thank you!
2017/08/02
[ "https://Stackoverflow.com/questions/45464860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5210601/" ]
\_throw has been discarded in newer versions of RxJS For newer versions of RxJS (6+), use this: ``` import { throwError } from 'rxjs'; ``` and throw an error like this: ``` if (error.status === 404) return throwError( new NotFoundError(error) ) ```
In Angular9 Observable: 1. if data arrived and status is OK, then send the data 2. If STATUS of the data is NOT OK, then throw an error ``` myObsFunc(): Observable<any> { return this.http.get<any>('/api/something') .pipe( /* Catch a backend error and let the component know */ catchError( err => { /* Rethrow error */ return throwError( err ); }), map( (res)=> { if( res.STATUS == "OK" ) { /* Send DATA to subscriber */ return Object.values( res.DATA) } else { /* Inform subscriber that a functional error occured */ throw ( "getOrphans: Status is not OK but "+ res.STATUS ) ; } }), ) } ```
19,929,215
What does this the following pattern `?:` mean in regexp? It should have something to do with searching for the n-ht occurrence of a pattern, isn't it.
2013/11/12
[ "https://Stackoverflow.com/questions/19929215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1829473/" ]
`?:` denotes non-capturing group: `"Non-capturing groupings, denoted by (?:regexp), still allow the regexp to be treated as a single unit, but don't establish a capturing group at the same time`." <http://perldoc.perl.org/perlretut.html#Non-capturing-groupings>
When `?:` appears after a parenthesis, it makes the group non-capturing. The group is just used for applying quantifiers, or for grouping alternates, rather than to save the part of the string that matches that sub-pattern.
19,929,215
What does this the following pattern `?:` mean in regexp? It should have something to do with searching for the n-ht occurrence of a pattern, isn't it.
2013/11/12
[ "https://Stackoverflow.com/questions/19929215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1829473/" ]
When `?:` appears after a parenthesis, it makes the group non-capturing. The group is just used for applying quantifiers, or for grouping alternates, rather than to save the part of the string that matches that sub-pattern.
**?:** creates a phantom group. It means we cannot access that group. Ex.: ``` (Alan) (?:Messias) (Cordeiro) ``` We'll have 2 groups: `$1 = Alan` and `$2 = Cordeiro` We do not have access the group between "Alan" and "Cordeiro". Maybe you'll like this link to test regex: <http://gskinner.com/RegExr/> Best regards
19,929,215
What does this the following pattern `?:` mean in regexp? It should have something to do with searching for the n-ht occurrence of a pattern, isn't it.
2013/11/12
[ "https://Stackoverflow.com/questions/19929215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1829473/" ]
`?:` denotes non-capturing group: `"Non-capturing groupings, denoted by (?:regexp), still allow the regexp to be treated as a single unit, but don't establish a capturing group at the same time`." <http://perldoc.perl.org/perlretut.html#Non-capturing-groupings>
**?:** creates a phantom group. It means we cannot access that group. Ex.: ``` (Alan) (?:Messias) (Cordeiro) ``` We'll have 2 groups: `$1 = Alan` and `$2 = Cordeiro` We do not have access the group between "Alan" and "Cordeiro". Maybe you'll like this link to test regex: <http://gskinner.com/RegExr/> Best regards
26,426,574
i am struggle days to find a way for working password strength checker, but still not found solution. I have AjaxBeginForm in partial view for some simple input. Here is my view: @model EntryViewModel ``` <style> input.input-validation-error, textarea.input-validation-error, select.input-validation-error { background: #FEF1EC; border: 1px solid #CD0A0A; } .field-validation-error { color: #C55050; } </style> @using (Ajax.BeginForm("Create", "Entry", new AjaxOptions { HttpMethod = "Post" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Title, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Username) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Username, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Username) </div> <div class="editor-label"> @Html.LabelFor(model => model.Password) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Password) </div> <div class="editor-label"> @Html.LabelFor(model => model.Url) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Url, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Url) </div> <div class="editor-label"> @Html.LabelFor(model => model.Description) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.Description, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Description) </div> @Html.HiddenFor(model => model.CategoryId) <div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a> <input class=" btn btn-primary" id="submitButton" type="submit" value="Create" /> </div> } ``` I've tried with many methods, including KendoUI, but none of works. Any suggestions for solution?
2014/10/17
[ "https://Stackoverflow.com/questions/26426574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110768/" ]
What about the [Google Password Strength API?](http://www.codeproject.com/Articles/19245/Google-Password-Strength-API).
<http://www.webappers.com/2007/08/22/jquery-password-strength-meter-with-better-algorithm/> I had once implemented using this hope this helps you. :)
26,426,574
i am struggle days to find a way for working password strength checker, but still not found solution. I have AjaxBeginForm in partial view for some simple input. Here is my view: @model EntryViewModel ``` <style> input.input-validation-error, textarea.input-validation-error, select.input-validation-error { background: #FEF1EC; border: 1px solid #CD0A0A; } .field-validation-error { color: #C55050; } </style> @using (Ajax.BeginForm("Create", "Entry", new AjaxOptions { HttpMethod = "Post" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Title, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Username) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Username, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Username) </div> <div class="editor-label"> @Html.LabelFor(model => model.Password) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Password) </div> <div class="editor-label"> @Html.LabelFor(model => model.Url) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Url, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Url) </div> <div class="editor-label"> @Html.LabelFor(model => model.Description) </div> <div class="editor-field"> @Html.TextAreaFor(model => model.Description, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.Description) </div> @Html.HiddenFor(model => model.CategoryId) <div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn">Close</a> <input class=" btn btn-primary" id="submitButton" type="submit" value="Create" /> </div> } ``` I've tried with many methods, including KendoUI, but none of works. Any suggestions for solution?
2014/10/17
[ "https://Stackoverflow.com/questions/26426574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4110768/" ]
what about StringLength and DataType(DataType.Password) ``` public class RegisterModel { [Required] [Display(Name = "Name")] public string UserName { get; set; } [Required] [StringLength(100, ErrorMessage = "Pass \"{0}\" must have no less {2} chars.", MinimumLength = 8)] [DataType(DataType.Password)] ```
<http://www.webappers.com/2007/08/22/jquery-password-strength-meter-with-better-algorithm/> I had once implemented using this hope this helps you. :)
41,973,109
I m using following code. I am reading a json file name is "hassan.json". If i read this file in controller through $http everything works fine. but i want to use the data that i read from file, again and again in different controller so i made a service for this. but **in service when i read data from that json file through $http.get()** and in return when i call that service method in my controller and console.log(data) **it returns me this in console "e {$$state: object}."** *this is **Controller**:* ``` app.controller('showdata', function($scope, service){ $scope.mydata = service.getData().then(function(user){ $scope.mydata = (user.data); console.log(($scope.mydata)); }); }); ``` *this is **service** i'm using:* ``` app.service('service', function($http, $q){ var outData; this.getData = function() { if (this.outData === undefined) { var deferred = $q.defer(); $http.get('jsons/hassan.json') .then(function(data){ this.outData = data; deferred.resolve(data); }, function(err) { deferred.reject(err); }); return deferred.promise; } else { return this.outData; } } }); ```
2017/02/01
[ "https://Stackoverflow.com/questions/41973109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7498727/" ]
Change the controller as below: ``` app.controller('showdata', function($scope, service){ service.getData().then(function(user){ $scope.mydata = (user.data); console.log(($scope.mydata)); }); }); ```
There is different between `$http.get().then()` and `$http.get().success()`. Change your code to this: ``` var deferred = $q.defer(); $http.get('jsons/hassan.json') .success(function(data){ this.outData = data; deferred.resolve(data); }) .error(function(err) { deferred.reject(err); }); return deferred.promise; ```
41,973,109
I m using following code. I am reading a json file name is "hassan.json". If i read this file in controller through $http everything works fine. but i want to use the data that i read from file, again and again in different controller so i made a service for this. but **in service when i read data from that json file through $http.get()** and in return when i call that service method in my controller and console.log(data) **it returns me this in console "e {$$state: object}."** *this is **Controller**:* ``` app.controller('showdata', function($scope, service){ $scope.mydata = service.getData().then(function(user){ $scope.mydata = (user.data); console.log(($scope.mydata)); }); }); ``` *this is **service** i'm using:* ``` app.service('service', function($http, $q){ var outData; this.getData = function() { if (this.outData === undefined) { var deferred = $q.defer(); $http.get('jsons/hassan.json') .then(function(data){ this.outData = data; deferred.resolve(data); }, function(err) { deferred.reject(err); }); return deferred.promise; } else { return this.outData; } } }); ```
2017/02/01
[ "https://Stackoverflow.com/questions/41973109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7498727/" ]
`$http` by itself is a promise, so there is no need in `$q`, try to rewrite your code using `$http`'s `cache`: ``` app.controller('showdata', function($scope, service){ service.getData().then(function(user) { // no need to call user.data, service handles this $scope.mydata = user; console.log($scope.mydata); }).catch(function (err) { // handle errors here if needed }); }); ``` and ``` app.service('service', function($http){ this.getData = function() { return $http({ method: 'GET', url: 'jsons/hassan.json', // cache will ensure calling ajax only once cache: true }).then(function (data) { // this will ensure that we get clear data in our service response return data.data; }); }; }}); ```
There is different between `$http.get().then()` and `$http.get().success()`. Change your code to this: ``` var deferred = $q.defer(); $http.get('jsons/hassan.json') .success(function(data){ this.outData = data; deferred.resolve(data); }) .error(function(err) { deferred.reject(err); }); return deferred.promise; ```
41,973,109
I m using following code. I am reading a json file name is "hassan.json". If i read this file in controller through $http everything works fine. but i want to use the data that i read from file, again and again in different controller so i made a service for this. but **in service when i read data from that json file through $http.get()** and in return when i call that service method in my controller and console.log(data) **it returns me this in console "e {$$state: object}."** *this is **Controller**:* ``` app.controller('showdata', function($scope, service){ $scope.mydata = service.getData().then(function(user){ $scope.mydata = (user.data); console.log(($scope.mydata)); }); }); ``` *this is **service** i'm using:* ``` app.service('service', function($http, $q){ var outData; this.getData = function() { if (this.outData === undefined) { var deferred = $q.defer(); $http.get('jsons/hassan.json') .then(function(data){ this.outData = data; deferred.resolve(data); }, function(err) { deferred.reject(err); }); return deferred.promise; } else { return this.outData; } } }); ```
2017/02/01
[ "https://Stackoverflow.com/questions/41973109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7498727/" ]
`$http` by itself is a promise, so there is no need in `$q`, try to rewrite your code using `$http`'s `cache`: ``` app.controller('showdata', function($scope, service){ service.getData().then(function(user) { // no need to call user.data, service handles this $scope.mydata = user; console.log($scope.mydata); }).catch(function (err) { // handle errors here if needed }); }); ``` and ``` app.service('service', function($http){ this.getData = function() { return $http({ method: 'GET', url: 'jsons/hassan.json', // cache will ensure calling ajax only once cache: true }).then(function (data) { // this will ensure that we get clear data in our service response return data.data; }); }; }}); ```
Change the controller as below: ``` app.controller('showdata', function($scope, service){ service.getData().then(function(user){ $scope.mydata = (user.data); console.log(($scope.mydata)); }); }); ```
10,423,703
I'm currently working on an application that uses a Windows Form GUI. The main work of the application will be performed on an additional thread - but it is possible that it will be dependent on the state of the form. Because of this, before I create the thread I must make sure that the form is **completely** loaded. Also, I need to make sure the thread is terminated **before** the form begins closing. Possible solutions for this problem might be overriding the `OnShown` and `OnFormClosing` methods. Does the `OnShow` method really gets called only after ALL of the assets of the form have been loaded? And what about the `OnFormClosing` - can I be sure that any code executed in this method will be performed **before** the form begins close / dispose?
2012/05/03
[ "https://Stackoverflow.com/questions/10423703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940723/" ]
I suggest you read through the WinForms event ordering as posted on MSDN: <http://msdn.microsoft.com/en-us/library/86faxx0d.aspx>
Windows Forms events can be tricky, and the order they fire unreliable. For example, the 'Shown' event is meant to fire once and once only, when the Form is first displayed, but just yesterday I found a way to completely prevent that event from firing by manipulating Form.Visible flags at the right time. So, you need to be quite specific about your needs. For example - when you say 'completely loaded', what do you mean? Controls created, form visible, Form constructor finished executing? Likewise, the FormClosing event might be circumvented by an unhandled exception in your main aUI thread, which results in the Form being removed without the event firing. I suggest never assuming anything around these events. Make your worker thread capable of dealing with the Form state being unavailable, or not ready. Without knowing your exact requirements, it's hard to be more specific.
10,423,703
I'm currently working on an application that uses a Windows Form GUI. The main work of the application will be performed on an additional thread - but it is possible that it will be dependent on the state of the form. Because of this, before I create the thread I must make sure that the form is **completely** loaded. Also, I need to make sure the thread is terminated **before** the form begins closing. Possible solutions for this problem might be overriding the `OnShown` and `OnFormClosing` methods. Does the `OnShow` method really gets called only after ALL of the assets of the form have been loaded? And what about the `OnFormClosing` - can I be sure that any code executed in this method will be performed **before** the form begins close / dispose?
2012/05/03
[ "https://Stackoverflow.com/questions/10423703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940723/" ]
Windows Forms events can be tricky, and the order they fire unreliable. For example, the 'Shown' event is meant to fire once and once only, when the Form is first displayed, but just yesterday I found a way to completely prevent that event from firing by manipulating Form.Visible flags at the right time. So, you need to be quite specific about your needs. For example - when you say 'completely loaded', what do you mean? Controls created, form visible, Form constructor finished executing? Likewise, the FormClosing event might be circumvented by an unhandled exception in your main aUI thread, which results in the Form being removed without the event firing. I suggest never assuming anything around these events. Make your worker thread capable of dealing with the Form state being unavailable, or not ready. Without knowing your exact requirements, it's hard to be more specific.
Have you tried to use InitializeComponent on the constructor of your main WinForm and use **OnLoad** (called whenever everything is loaded)?
10,423,703
I'm currently working on an application that uses a Windows Form GUI. The main work of the application will be performed on an additional thread - but it is possible that it will be dependent on the state of the form. Because of this, before I create the thread I must make sure that the form is **completely** loaded. Also, I need to make sure the thread is terminated **before** the form begins closing. Possible solutions for this problem might be overriding the `OnShown` and `OnFormClosing` methods. Does the `OnShow` method really gets called only after ALL of the assets of the form have been loaded? And what about the `OnFormClosing` - can I be sure that any code executed in this method will be performed **before** the form begins close / dispose?
2012/05/03
[ "https://Stackoverflow.com/questions/10423703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940723/" ]
I suggest you read through the WinForms event ordering as posted on MSDN: <http://msdn.microsoft.com/en-us/library/86faxx0d.aspx>
Have you tried to use InitializeComponent on the constructor of your main WinForm and use **OnLoad** (called whenever everything is loaded)?
7,512,343
I'm new in 3D games developing so I have kinda dummy question - how to move a mesh in 3D engine (under moving I mean a walking animation). And how to dress some skin on it? What I have: 1. open source 3D OpenGL engine - NinevehGL <http://nineveh.gl/>. It's super easy to load a mesh to. I' pretty sure it will be awesome engine when it will be released! 2. a mesh model of the human. <http://www.2shared.com/file/RTBEvSbf/female.html> (it's mesh of a female that I downloaded from some open source web site..) 3. found a web site from which I can download skeleton animation in formats: dao (COLLADA) , XML , BVH (?) - <http://www.animeeple.com/details/bcd6ac4b-ebc9-465e-9233-ed0220387fb9> 4. what I stuck on (see attached image) ![enter image description here](https://i.stack.imgur.com/8dx0t.png) So, how can I join all these things and make simple game when dressed human will walk forward and backward?
2011/09/22
[ "https://Stackoverflow.com/questions/7512343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145792/" ]
The problem is difficult to answer, because it would require knowledge of the engine's API. Also you can't just stick a skeletal animation onto some mesh. You need some connection between both, a process called rigging, in which you add "bones" (also called armatures) to the mesh. This is an artistic process, done in a 3D modeller. Then you need to implement a skeletal animation system, which is a far too complex task to answer in a single Stackoverflow answer (it involves animation curve evaluation, quaternion interpolation, skinning matrices, etc.). You should break down your question into smaller pieces.
I'm a BETA Tester for Nineveh Engine. Currently, the engine does not support bones/skeleton animation. This will be a part of their next release version which is upcoming in next 4-8 months. Future (Roadmap) Version 0.9.3 : Q4 2011 - Q1 2012 Bones, Rigging and Mesh's Animations. Mesh Morph. You might want to checkout <http://nineveh.gl/docs/changelog/>
250,903
I have SQL server 2017. I have one 3 TB size database there. Somehow due to long running transaction the database got stuck 'IN Recovery' mode after SQL server Restarted. When I checked the sql error logs it says 2 189 255 seconds remaining (Phase 2 of 3) completed which is almost 25 days. My goal is to bring the database online even if I lose some data. So I've ran below commands but no luck. ``` USE [master] GO RESTORE DATABASE test WITH RECOVERY --Msg 3101, Level 16, State 1, Line 6 --Exclusive access could not be obtained because the database is in use. --Msg 3013, Level 16, State 1, Line 6 --RESTORE DATABASE is terminating abnormally. ALTER DATABASE test SET EMERGENCY; GO --Msg 5011, Level 14, State 7, Line 13 --User does not have permission to alter database 'DragonDriveConnect', the database does not exist, or the database is not in a state that allows access checks. --Msg 5069, Level 16, State 1, Line 13 --ALTER DATABASE statement failed. DBCC CHECKDB (DragonDriveConnect, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS; GO --Msg 922, Level 14, State 1, Line 22 --Database 'DragonDriveConnect' is being recovered. Waiting until recovery is finished. ``` At last I've tried to Delete the database too but that is also not working and giving me error saying Cant Delete. How do I get out of this situation?
2019/10/12
[ "https://dba.stackexchange.com/questions/250903", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/192946/" ]
The error you're seeing in the SQL Server Error Log is this one: > > Recovery of database 'CrashTestDummy' (9) is 0% complete (approximately 42 seconds remain). Phase 2 of 3. This is an informational message only. No user action is required > > > More generically, it will say: > > Recovery of database '`{Database Name}`' (`{Database ID}`) is `{N}`% complete (approximately `{N}` seconds remain). Phase `{N}` of 3. This is an informational message only. No user action is required > > > Because your database was not shut down cleanly on restart, the database *must* go through "crash recovery". This is required to ensure the database remains consistent. When the database is not shut down cleanly, SQL Server must make sure that transactions written to the transaction log have been reconciled properly against the data files. All transactions are guaranteed to be written to the transaction log. However, updating data is initially only done in memory. Updates to the physical data files are done asynchronously via a [checkpoint](https://learn.microsoft.com/en-us/sql/relational-databases/logs/database-checkpoints-sql-server). The asynchronous nature of the data file updates are why a crash or unclean shutdown requires extra work on startup. As indicated by the error message, there are three phases to the recovery. Each of these is essentially a pass through the transaction log: 1. Analysis 2. Redo / Roll Forward 3. Undo / Rollback ### Analysis This phase is simply to review the transaction log & determine what needs to be done. It will identify when the most recent checkpoint was, and what transactions might need to be rolled forward or back to ensure consistency. ### Redo / Roll Forward Completed transactions from the transaction log need to be reviewed to ensure the data file has been completed updated. Without this, changes that were only in-memory might have been lost. This phase will take those transactions that were committed after the most recent checkpoint and redo them, to ensure they are persisted to the data file. If you are using SQL Server Enterprise edition, [Fast Recovery](https://www.sqlskills.com/blogs/paul/fast-recovery-used/) will allow the database to come online & be available after this phase of recovery. If you are not using Enterprise Edition, the database will not be available until after the Undo phase has completed. ### Undo / Rollback Transactions from the transaction log that were rolled back, or were uncommitted at the time of "crash" must be rolled back. SQL Server must verify that if uncommitted changes were made to the data file, they are undone. Without this, a rolled back change could be partially committed, violating the [ACID principles](https://en.wikipedia.org/wiki/ACID) of the database. This phase will perform the rollback of any transactions that were uncommitted at the time of crash, or were rolled back after the final checkpoint. So what can you do about it? ---------------------------- While the database is in recovery, attempts to bring the database online via a `RESTORE` command like this will fail: ``` RESTORE DATABASE CrashTestDummy WITH RECOVERY; ``` SQL Server is *already* attempting to do this. The `RESTORE...WITH RECOVERY;` will simply put the database through the exact same steps in order to bring the database online in a consistent manner. ### Be patient The right thing to do is just be patient. This part of the message from the error log is the one that you should pay attention to: > > No user action is required > > > Note, too, that the time remaining is an estimate. In my experience, it is wildly inaccurate. Sometimes the time remaining will grow larger, rather than reducing. Sometimes it will report a very long completion time, and suddenly complete very fast. Its just an estimate. ### Can you just "throw away" your transaction log and start fresh? **I advise against it.** I would suggest you never, ever do this with a production database. There is a procedure to attach a database without a transaction log, and ask SQL Server to `ATTACH_REBUILD_LOG`. I won't detail all the steps, but the "punchline" for that procedure is to do this: ``` CREATE DATABASE CrashTestDummy ON (FILENAME = 'C:\SQL\MSSQL15.MSSQLSERVER\MSSQL\DATA\CrashTestDummy.mdf') FOR ATTACH_REBUILD_LOG; ``` Running this on a crashed database may result in this error: > > The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure. > Msg 1813, Level 16, State 2, Line 5 > Could not open new database 'CrashTestDummy'. CREATE DATABASE is aborted. > > > In which case, you're stuck. You'll need to use the original transaction log & be patient. Just wait for it to recover.
Patience, patience! Possible causes for the databases to stuck in β€œIn Recovery” mode? * Huge size of transaction log file. * SQL restarted during a long running transaction. * Huge number of VLFs (i.e. virtual Log Files). * Could be a bug in SQL Server which is fixed with the help of some patches. The very first thing that your should do is checking of ERRORLOG. In Errorlog, we should see the very first message in the database (TestMe is the name of my database): **Starting up database β€˜TestMe’.** ``` This means the files are opened and recovery is started. After sometime, you should see phase 1. Recovery of database β€˜TestMe’ (28) is 0% complete (approximately 37 seconds remain). Phase 1 of 3. This is an informational message only. No user action is required. Recovery of database β€˜TestMe’ (28) is 3% complete (approximately 36 seconds remain). Phase 1 of 3. This is an informational message only. No user action is required. ``` Once phase 1 is complete, it would go with Phase 2 and 3. And once it completes, you should use something similar. ``` 3807 transactions rolled forward in database β€˜TestMe’ (28). This is an informational message only. No user action is required. 0 transactions rolled back in database β€˜TestMe’ (28). This is an informational message only. No user action is required. Recovery is writing a checkpoint in database β€˜TestMe’ (28). This is an informational message only. No user action is required. Recovery completed for database TestMe (database ID 28) in 30 second(s) (analysis 1289 ms, redo 29343 ms, undo 72 ms.) This is an informational message only. No user action is required ```
250,903
I have SQL server 2017. I have one 3 TB size database there. Somehow due to long running transaction the database got stuck 'IN Recovery' mode after SQL server Restarted. When I checked the sql error logs it says 2 189 255 seconds remaining (Phase 2 of 3) completed which is almost 25 days. My goal is to bring the database online even if I lose some data. So I've ran below commands but no luck. ``` USE [master] GO RESTORE DATABASE test WITH RECOVERY --Msg 3101, Level 16, State 1, Line 6 --Exclusive access could not be obtained because the database is in use. --Msg 3013, Level 16, State 1, Line 6 --RESTORE DATABASE is terminating abnormally. ALTER DATABASE test SET EMERGENCY; GO --Msg 5011, Level 14, State 7, Line 13 --User does not have permission to alter database 'DragonDriveConnect', the database does not exist, or the database is not in a state that allows access checks. --Msg 5069, Level 16, State 1, Line 13 --ALTER DATABASE statement failed. DBCC CHECKDB (DragonDriveConnect, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS; GO --Msg 922, Level 14, State 1, Line 22 --Database 'DragonDriveConnect' is being recovered. Waiting until recovery is finished. ``` At last I've tried to Delete the database too but that is also not working and giving me error saying Cant Delete. How do I get out of this situation?
2019/10/12
[ "https://dba.stackexchange.com/questions/250903", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/192946/" ]
The error you're seeing in the SQL Server Error Log is this one: > > Recovery of database 'CrashTestDummy' (9) is 0% complete (approximately 42 seconds remain). Phase 2 of 3. This is an informational message only. No user action is required > > > More generically, it will say: > > Recovery of database '`{Database Name}`' (`{Database ID}`) is `{N}`% complete (approximately `{N}` seconds remain). Phase `{N}` of 3. This is an informational message only. No user action is required > > > Because your database was not shut down cleanly on restart, the database *must* go through "crash recovery". This is required to ensure the database remains consistent. When the database is not shut down cleanly, SQL Server must make sure that transactions written to the transaction log have been reconciled properly against the data files. All transactions are guaranteed to be written to the transaction log. However, updating data is initially only done in memory. Updates to the physical data files are done asynchronously via a [checkpoint](https://learn.microsoft.com/en-us/sql/relational-databases/logs/database-checkpoints-sql-server). The asynchronous nature of the data file updates are why a crash or unclean shutdown requires extra work on startup. As indicated by the error message, there are three phases to the recovery. Each of these is essentially a pass through the transaction log: 1. Analysis 2. Redo / Roll Forward 3. Undo / Rollback ### Analysis This phase is simply to review the transaction log & determine what needs to be done. It will identify when the most recent checkpoint was, and what transactions might need to be rolled forward or back to ensure consistency. ### Redo / Roll Forward Completed transactions from the transaction log need to be reviewed to ensure the data file has been completed updated. Without this, changes that were only in-memory might have been lost. This phase will take those transactions that were committed after the most recent checkpoint and redo them, to ensure they are persisted to the data file. If you are using SQL Server Enterprise edition, [Fast Recovery](https://www.sqlskills.com/blogs/paul/fast-recovery-used/) will allow the database to come online & be available after this phase of recovery. If you are not using Enterprise Edition, the database will not be available until after the Undo phase has completed. ### Undo / Rollback Transactions from the transaction log that were rolled back, or were uncommitted at the time of "crash" must be rolled back. SQL Server must verify that if uncommitted changes were made to the data file, they are undone. Without this, a rolled back change could be partially committed, violating the [ACID principles](https://en.wikipedia.org/wiki/ACID) of the database. This phase will perform the rollback of any transactions that were uncommitted at the time of crash, or were rolled back after the final checkpoint. So what can you do about it? ---------------------------- While the database is in recovery, attempts to bring the database online via a `RESTORE` command like this will fail: ``` RESTORE DATABASE CrashTestDummy WITH RECOVERY; ``` SQL Server is *already* attempting to do this. The `RESTORE...WITH RECOVERY;` will simply put the database through the exact same steps in order to bring the database online in a consistent manner. ### Be patient The right thing to do is just be patient. This part of the message from the error log is the one that you should pay attention to: > > No user action is required > > > Note, too, that the time remaining is an estimate. In my experience, it is wildly inaccurate. Sometimes the time remaining will grow larger, rather than reducing. Sometimes it will report a very long completion time, and suddenly complete very fast. Its just an estimate. ### Can you just "throw away" your transaction log and start fresh? **I advise against it.** I would suggest you never, ever do this with a production database. There is a procedure to attach a database without a transaction log, and ask SQL Server to `ATTACH_REBUILD_LOG`. I won't detail all the steps, but the "punchline" for that procedure is to do this: ``` CREATE DATABASE CrashTestDummy ON (FILENAME = 'C:\SQL\MSSQL15.MSSQLSERVER\MSSQL\DATA\CrashTestDummy.mdf') FOR ATTACH_REBUILD_LOG; ``` Running this on a crashed database may result in this error: > > The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure. > Msg 1813, Level 16, State 2, Line 5 > Could not open new database 'CrashTestDummy'. CREATE DATABASE is aborted. > > > In which case, you're stuck. You'll need to use the original transaction log & be patient. Just wait for it to recover.
In my case, This issue has been resolved by Restarting SQL Server Service, You can do it from SQL Server Configuration Manager. [![enter image description here](https://i.stack.imgur.com/1nCeM.png)](https://i.stack.imgur.com/1nCeM.png)
250,903
I have SQL server 2017. I have one 3 TB size database there. Somehow due to long running transaction the database got stuck 'IN Recovery' mode after SQL server Restarted. When I checked the sql error logs it says 2 189 255 seconds remaining (Phase 2 of 3) completed which is almost 25 days. My goal is to bring the database online even if I lose some data. So I've ran below commands but no luck. ``` USE [master] GO RESTORE DATABASE test WITH RECOVERY --Msg 3101, Level 16, State 1, Line 6 --Exclusive access could not be obtained because the database is in use. --Msg 3013, Level 16, State 1, Line 6 --RESTORE DATABASE is terminating abnormally. ALTER DATABASE test SET EMERGENCY; GO --Msg 5011, Level 14, State 7, Line 13 --User does not have permission to alter database 'DragonDriveConnect', the database does not exist, or the database is not in a state that allows access checks. --Msg 5069, Level 16, State 1, Line 13 --ALTER DATABASE statement failed. DBCC CHECKDB (DragonDriveConnect, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS; GO --Msg 922, Level 14, State 1, Line 22 --Database 'DragonDriveConnect' is being recovered. Waiting until recovery is finished. ``` At last I've tried to Delete the database too but that is also not working and giving me error saying Cant Delete. How do I get out of this situation?
2019/10/12
[ "https://dba.stackexchange.com/questions/250903", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/192946/" ]
The error you're seeing in the SQL Server Error Log is this one: > > Recovery of database 'CrashTestDummy' (9) is 0% complete (approximately 42 seconds remain). Phase 2 of 3. This is an informational message only. No user action is required > > > More generically, it will say: > > Recovery of database '`{Database Name}`' (`{Database ID}`) is `{N}`% complete (approximately `{N}` seconds remain). Phase `{N}` of 3. This is an informational message only. No user action is required > > > Because your database was not shut down cleanly on restart, the database *must* go through "crash recovery". This is required to ensure the database remains consistent. When the database is not shut down cleanly, SQL Server must make sure that transactions written to the transaction log have been reconciled properly against the data files. All transactions are guaranteed to be written to the transaction log. However, updating data is initially only done in memory. Updates to the physical data files are done asynchronously via a [checkpoint](https://learn.microsoft.com/en-us/sql/relational-databases/logs/database-checkpoints-sql-server). The asynchronous nature of the data file updates are why a crash or unclean shutdown requires extra work on startup. As indicated by the error message, there are three phases to the recovery. Each of these is essentially a pass through the transaction log: 1. Analysis 2. Redo / Roll Forward 3. Undo / Rollback ### Analysis This phase is simply to review the transaction log & determine what needs to be done. It will identify when the most recent checkpoint was, and what transactions might need to be rolled forward or back to ensure consistency. ### Redo / Roll Forward Completed transactions from the transaction log need to be reviewed to ensure the data file has been completed updated. Without this, changes that were only in-memory might have been lost. This phase will take those transactions that were committed after the most recent checkpoint and redo them, to ensure they are persisted to the data file. If you are using SQL Server Enterprise edition, [Fast Recovery](https://www.sqlskills.com/blogs/paul/fast-recovery-used/) will allow the database to come online & be available after this phase of recovery. If you are not using Enterprise Edition, the database will not be available until after the Undo phase has completed. ### Undo / Rollback Transactions from the transaction log that were rolled back, or were uncommitted at the time of "crash" must be rolled back. SQL Server must verify that if uncommitted changes were made to the data file, they are undone. Without this, a rolled back change could be partially committed, violating the [ACID principles](https://en.wikipedia.org/wiki/ACID) of the database. This phase will perform the rollback of any transactions that were uncommitted at the time of crash, or were rolled back after the final checkpoint. So what can you do about it? ---------------------------- While the database is in recovery, attempts to bring the database online via a `RESTORE` command like this will fail: ``` RESTORE DATABASE CrashTestDummy WITH RECOVERY; ``` SQL Server is *already* attempting to do this. The `RESTORE...WITH RECOVERY;` will simply put the database through the exact same steps in order to bring the database online in a consistent manner. ### Be patient The right thing to do is just be patient. This part of the message from the error log is the one that you should pay attention to: > > No user action is required > > > Note, too, that the time remaining is an estimate. In my experience, it is wildly inaccurate. Sometimes the time remaining will grow larger, rather than reducing. Sometimes it will report a very long completion time, and suddenly complete very fast. Its just an estimate. ### Can you just "throw away" your transaction log and start fresh? **I advise against it.** I would suggest you never, ever do this with a production database. There is a procedure to attach a database without a transaction log, and ask SQL Server to `ATTACH_REBUILD_LOG`. I won't detail all the steps, but the "punchline" for that procedure is to do this: ``` CREATE DATABASE CrashTestDummy ON (FILENAME = 'C:\SQL\MSSQL15.MSSQLSERVER\MSSQL\DATA\CrashTestDummy.mdf') FOR ATTACH_REBUILD_LOG; ``` Running this on a crashed database may result in this error: > > The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure. > Msg 1813, Level 16, State 2, Line 5 > Could not open new database 'CrashTestDummy'. CREATE DATABASE is aborted. > > > In which case, you're stuck. You'll need to use the original transaction log & be patient. Just wait for it to recover.
If you have SQL Server 2019 you can enable accelerated database recovery which is many times faster and can help avoid this problem in the future <https://learn.microsoft.com/en-us/sql/relational-databases/accelerated-database-recovery-concepts?view=sql-server-ver15>
250,903
I have SQL server 2017. I have one 3 TB size database there. Somehow due to long running transaction the database got stuck 'IN Recovery' mode after SQL server Restarted. When I checked the sql error logs it says 2 189 255 seconds remaining (Phase 2 of 3) completed which is almost 25 days. My goal is to bring the database online even if I lose some data. So I've ran below commands but no luck. ``` USE [master] GO RESTORE DATABASE test WITH RECOVERY --Msg 3101, Level 16, State 1, Line 6 --Exclusive access could not be obtained because the database is in use. --Msg 3013, Level 16, State 1, Line 6 --RESTORE DATABASE is terminating abnormally. ALTER DATABASE test SET EMERGENCY; GO --Msg 5011, Level 14, State 7, Line 13 --User does not have permission to alter database 'DragonDriveConnect', the database does not exist, or the database is not in a state that allows access checks. --Msg 5069, Level 16, State 1, Line 13 --ALTER DATABASE statement failed. DBCC CHECKDB (DragonDriveConnect, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS; GO --Msg 922, Level 14, State 1, Line 22 --Database 'DragonDriveConnect' is being recovered. Waiting until recovery is finished. ``` At last I've tried to Delete the database too but that is also not working and giving me error saying Cant Delete. How do I get out of this situation?
2019/10/12
[ "https://dba.stackexchange.com/questions/250903", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/192946/" ]
Patience, patience! Possible causes for the databases to stuck in β€œIn Recovery” mode? * Huge size of transaction log file. * SQL restarted during a long running transaction. * Huge number of VLFs (i.e. virtual Log Files). * Could be a bug in SQL Server which is fixed with the help of some patches. The very first thing that your should do is checking of ERRORLOG. In Errorlog, we should see the very first message in the database (TestMe is the name of my database): **Starting up database β€˜TestMe’.** ``` This means the files are opened and recovery is started. After sometime, you should see phase 1. Recovery of database β€˜TestMe’ (28) is 0% complete (approximately 37 seconds remain). Phase 1 of 3. This is an informational message only. No user action is required. Recovery of database β€˜TestMe’ (28) is 3% complete (approximately 36 seconds remain). Phase 1 of 3. This is an informational message only. No user action is required. ``` Once phase 1 is complete, it would go with Phase 2 and 3. And once it completes, you should use something similar. ``` 3807 transactions rolled forward in database β€˜TestMe’ (28). This is an informational message only. No user action is required. 0 transactions rolled back in database β€˜TestMe’ (28). This is an informational message only. No user action is required. Recovery is writing a checkpoint in database β€˜TestMe’ (28). This is an informational message only. No user action is required. Recovery completed for database TestMe (database ID 28) in 30 second(s) (analysis 1289 ms, redo 29343 ms, undo 72 ms.) This is an informational message only. No user action is required ```
In my case, This issue has been resolved by Restarting SQL Server Service, You can do it from SQL Server Configuration Manager. [![enter image description here](https://i.stack.imgur.com/1nCeM.png)](https://i.stack.imgur.com/1nCeM.png)
250,903
I have SQL server 2017. I have one 3 TB size database there. Somehow due to long running transaction the database got stuck 'IN Recovery' mode after SQL server Restarted. When I checked the sql error logs it says 2 189 255 seconds remaining (Phase 2 of 3) completed which is almost 25 days. My goal is to bring the database online even if I lose some data. So I've ran below commands but no luck. ``` USE [master] GO RESTORE DATABASE test WITH RECOVERY --Msg 3101, Level 16, State 1, Line 6 --Exclusive access could not be obtained because the database is in use. --Msg 3013, Level 16, State 1, Line 6 --RESTORE DATABASE is terminating abnormally. ALTER DATABASE test SET EMERGENCY; GO --Msg 5011, Level 14, State 7, Line 13 --User does not have permission to alter database 'DragonDriveConnect', the database does not exist, or the database is not in a state that allows access checks. --Msg 5069, Level 16, State 1, Line 13 --ALTER DATABASE statement failed. DBCC CHECKDB (DragonDriveConnect, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS; GO --Msg 922, Level 14, State 1, Line 22 --Database 'DragonDriveConnect' is being recovered. Waiting until recovery is finished. ``` At last I've tried to Delete the database too but that is also not working and giving me error saying Cant Delete. How do I get out of this situation?
2019/10/12
[ "https://dba.stackexchange.com/questions/250903", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/192946/" ]
Patience, patience! Possible causes for the databases to stuck in β€œIn Recovery” mode? * Huge size of transaction log file. * SQL restarted during a long running transaction. * Huge number of VLFs (i.e. virtual Log Files). * Could be a bug in SQL Server which is fixed with the help of some patches. The very first thing that your should do is checking of ERRORLOG. In Errorlog, we should see the very first message in the database (TestMe is the name of my database): **Starting up database β€˜TestMe’.** ``` This means the files are opened and recovery is started. After sometime, you should see phase 1. Recovery of database β€˜TestMe’ (28) is 0% complete (approximately 37 seconds remain). Phase 1 of 3. This is an informational message only. No user action is required. Recovery of database β€˜TestMe’ (28) is 3% complete (approximately 36 seconds remain). Phase 1 of 3. This is an informational message only. No user action is required. ``` Once phase 1 is complete, it would go with Phase 2 and 3. And once it completes, you should use something similar. ``` 3807 transactions rolled forward in database β€˜TestMe’ (28). This is an informational message only. No user action is required. 0 transactions rolled back in database β€˜TestMe’ (28). This is an informational message only. No user action is required. Recovery is writing a checkpoint in database β€˜TestMe’ (28). This is an informational message only. No user action is required. Recovery completed for database TestMe (database ID 28) in 30 second(s) (analysis 1289 ms, redo 29343 ms, undo 72 ms.) This is an informational message only. No user action is required ```
If you have SQL Server 2019 you can enable accelerated database recovery which is many times faster and can help avoid this problem in the future <https://learn.microsoft.com/en-us/sql/relational-databases/accelerated-database-recovery-concepts?view=sql-server-ver15>
1,899,529
i have just started using adobe livecycle . i dont need to understand the livecycle with a developers perspective but as of now i have to get into testing livecycle applications. where should i get started so that i understand basics of livecycle. for instance i would like to know what a watched folder is . please refer me to livecycle tutorial
2009/12/14
[ "https://Stackoverflow.com/questions/1899529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/213574/" ]
I'd suggest checking out the Adobe Evangelism Team's Tour de LifeCycle reference: <http://www.adobe.com/devnet/livecycle/tourdelivecycle/> I've found it to be a good centralized point for blogs, turorials and documentation on all things LiveCycle.
You might find the [LiveCycle Application Development Process](http://help.adobe.com/en_US/livecycle/9.0/appDevWorkflow/index.html) useful - it highlights the installation, planning, development, deployment, and maintenance phases of a LiveCycle application. Best of luck! -John
1,899,529
i have just started using adobe livecycle . i dont need to understand the livecycle with a developers perspective but as of now i have to get into testing livecycle applications. where should i get started so that i understand basics of livecycle. for instance i would like to know what a watched folder is . please refer me to livecycle tutorial
2009/12/14
[ "https://Stackoverflow.com/questions/1899529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/213574/" ]
It's important to realise that LiveCycle is a suite of products (Some people even call it a platform). The suite contains many solution components and your approach to testing would probably depend on which components you're working with. Having said that; generally LiveCycle applications involve PDF-based electronic forms that users can fill in online and submit to a BPM server for processing. In more recent times Livecycle can also be seen as the back-end for enterprise-scale Flex applications.
You might find the [LiveCycle Application Development Process](http://help.adobe.com/en_US/livecycle/9.0/appDevWorkflow/index.html) useful - it highlights the installation, planning, development, deployment, and maintenance phases of a LiveCycle application. Best of luck! -John
2,683
Time to get it straight once and for all. When do you / do you not make a Brocho on dessert in a meal (where you washed)?
2010/08/27
[ "https://judaism.stackexchange.com/questions/2683", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/128/" ]
There are a lot of different practices (and I believe a stira in the Mishna Brurah), and it may depend on your practice. BUT: Here's what I was told in yeshiva: Fresh fruit (including "ha'adama fruit" like watermelon and bananas), candy, ice cream -- all get a bracha. Anything mezonos, anything liquid, cooked fruit -- included with the meal.
According to the Sephardim, one is Lechtechila not allowed toto eat cakes or cookies during a meal of bread (Yalkut Yosef, Heleq 3, page 187). He says you must wait until after you finish Birkat HaMazon. EDIT: Because some cakes are Hamotzi and some are Mezonot. This Halacha has a lot of cirumstances. <http://www.dailyhalacha.com/displayRead.asp?readID=1571&txtSearch=eating%20cake%20meal> See this for more details.
2,683
Time to get it straight once and for all. When do you / do you not make a Brocho on dessert in a meal (where you washed)?
2010/08/27
[ "https://judaism.stackexchange.com/questions/2683", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/128/" ]
There are a lot of different practices (and I believe a stira in the Mishna Brurah), and it may depend on your practice. BUT: Here's what I was told in yeshiva: Fresh fruit (including "ha'adama fruit" like watermelon and bananas), candy, ice cream -- all get a bracha. Anything mezonos, anything liquid, cooked fruit -- included with the meal.
This publication is relevant to the conversation: <http://halachayomit.co.il/en/default.aspx?HalachaID=1812> Summary: One should not recite any blessing at all on cakes served at the end of the meal. If the cake, however, contains all three conditions in that its dough is sweet, it is crunchy, and it is filled (like Ma’mool and Baklava), only if the tablecloth was removed and only then was this kind of cake served will one recite the blessing of β€œBorei Minei Mezonot” on it. If even this kind of cake was served without first removing the tablecloth, one does not recite any blessing. It is preferable, however, not to serve any cakes before Birkat HaMazon is recited. <http://halachayomit.co.il/en/default.aspx?HalachaID=1803> Summary: If desserts, such as fruits, assorted nuts, and the like, are served at the end of the meal, one must recite the appropriate blessings on each item, be it β€œBorei Peri Ha’etz”, β€œBorei Peri Ha’adama”, or β€œShehakol Nihya Bidvaro”. Regarding ice cream served at the end of the meal before Birkat HaMazon, according to the letter of the law one may recite the β€œShehakol” blessing on it, however, it is preferable to delay eating the ice cream until after Birkat HaMazon, at which point one may recite a blessing on it according to all opinions. This holds true especially on Shabbat and holiday meals when Kiddush is recited over wine before the meal, as was explained above.
2,683
Time to get it straight once and for all. When do you / do you not make a Brocho on dessert in a meal (where you washed)?
2010/08/27
[ "https://judaism.stackexchange.com/questions/2683", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/128/" ]
According to Sephardi poskim all deserts require their own blessing. In most sephardi homes on shabat they typically strive to bring out something for each of the berakhot(mezunot, eitz, adamah, hakol).
According to the Sephardim, one is Lechtechila not allowed toto eat cakes or cookies during a meal of bread (Yalkut Yosef, Heleq 3, page 187). He says you must wait until after you finish Birkat HaMazon. EDIT: Because some cakes are Hamotzi and some are Mezonot. This Halacha has a lot of cirumstances. <http://www.dailyhalacha.com/displayRead.asp?readID=1571&txtSearch=eating%20cake%20meal> See this for more details.
2,683
Time to get it straight once and for all. When do you / do you not make a Brocho on dessert in a meal (where you washed)?
2010/08/27
[ "https://judaism.stackexchange.com/questions/2683", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/128/" ]
According to Sephardi poskim all deserts require their own blessing. In most sephardi homes on shabat they typically strive to bring out something for each of the berakhot(mezunot, eitz, adamah, hakol).
This publication is relevant to the conversation: <http://halachayomit.co.il/en/default.aspx?HalachaID=1812> Summary: One should not recite any blessing at all on cakes served at the end of the meal. If the cake, however, contains all three conditions in that its dough is sweet, it is crunchy, and it is filled (like Ma’mool and Baklava), only if the tablecloth was removed and only then was this kind of cake served will one recite the blessing of β€œBorei Minei Mezonot” on it. If even this kind of cake was served without first removing the tablecloth, one does not recite any blessing. It is preferable, however, not to serve any cakes before Birkat HaMazon is recited. <http://halachayomit.co.il/en/default.aspx?HalachaID=1803> Summary: If desserts, such as fruits, assorted nuts, and the like, are served at the end of the meal, one must recite the appropriate blessings on each item, be it β€œBorei Peri Ha’etz”, β€œBorei Peri Ha’adama”, or β€œShehakol Nihya Bidvaro”. Regarding ice cream served at the end of the meal before Birkat HaMazon, according to the letter of the law one may recite the β€œShehakol” blessing on it, however, it is preferable to delay eating the ice cream until after Birkat HaMazon, at which point one may recite a blessing on it according to all opinions. This holds true especially on Shabbat and holiday meals when Kiddush is recited over wine before the meal, as was explained above.
2,683
Time to get it straight once and for all. When do you / do you not make a Brocho on dessert in a meal (where you washed)?
2010/08/27
[ "https://judaism.stackexchange.com/questions/2683", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/128/" ]
Regarding mezonos (mentioned quickly in a comment on a different answer): Bread is Hamotzi, and therefore one doesn't make a beracha on it since it is included in the Hamotzi at the beginning of the meal. Cake is Mezonos and one would make a beracha on it when it is eaten as dessert. The question of making a beracha on a mezonos dessert depends on what is considered "Pas/Bread" vs. "Pas Haba BeKisnin/Cake". There are 3 possibilities cited in SH"A (really simplifying here): * Sweetened dough * Filled dough * Hard dough If the desert you're eating satisfies all three, it is definitely a Mezonos (and not a Hamotzi) and therefore one makes a Mezonos when eaten as dessert. A good example are hamentaschen. However, if it satisfies only one (possibly even two) of the conditions, no beracha.
According to the Sephardim, one is Lechtechila not allowed toto eat cakes or cookies during a meal of bread (Yalkut Yosef, Heleq 3, page 187). He says you must wait until after you finish Birkat HaMazon. EDIT: Because some cakes are Hamotzi and some are Mezonot. This Halacha has a lot of cirumstances. <http://www.dailyhalacha.com/displayRead.asp?readID=1571&txtSearch=eating%20cake%20meal> See this for more details.
2,683
Time to get it straight once and for all. When do you / do you not make a Brocho on dessert in a meal (where you washed)?
2010/08/27
[ "https://judaism.stackexchange.com/questions/2683", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/128/" ]
Regarding mezonos (mentioned quickly in a comment on a different answer): Bread is Hamotzi, and therefore one doesn't make a beracha on it since it is included in the Hamotzi at the beginning of the meal. Cake is Mezonos and one would make a beracha on it when it is eaten as dessert. The question of making a beracha on a mezonos dessert depends on what is considered "Pas/Bread" vs. "Pas Haba BeKisnin/Cake". There are 3 possibilities cited in SH"A (really simplifying here): * Sweetened dough * Filled dough * Hard dough If the desert you're eating satisfies all three, it is definitely a Mezonos (and not a Hamotzi) and therefore one makes a Mezonos when eaten as dessert. A good example are hamentaschen. However, if it satisfies only one (possibly even two) of the conditions, no beracha.
This publication is relevant to the conversation: <http://halachayomit.co.il/en/default.aspx?HalachaID=1812> Summary: One should not recite any blessing at all on cakes served at the end of the meal. If the cake, however, contains all three conditions in that its dough is sweet, it is crunchy, and it is filled (like Ma’mool and Baklava), only if the tablecloth was removed and only then was this kind of cake served will one recite the blessing of β€œBorei Minei Mezonot” on it. If even this kind of cake was served without first removing the tablecloth, one does not recite any blessing. It is preferable, however, not to serve any cakes before Birkat HaMazon is recited. <http://halachayomit.co.il/en/default.aspx?HalachaID=1803> Summary: If desserts, such as fruits, assorted nuts, and the like, are served at the end of the meal, one must recite the appropriate blessings on each item, be it β€œBorei Peri Ha’etz”, β€œBorei Peri Ha’adama”, or β€œShehakol Nihya Bidvaro”. Regarding ice cream served at the end of the meal before Birkat HaMazon, according to the letter of the law one may recite the β€œShehakol” blessing on it, however, it is preferable to delay eating the ice cream until after Birkat HaMazon, at which point one may recite a blessing on it according to all opinions. This holds true especially on Shabbat and holiday meals when Kiddush is recited over wine before the meal, as was explained above.
4,312,391
I'm looking for possibly efficient algorithm to detect "win" situation in a gomoku (five-in-a-row) game, played on a 19x19 board. Win situation happens when one of the players manages to get five and NO MORE than five "stones" in a row (horizontal, diagonal or vertical). I have the following data easily accessible: * previous moves ("stones") of both players stored in a 2d array (can be also json notation object), with variables "B" and "W" to difference players from each other, * "coordinates" of the incoming move (move.x, move.y), * number of moves each player did I'm doing it in javascript, but any solution that doesn't use low-level stuff like memory allocation nor higher-level (python) array operations would be good. I've found similiar question ( [Detect winning game in nought and crosses](https://stackoverflow.com/questions/2670217/detect-winning-game-in-nought-and-crosses) ), but solutions given there only refer to small boards (5x5 etc).
2010/11/30
[ "https://Stackoverflow.com/questions/4312391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183918/" ]
A simple to understand solution without excessive loops (only pseudocode provided, let me know if you need more explanation): I assume your 2-d array runs like this: ``` board = [ [...], [...], [...], ... ]; ``` I.e. the inner arrays represent the horizontal rows of the board. I also assume that the array is populated by "b", "w", and "x", representing black pieces, white pieces, and empty squares, respectively. My solution is somewhat divide-and-conquer, so I've divided it into the 3 cases below. Bear with me, it may seem more complex than simply running multiple nested loops at first, but the concept is easy to understand, read, and with the right approach, quite simple to code. Horizontal lines ================ Let's first consider the case of detecting a win situation ONLY if the line is horizontal - this is the easiest. First, join a row into a single string, using something like `board[0].join("")`. Do this for each row. You end up with an array like this: ``` rows = [ "bxwwwbx...", "xxxwbxx...", "wwbbbbx...", ... ] ``` Now join THIS array, but inserting an "x" between elements to separate each row: `rows.join("x")`. Now you have one long string representing your board, and it's simply a matter of applying a regexp to find consecutive "w" or "b" of exactly 5 length: `superString.test(/(b{5,5})|(w{5,5})/)`. If the test returns `true` you have a win situation. If not, let's move on to vertical lines. Vertical lines ============== You want to reuse the above code, so create a function `testRows` for it. Testing for vertical lines is exactly the same process, but you want to **transpose** the board, so that rows become columns and columns become rows. Then you apply the same `testRows` function. Transposing can be done by copying values into a new 2-d array, or by writing a simple `getCol` function and using that within `testRows`. Diagonal lines ============== Again, we want to reuse the `testRows' function. A diagonal such as this: ``` b x x x x x b x x x x x b x x x x x b x x x x x b ``` Can be converted to a vertical such as this: ``` b x x x x b x x x b x x b x b ``` By shifting row `i` by `i` positions. Now it's a matter of transposing and we are back at testing for horizontals. You'll need to do the same for diagonals that go the other way, but this time shift row `i` by `length - 1 - i` positions, or in your case, `18 - i` positions. Functional javascript ===================== As a side note, my solution fits nicely with functional programming, which means that it can be quite easily coded if you have functional programming tools with you, though it's not necessary. I recommend using [underscore.js](http://documentcloud.github.com/underscore/) as it's quite likely you'll need basic tools like `map`, `reduce` and `filter` in many different game algorithms. For example, my section on testing horizontal lines can be written in one line of javascript with the use of `map`: ``` _(board).map(function (row) {return row.join("")}).join("x").test(/(b{5,5})|(w{5,5})/); ```
untested: ``` int left = max(0, move.x-5), right = min(width-1, move.x+5), top = max(0, move.y-5), bottom = min(width-1, move.y+5); // check the primary diagonal (top-left to bottom-right) for (int x = left, y = top; x <= right && y <= bottom; x++, y++) { for (int count = 0; x <= right && y <= bottom && stones[x][y] == lastPlayer; x++, y++, count++) { if (count >= 5) return true; } } // check the secondary diagonal (top-right to bottom-left) // ... // check the horizontal // ... // check the vertical // ... return false; ``` alternatively, if you don't like the nested loops (untested): ``` // check the primary diagonal (top-left to bottom-right) int count = 0, maxCount = 0; for (int x = left, y = top; x <= right && y <= bottom; x++, y++) { if (count < 5) { count = stones[x][y] == lastPlayer ? count + 1 : 0; } else { return true; } } ```
4,312,391
I'm looking for possibly efficient algorithm to detect "win" situation in a gomoku (five-in-a-row) game, played on a 19x19 board. Win situation happens when one of the players manages to get five and NO MORE than five "stones" in a row (horizontal, diagonal or vertical). I have the following data easily accessible: * previous moves ("stones") of both players stored in a 2d array (can be also json notation object), with variables "B" and "W" to difference players from each other, * "coordinates" of the incoming move (move.x, move.y), * number of moves each player did I'm doing it in javascript, but any solution that doesn't use low-level stuff like memory allocation nor higher-level (python) array operations would be good. I've found similiar question ( [Detect winning game in nought and crosses](https://stackoverflow.com/questions/2670217/detect-winning-game-in-nought-and-crosses) ), but solutions given there only refer to small boards (5x5 etc).
2010/11/30
[ "https://Stackoverflow.com/questions/4312391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183918/" ]
Even though this is a really old question I want to provide my answer because I took a deeper look into this problem today and solved it in a much (much) more efficient way. I'm using a bit board, which is used in most of the board games and engines (chess engines) due to the efficiency, to represent my field. You can do everything you need in this game with bitwise operations. A bit can just have 2 states (0 and 1) however what we need are 3 states e.g. p1, p2 or empty. To solve this problem we're going to have 2 boards instead, one for each player. Another problem is that Gomoku has a lot of fields (19x19) and there is no number type that has that many bits to represent the field. We will use an array of numbers to represent each line and just use the first lsb 15bits of it. Vertical rows ------------- A simplified board of player 1 could look like this ``` 000000 101100 001000 011000 000000 ``` Lets say we want to detect 3 in a row. We take the first 3 rows(0-2) and took at them. ``` 000000 001100 101000 ``` With the & (AND) operator you can check if there is a 1 in every row. ``` var result = field[player][0] & field[player][1] & field[player][2]; ``` In this case the result will be 0 which means no winner. Lets continue... The next step is to take rows 1-3 ``` 101100 001000 011000 ``` Apply the AND again and that we will get is `001000`. We don't have to care what number this is, just if it's 0 or not. (result != 0) Horizontal rows --------------- Ok now we can detect vertical rows. To detect the horizontal rows we need to save another 2 boards, again one for each player. But we need to invert x and y axis. Then we can do the same check again to detect horizontal lines. Your array would then be: ``` //[player][hORv][rows] var field[2][2][19]; ``` Diagonals :) ------------ The trickiest part are the diagonals of course but with a simple trick you can do the same check as above. A simple board: ``` 000000 010000 001000 000100 000000 ``` Basically we do the same as above but before we do that we need to shift the rows. Lets say we're at row 1-3. ``` 010000 001000 000100 ``` The first row stays as it is. Then you shift the second row one to the left and the third 2 to the left. ``` var r0 = field[0][0][i]; var r1 = field[0][0][i+1] << 1; var r2 = field[0][0][i+2] << 2; ``` What you will get is: ``` 010000 010000 010000 ``` Apply AND you can have your win detection. To get the other diagonal direction just do it again, but instead of shifting to the left <<, shift to the right >> I hopes this helps someone.
untested: ``` int left = max(0, move.x-5), right = min(width-1, move.x+5), top = max(0, move.y-5), bottom = min(width-1, move.y+5); // check the primary diagonal (top-left to bottom-right) for (int x = left, y = top; x <= right && y <= bottom; x++, y++) { for (int count = 0; x <= right && y <= bottom && stones[x][y] == lastPlayer; x++, y++, count++) { if (count >= 5) return true; } } // check the secondary diagonal (top-right to bottom-left) // ... // check the horizontal // ... // check the vertical // ... return false; ``` alternatively, if you don't like the nested loops (untested): ``` // check the primary diagonal (top-left to bottom-right) int count = 0, maxCount = 0; for (int x = left, y = top; x <= right && y <= bottom; x++, y++) { if (count < 5) { count = stones[x][y] == lastPlayer ? count + 1 : 0; } else { return true; } } ```
4,312,391
I'm looking for possibly efficient algorithm to detect "win" situation in a gomoku (five-in-a-row) game, played on a 19x19 board. Win situation happens when one of the players manages to get five and NO MORE than five "stones" in a row (horizontal, diagonal or vertical). I have the following data easily accessible: * previous moves ("stones") of both players stored in a 2d array (can be also json notation object), with variables "B" and "W" to difference players from each other, * "coordinates" of the incoming move (move.x, move.y), * number of moves each player did I'm doing it in javascript, but any solution that doesn't use low-level stuff like memory allocation nor higher-level (python) array operations would be good. I've found similiar question ( [Detect winning game in nought and crosses](https://stackoverflow.com/questions/2670217/detect-winning-game-in-nought-and-crosses) ), but solutions given there only refer to small boards (5x5 etc).
2010/11/30
[ "https://Stackoverflow.com/questions/4312391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/183918/" ]
A simple to understand solution without excessive loops (only pseudocode provided, let me know if you need more explanation): I assume your 2-d array runs like this: ``` board = [ [...], [...], [...], ... ]; ``` I.e. the inner arrays represent the horizontal rows of the board. I also assume that the array is populated by "b", "w", and "x", representing black pieces, white pieces, and empty squares, respectively. My solution is somewhat divide-and-conquer, so I've divided it into the 3 cases below. Bear with me, it may seem more complex than simply running multiple nested loops at first, but the concept is easy to understand, read, and with the right approach, quite simple to code. Horizontal lines ================ Let's first consider the case of detecting a win situation ONLY if the line is horizontal - this is the easiest. First, join a row into a single string, using something like `board[0].join("")`. Do this for each row. You end up with an array like this: ``` rows = [ "bxwwwbx...", "xxxwbxx...", "wwbbbbx...", ... ] ``` Now join THIS array, but inserting an "x" between elements to separate each row: `rows.join("x")`. Now you have one long string representing your board, and it's simply a matter of applying a regexp to find consecutive "w" or "b" of exactly 5 length: `superString.test(/(b{5,5})|(w{5,5})/)`. If the test returns `true` you have a win situation. If not, let's move on to vertical lines. Vertical lines ============== You want to reuse the above code, so create a function `testRows` for it. Testing for vertical lines is exactly the same process, but you want to **transpose** the board, so that rows become columns and columns become rows. Then you apply the same `testRows` function. Transposing can be done by copying values into a new 2-d array, or by writing a simple `getCol` function and using that within `testRows`. Diagonal lines ============== Again, we want to reuse the `testRows' function. A diagonal such as this: ``` b x x x x x b x x x x x b x x x x x b x x x x x b ``` Can be converted to a vertical such as this: ``` b x x x x b x x x b x x b x b ``` By shifting row `i` by `i` positions. Now it's a matter of transposing and we are back at testing for horizontals. You'll need to do the same for diagonals that go the other way, but this time shift row `i` by `length - 1 - i` positions, or in your case, `18 - i` positions. Functional javascript ===================== As a side note, my solution fits nicely with functional programming, which means that it can be quite easily coded if you have functional programming tools with you, though it's not necessary. I recommend using [underscore.js](http://documentcloud.github.com/underscore/) as it's quite likely you'll need basic tools like `map`, `reduce` and `filter` in many different game algorithms. For example, my section on testing horizontal lines can be written in one line of javascript with the use of `map`: ``` _(board).map(function (row) {return row.join("")}).join("x").test(/(b{5,5})|(w{5,5})/); ```
Even though this is a really old question I want to provide my answer because I took a deeper look into this problem today and solved it in a much (much) more efficient way. I'm using a bit board, which is used in most of the board games and engines (chess engines) due to the efficiency, to represent my field. You can do everything you need in this game with bitwise operations. A bit can just have 2 states (0 and 1) however what we need are 3 states e.g. p1, p2 or empty. To solve this problem we're going to have 2 boards instead, one for each player. Another problem is that Gomoku has a lot of fields (19x19) and there is no number type that has that many bits to represent the field. We will use an array of numbers to represent each line and just use the first lsb 15bits of it. Vertical rows ------------- A simplified board of player 1 could look like this ``` 000000 101100 001000 011000 000000 ``` Lets say we want to detect 3 in a row. We take the first 3 rows(0-2) and took at them. ``` 000000 001100 101000 ``` With the & (AND) operator you can check if there is a 1 in every row. ``` var result = field[player][0] & field[player][1] & field[player][2]; ``` In this case the result will be 0 which means no winner. Lets continue... The next step is to take rows 1-3 ``` 101100 001000 011000 ``` Apply the AND again and that we will get is `001000`. We don't have to care what number this is, just if it's 0 or not. (result != 0) Horizontal rows --------------- Ok now we can detect vertical rows. To detect the horizontal rows we need to save another 2 boards, again one for each player. But we need to invert x and y axis. Then we can do the same check again to detect horizontal lines. Your array would then be: ``` //[player][hORv][rows] var field[2][2][19]; ``` Diagonals :) ------------ The trickiest part are the diagonals of course but with a simple trick you can do the same check as above. A simple board: ``` 000000 010000 001000 000100 000000 ``` Basically we do the same as above but before we do that we need to shift the rows. Lets say we're at row 1-3. ``` 010000 001000 000100 ``` The first row stays as it is. Then you shift the second row one to the left and the third 2 to the left. ``` var r0 = field[0][0][i]; var r1 = field[0][0][i+1] << 1; var r2 = field[0][0][i+2] << 2; ``` What you will get is: ``` 010000 010000 010000 ``` Apply AND you can have your win detection. To get the other diagonal direction just do it again, but instead of shifting to the left <<, shift to the right >> I hopes this helps someone.
4,400,908
I have a package com.supercorp.killerapp and within it is a package(com.supercorp.killerapp.views) if I'm not creating the app with the guiformbuilder: * How do I set the icon of a button on a JInternalFrame that is in the views directory? * In general, how do I access images in a different folder? * Should all my images be contained in a seperate folder? The syntax I'm using is: ``` JButton iconButton = new JButton(new ImageIcon("page_delete.png")); ``` The button isn't displaying the image.
2010/12/09
[ "https://Stackoverflow.com/questions/4400908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383986/" ]
I put in the jar that contains my application, in a package called `com.example.GreatApp.resources` and then load it using: ``` getClassLoader().getResourceAsStream( "com/example/GreatApp/resource/icon.png");` ``` **Update. Full example** ``` /** * Creates and returns an ImageIcon from the resource in jar. * @param location resource location in the jar, * like 'com/example/GreatApp/res/icon.png' or null if it was not found. */ public ImageIcon createImageIconFromResource(String location) throws java.io.IOException { java.io.InputStream input = getClassLoader().getResourceAsStream( location); // or throw an ioexception here aka `file not found` if(input == null) return null; return new ImageIcon(ImageIO.read(input)); } ```
You can put the images anywhere on the classpath. I find it most logical to put them in the root of the project in an "images" folder. Packages map to folders when compiled & packaged so it looks like you need: ``` Image im = Toolkit.getDefaultToolkit().getImage( "/com/supercorp/killerapp/views/page_delete.png" ); JButton iconButton = new JButton( new ImageIcon( im ) ); ```
66,453,074
I'm trying to use `mark_text` to create a stacked text in a stacked bar chart. I would like to label each bar with the value of 'Time'. Is it possible to have text marks in the corresponding stack of a stacked area chart? Here's how I create bar & text chart: ``` bar = alt.Chart(df_pivot, title = {'text' :'How do people spend their time?', 'subtitle' : 'Average of minutes per day from time-use diaries for people between 15 and 64'}).mark_bar().transform_calculate( filtered="datum.Category == 'Paid work'" ).transform_joinaggregate(sort_val="sum(filtered)", groupby=["Country"] ).encode( x=alt.X('Time', stack='zero'), y=alt.Y('Country', sort=alt.SortField('sort_val', order='descending')), color=alt.Color('Category:N', sort=CatOrder), order=alt.Order('color_Category_sort_index:Q'), tooltip=['Country', 'Category', 'Time'] ).interactive() bar ``` [![bar](https://i.stack.imgur.com/hcBUd.png)](https://i.stack.imgur.com/hcBUd.png) ``` text = alt.Chart(df_pivot).mark_text(align='center', baseline='middle', color='black').transform_calculate( filtered="datum.Category == 'Paid work'" ).transform_joinaggregate(sort_val="sum(filtered)", groupby=["Country"] ).encode( x=alt.X('Time:Q', stack='zero'), y=alt.Y('Country', sort=alt.SortField('sort_val', order='descending')), detail='Category:N', text=alt.Text('Time:Q', format='.0f') ) bar + text ``` [![bar+text](https://i.stack.imgur.com/sIxD8.png)](https://i.stack.imgur.com/sIxD8.png) **Issue:** * The text is not in its proper stack & The order of the text is also wrong. * The Y sorting is reset and they are no longer sorted as expected. It's not that I don't understand why I have these issues. I'm new to this platform, the source code via my notebook: <https://www.kaggle.com/interphuoc0101/times-use>. Thanks a lot.
2021/03/03
[ "https://Stackoverflow.com/questions/66453074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15308498/" ]
Your bar chart specifies a stack order: ``` order=alt.Order('color_Category_sort_index:Q'), ``` You should add a matching `order` encoding to your text layer to ensure the text appears in the same order.
Here is an example of how you can use `order` in both charts: ``` import altair as alt from vega_datasets import data source=data.barley() bars = alt.Chart(source).mark_bar().encode( x=alt.X('sum(yield):Q', stack='zero'), y=alt.Y('variety:N'), color=alt.Color('site'), order=alt.Order('color_Category_sort_index:Q'), ) text = alt.Chart(source).mark_text(dx=-15, dy=3, color='white').encode( x=alt.X('sum(yield):Q', stack='zero'), y=alt.Y('variety:N'), detail='site:N', text=alt.Text('sum(yield):Q', format='.1f'), order=alt.Order('color_Category_sort_index:Q') ) bars + text ``` [![enter image description here](https://i.stack.imgur.com/9Nkvw.png)](https://i.stack.imgur.com/9Nkvw.png)
37,134,911
What is the best way to compare two string without case sensitive using c#? Am using the below codes. ``` string b = "b"; int c = string.Compare(a, b); ```
2016/05/10
[ "https://Stackoverflow.com/questions/37134911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3916803/" ]
By explicitly specifying it: ``` int c = string.Compare(a, b, StringComparison.InvariantCultureIgnoreCase) ```
``` String.Equals(stringA, stringB, StringComparison.CurrentCultureIgnoreCase) ```
37,134,911
What is the best way to compare two string without case sensitive using c#? Am using the below codes. ``` string b = "b"; int c = string.Compare(a, b); ```
2016/05/10
[ "https://Stackoverflow.com/questions/37134911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3916803/" ]
By explicitly specifying it: ``` int c = string.Compare(a, b, StringComparison.InvariantCultureIgnoreCase) ```
convert them to lower case then compare, There you go: ``` string b = "b"; string a = ""; int c = string.Compare(a.ToLower(), b.ToLower()); ```
37,134,911
What is the best way to compare two string without case sensitive using c#? Am using the below codes. ``` string b = "b"; int c = string.Compare(a, b); ```
2016/05/10
[ "https://Stackoverflow.com/questions/37134911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3916803/" ]
Try this code ``` int c = string.Compare(a, b,true); ```
``` String.Equals(stringA, stringB, StringComparison.CurrentCultureIgnoreCase) ```
37,134,911
What is the best way to compare two string without case sensitive using c#? Am using the below codes. ``` string b = "b"; int c = string.Compare(a, b); ```
2016/05/10
[ "https://Stackoverflow.com/questions/37134911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3916803/" ]
convert them to lower case then compare, There you go: ``` string b = "b"; string a = ""; int c = string.Compare(a.ToLower(), b.ToLower()); ```
``` String.Equals(stringA, stringB, StringComparison.CurrentCultureIgnoreCase) ```
37,134,911
What is the best way to compare two string without case sensitive using c#? Am using the below codes. ``` string b = "b"; int c = string.Compare(a, b); ```
2016/05/10
[ "https://Stackoverflow.com/questions/37134911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3916803/" ]
Try this code ``` int c = string.Compare(a, b,true); ```
convert them to lower case then compare, There you go: ``` string b = "b"; string a = ""; int c = string.Compare(a.ToLower(), b.ToLower()); ```
62,870,072
I have a router sample below , now how will I get the details of that when it is done navigating on that page or when it reach the user page ?. I wanted to check on my user.component.ts that the navigation comes from this [routerLink]="['user', user.id, 'details']" ``` [routerLink]="['user', user.id, 'details']" ```
2020/07/13
[ "https://Stackoverflow.com/questions/62870072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using `itertools.groupby` ``` from itertools import groupby result = [] for m,n in groupby(a, lambda x: x[1]): n = list(n) result.extend(n + [[sum(int(i) for i, _ in n), ""]]) print(result) ``` **Output:** ``` [['45', '00128'], ['88', '00128'], ['87', '00128'], [220, ''], ['50', '88292'], ['69', '88292'], [119, ''], ['70', '72415'], ['93', '72415'], ['79', '72415'], [242, '']] ``` Edit as per comment ``` for m,n in groupby(a, lambda x: x[1]): n = list(n) val_1, val_2, val_3 = 0, 0, 0 for i in n: val_1 += int(i[0]) #val_2, val_3.... result.extend(n + [[val_1, ""]]) ``` If you can use `numpy` then the sum of axis 0 is simpler **Ex:** ``` for m,n in groupby(a, lambda x: x[1]): n = np.array(list(n), dtype=int) print(np.delete(np.sum(n, axis=0), 1)) ``` --- ``` np.delete --> Delete element in index 1 np.sum with axis=0 --> sum element in column. ```
Looks like you've imported data from a spreadsheet? A very clean way to do this would be to use the `pandas` library, and let it do the data wrangling for you: ```py a = [ ['45', '00128'], ['88', '00128'], ['87', '00128'], ['50', '88292'], ['69', '88292'], ['70', '72415'], ['93', '72415'], ['79', '72415'] ] # Import the library import pandas as pd # Put data into a pandas DataFrame and set column names df = pd.DataFrame(a, columns=['value', 'category']) # Change `value` column to integers df['value'] = df['value'].astype(int) # Group by the `category` column and sum sum_df = df.groupby('category').sum() # Show answer print(sum_df) ``` Should print out the following: ``` value category 00128 220 72415 242 88292 119 ```
62,870,072
I have a router sample below , now how will I get the details of that when it is done navigating on that page or when it reach the user page ?. I wanted to check on my user.component.ts that the navigation comes from this [routerLink]="['user', user.id, 'details']" ``` [routerLink]="['user', user.id, 'details']" ```
2020/07/13
[ "https://Stackoverflow.com/questions/62870072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using `itertools.groupby` ``` from itertools import groupby result = [] for m,n in groupby(a, lambda x: x[1]): n = list(n) result.extend(n + [[sum(int(i) for i, _ in n), ""]]) print(result) ``` **Output:** ``` [['45', '00128'], ['88', '00128'], ['87', '00128'], [220, ''], ['50', '88292'], ['69', '88292'], [119, ''], ['70', '72415'], ['93', '72415'], ['79', '72415'], [242, '']] ``` Edit as per comment ``` for m,n in groupby(a, lambda x: x[1]): n = list(n) val_1, val_2, val_3 = 0, 0, 0 for i in n: val_1 += int(i[0]) #val_2, val_3.... result.extend(n + [[val_1, ""]]) ``` If you can use `numpy` then the sum of axis 0 is simpler **Ex:** ``` for m,n in groupby(a, lambda x: x[1]): n = np.array(list(n), dtype=int) print(np.delete(np.sum(n, axis=0), 1)) ``` --- ``` np.delete --> Delete element in index 1 np.sum with axis=0 --> sum element in column. ```
A pretty raw way of doing it. This is just for knowledge purpose. I would recommend the answer given by Rakesh ``` from collections import defaultdict sums_dict = defaultdict(int) a = [ ['45', '00128'], ['88', '00128'], ['87', '00128'], ['50', '88292'], ['69', '88292'], ['70', '72415'], ['93', '72415'], ['79', '72415'] ] sums_dict = {v:sums_dict[v]+int(k) for k,v in a} for k in sums_dict: index = next((len(a) - i - 1 for i, lst in enumerate(reversed(a)) if k in lst), -1) a.insert(index, [str(sums_dict[k]),""]) a.insert(index+2, ['Total', '']) print(a) ``` Output: ``` [['45', '00128'], ['88', '00128'], ['87', ''], ['87', '00128'], ['Total', ''], ['50', '88292'], ['69', ''], ['69', '88292'], ['Total', ''], ['70', '72415'], ['93', '72415'], ['79', ''], ['79', '72415'], ['Total', '']] ```
47,695
AFAIK people like scripting because it's easier, and it makes development cycle faster. But what about when games are shipped. No one expects shipped binaries to be changed, unless there is an update or a DLC. So why developers don't compile their script files before shipping? **Potential benefits:** 1. Faster run time 2. Obfuscating binary a little mode and I can't think of any possible draw backs. Examples: 1. Civilization 5 had lots of lua scripts inside their assets folder. 2. Angry birds also had a lot those scripts along side binary. 3. Age of Mythology had lots of xs scripts for their AI. 4. Civilization 4 had lots of python scripts. I'm pretty sure the list could have gotten a lot longer if I had more games installed on my device.
2013/01/19
[ "https://gamedev.stackexchange.com/questions/47695", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/7328/" ]
I suspect it's because that one of the advantages of using scripts over C++ code is that there is no compile process so it makes for quick and easy editing during development. Lua also gains no run-time performance from compiling it off-line. [It's just load time it speeds up.](http://www.lua.org/manual/4.0/luac.html) Adding the extra compile step in then just slows down development and makes the process more error-prone (e.g. the script can get out of sync with the compiled version). Compiling all the scripts just before you ship the game has obvious risks that you did all your testing with the scripts in their uncompiled state, and shipping something that's not been tested is a bad idea. On any single player game there's also no harm done if your users want to modify the game in some way by editing scripts.
The reasons for each game is really only known to the developer. I plan on including the scripts in my game for one simple reason, I want users to be able to customize the game. There are a few benefits I can think of for not compiling the scripts: * **User customization**: Allows the users to modify certain aspects of the game play or units in the game. Then users can just drop in new scripts and add a new AI difficulty level or add a custom unit. * **Localization data**: Allows developers to deploy specific data to specific locals without needing to recompile the binary for each location. * **Segregation of code**: The people working on creating the code behind the binary are not necessarily the same people working on the scripts. Keeping them separate means the two groups don't rely on each other. * **Easy updates**: Updating just the scripts is a simpler process and might be easier permission-wise to update files than replacing an executable.
64,216,176
1. I have a Table In SQL. 2. Then I have created one Table-Valued Function named GetTaxDataSet. So when I execute that function with the Where condition, I'm getting the dataset values that I need. 3. Now, I'm trying to get the dataset using the SQL Table-Valued function using C# code. ``` DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(); string sqlSelect = "Select * From [dbo].[fn_GetTaxRuleDataSet] (@TaxID, @TaxRulesID)"; SqlCommand cmd = new SqlCommand(sqlSelect, Sqlconn); SqlParameter param1 = new SqlParameter(); param1.ParameterName = "@ID"; param1.SqlDbType = SqlDbType.Int; param1.ParameterName = "@TaxID"; param1.SqlDbType = SqlDbType.Int; param1.ParameterName = "TaxRulesID"; param1.SqlDbType = SqlDbType.Int; param1.ParameterName = "@EffectiveDate"; param1.SqlDbType = SqlDbType.DateTime; cmd.Parameters.Add(param1); Sqlconn.Open(); //Executing The SqlCommand. SqlDataReader dr = cmd.ExecuteReader(); Console.ReadLine(); ``` Can you guys suggest me with right code? Thanks
2020/10/05
[ "https://Stackoverflow.com/questions/64216176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14376508/" ]
Hope this answer helps you. Just keep in mind that when you create a method with its return type of DataSet, it should also be set to receive the DataSet. ``` public DataSet GetData() { DataSet output = new DataSet(); try { SqlConnection sqlConn = new SqlConnection(connectionString); if (sqlConn.State == ConnectionState.Closed) { sqlConn.Open(); } String sqlSelect = "Select * From [dbo].[fn_GetTaxRuleDataSet] (@TaxID, @TaxRulesID)"; SqlCommand cmd = new SqlCommand(sqlSelect, sqlConn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(output); sqlConn.Close(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", ex.Message, true); return (null); } return output; } ```
The below code worked. This is for the Table-Valued Function. Trying to retrieve the Data from c#. public void fn\_GetTaxCalculationDataSet(int cur\_tax\_calc\_ruleid) { Sqlconn.Open(); //Connection Open ``` //Variables to Store Result from DataSet int TaxCalcRuleID = cur_tax_calc_ruleid; int ScheduleTypeID = 0; int FilingStatusID = 0; int bottomorder = 0; decimal bottom = 0; decimal Amount = 0; decimal plusAmountOfPercentage = 0; try { //Defining The Query. string sqlSelect = "Select * From dbo.[fn_GetTaxCalculationDataSet] (@TaxCalcRuleID)"; SqlCommand cmd = new SqlCommand(sqlSelect, Sqlconn); cmd.Parameters.Add("@TaxCalcRuleID", SqlDbType.Int).Value = cur_tax_calc_ruleid; //Executing The SqlCommand SqlDataReader dr = cmd.ExecuteReader(); Console.WriteLine(Environment.NewLine + "Retrieving CalcData based on TaxRuleID From database..!" + Environment.NewLine); Console.WriteLine("Retriving The Records"); Console.WriteLine("Press Any Key To Continue.....!"); Console.ReadLine(); //Check if have any records..! if (dr.HasRows) { while (dr.Read()) { TaxCalcRuleID = dr.GetInt32(0); ScheduleTypeID = dr.GetInt32(1); FilingStatusID = dr.GetInt32(2); bottomorder = dr.GetInt32(3); bottom = dr.GetDecimal(4); Amount = dr.GetDecimal(5); plusAmountOfPercentage = dr.GetDecimal(6); //Displaying The Retrieved Records or DataSet..! Console.WriteLine("{0},{1},{2},{3},{4},{5},{6}", TaxCalcRuleID.ToString(), ScheduleTypeID, FilingStatusID, bottomorder, bottom, Amount, plusAmountOfPercentage); Console.WriteLine("Press Enter To Close"); Console.ReadLine(); } } else { Console.WriteLine("No Data Found"); } //Data ReaderClosed. dr.Close(); //SQL Connection Closed. Sqlconn.Close(); } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); } } ```
12,259,544
When I enter to my site without using a Google result, I can access without any problems, with and without www. But, when I access throught the Google results, redirects to Google again. This is one of my affected sites: **Before Google Search:** <http://somesite.com/> - All OK <http://www.somesite.com/> - All OK **Using Google Search** <https://www.google.com?q=somesite> - First link refirects to Google **After using Google results, if I access to site typing it:** <http://somesite.com/> - All OK <http://www.somesite.com/> - Redirects to Google
2012/09/04
[ "https://Stackoverflow.com/questions/12259544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989868/" ]
use Firebug(FireFox Add on) to see what is happening ! It will give you more clarity on what is happening.
I had the same problem. It has something to do with https connection. If you are using firefox, read this: <http://forums.mozillazine.org/viewtopic.php?f=38&t=2317787> If you are using Chrome, you can disable google redirecting search results by using this plugin: <https://code.google.com/p/undirect/>
12,118
How can i set my laptop with ubuntu 10.04 to autoconnect to Wi-Fi (with pass, WPA2-Personal), when i on my laptop without asking password on wi-fi? I wont on my laptop and start surfing without enter pass of my wi-fi.
2010/11/08
[ "https://askubuntu.com/questions/12118", "https://askubuntu.com", "https://askubuntu.com/users/2964/" ]
You must be logged-in to get a network connection with NetworkManager. One ugly workaround is to configure the gdm to auto-login, this poses a security threat if someone can physically access your laptop. **System > Administration > Login Screen** ![alt text](https://i.stack.imgur.com/NWs4d.png) Unlock and select "Login as automatically"
You'll want to follow the instructions in this thread - <http://ubuntuforums.org/showthread.php?t=263136> Basically, it comes down to: 1) Generate a PSK via wpa\_supplicant 2) Modify /etc/network/interfaces to use your network settings. A sample: ``` iface eth0 inet static address 192.168.1.15 netmask 255.255.255.0 wireless-essid my_essid gateway 192.168.1.1 scan_ssid=1 proto=WPA RSN key_mgmt=WPA-PSK pairwise=CCMP TKIP group=CCMP TKIP psk=your_psk ```
12,118
How can i set my laptop with ubuntu 10.04 to autoconnect to Wi-Fi (with pass, WPA2-Personal), when i on my laptop without asking password on wi-fi? I wont on my laptop and start surfing without enter pass of my wi-fi.
2010/11/08
[ "https://askubuntu.com/questions/12118", "https://askubuntu.com", "https://askubuntu.com/users/2964/" ]
You must be logged-in to get a network connection with NetworkManager. One ugly workaround is to configure the gdm to auto-login, this poses a security threat if someone can physically access your laptop. **System > Administration > Login Screen** ![alt text](https://i.stack.imgur.com/NWs4d.png) Unlock and select "Login as automatically"
Do you mean your WiFi key or user password. The key is stored like a password, so if you use auto login, you may need to enter your password to gain access. You can stop the password request by opening System->Passwords and Encryption Keys Select Passwords:Login from the passwords tab Right click and select change password Change the password to blank I wouldn't recommend it, but if you are happy with the reduced security it is OK.
12,118
How can i set my laptop with ubuntu 10.04 to autoconnect to Wi-Fi (with pass, WPA2-Personal), when i on my laptop without asking password on wi-fi? I wont on my laptop and start surfing without enter pass of my wi-fi.
2010/11/08
[ "https://askubuntu.com/questions/12118", "https://askubuntu.com", "https://askubuntu.com/users/2964/" ]
You must be logged-in to get a network connection with NetworkManager. One ugly workaround is to configure the gdm to auto-login, this poses a security threat if someone can physically access your laptop. **System > Administration > Login Screen** ![alt text](https://i.stack.imgur.com/NWs4d.png) Unlock and select "Login as automatically"
You'll need to provide a bit more information! Here is my stab at it anyway: Right click on the **networking icon**, select **"edit connection.."** and choose the connection you want to automatically connect with. Make sure the connection has got the **password** saved (enter it in the security tab), then select **"available to all users"** (or something along those lines, check box in the lower left) and click **apply**. Network Manager will now no longer ask you for a password for this connection. The Gnome Keyring Manager should not ask you either, given you're logged in. If it keeps asking, perhaps another application is requesting a password? Edit: I just noticed the big check box right under the name of the network, in the "edit connection" dialog, where it says: "Connect automatically". I presume it's enabled. Notice, you can check this box on multiple connections.
15,935,752
I am using ec2 instance @ ubuntu . I am trying to automatically do "git pull" after i launched a new instance from my AMI. The repo dir is already in my AMI, all i need is update the repo. what i am doing now is I put "git pull origin master" in rc.local.... but it doesn't work....
2013/04/10
[ "https://Stackoverflow.com/questions/15935752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410231/" ]
`git --git-dir=some/dir/.git pull origin master` should work
The right place to put the code is not `/etc/rc.local/` but `~/.profile`. You can then run commands as the logged in user without the need for `sudo` or `su` to change the user running the commands.
15,935,752
I am using ec2 instance @ ubuntu . I am trying to automatically do "git pull" after i launched a new instance from my AMI. The repo dir is already in my AMI, all i need is update the repo. what i am doing now is I put "git pull origin master" in rc.local.... but it doesn't work....
2013/04/10
[ "https://Stackoverflow.com/questions/15935752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410231/" ]
`git --git-dir=some/dir/.git pull origin master` should work
Taking notes from <https://stackoverflow.com/a/8880633/659188> and your working answer above, you could apply this to potentially multiple folders by doing something like this in your `rc.local` file (also only pulls current branch instead of always being master): ``` #!/bin/bash -e # /etc/rc.local # Ensure folders in array have a trailing slash! declare -a folders=("/var/www/html/project1/" "/var/www/html/project2/" "/some/other/location/") # Update to latest in all above folders for i in "${folders[@]}" do sudo -u ubuntu -i git --git-dir=$i/.git --work-tree=$i fetch origin sudo -u ubuntu -i git --git-dir=$i/.git --work-tree=$i pull done exit 0 ```
15,935,752
I am using ec2 instance @ ubuntu . I am trying to automatically do "git pull" after i launched a new instance from my AMI. The repo dir is already in my AMI, all i need is update the repo. what i am doing now is I put "git pull origin master" in rc.local.... but it doesn't work....
2013/04/10
[ "https://Stackoverflow.com/questions/15935752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410231/" ]
`git --git-dir=some/dir/.git pull origin master` should work
If you want to do the `git pull` when the instance has been created (first boot), you could use [cloud-init](https://cloud-init.io/). Check the AWS docs [To pass a shell script to an instance with user data](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) This could be automated by using [ansible](http://docs.ansible.com/)/[saltstack](https://docs.saltstack.com) etc but for testing, you could manually upload your script. In step 3 "Configure instance" in the Advance Details, select option As file and put the script below. [![enter image description here](https://i.stack.imgur.com/sV0ca.png)](https://i.stack.imgur.com/sV0ca.png) You could upload there your custom script: ``` #!/bin/sh echo "git pull or any other custom commands here" ```
15,935,752
I am using ec2 instance @ ubuntu . I am trying to automatically do "git pull" after i launched a new instance from my AMI. The repo dir is already in my AMI, all i need is update the repo. what i am doing now is I put "git pull origin master" in rc.local.... but it doesn't work....
2013/04/10
[ "https://Stackoverflow.com/questions/15935752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410231/" ]
I got it to work.. sudo -u ubuntu -i git --git-dir=/home/ubuntu/blastoff/.git --work-tree=/home/ubuntu/blastoff/ fetch origin sudo -u ubuntu -i git --git-dir=/home/ubuntu/blastoff/.git --work-tree=/home/ubuntu/blastoff/ merge origin/master
The right place to put the code is not `/etc/rc.local/` but `~/.profile`. You can then run commands as the logged in user without the need for `sudo` or `su` to change the user running the commands.
15,935,752
I am using ec2 instance @ ubuntu . I am trying to automatically do "git pull" after i launched a new instance from my AMI. The repo dir is already in my AMI, all i need is update the repo. what i am doing now is I put "git pull origin master" in rc.local.... but it doesn't work....
2013/04/10
[ "https://Stackoverflow.com/questions/15935752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410231/" ]
I got it to work.. sudo -u ubuntu -i git --git-dir=/home/ubuntu/blastoff/.git --work-tree=/home/ubuntu/blastoff/ fetch origin sudo -u ubuntu -i git --git-dir=/home/ubuntu/blastoff/.git --work-tree=/home/ubuntu/blastoff/ merge origin/master
Taking notes from <https://stackoverflow.com/a/8880633/659188> and your working answer above, you could apply this to potentially multiple folders by doing something like this in your `rc.local` file (also only pulls current branch instead of always being master): ``` #!/bin/bash -e # /etc/rc.local # Ensure folders in array have a trailing slash! declare -a folders=("/var/www/html/project1/" "/var/www/html/project2/" "/some/other/location/") # Update to latest in all above folders for i in "${folders[@]}" do sudo -u ubuntu -i git --git-dir=$i/.git --work-tree=$i fetch origin sudo -u ubuntu -i git --git-dir=$i/.git --work-tree=$i pull done exit 0 ```
15,935,752
I am using ec2 instance @ ubuntu . I am trying to automatically do "git pull" after i launched a new instance from my AMI. The repo dir is already in my AMI, all i need is update the repo. what i am doing now is I put "git pull origin master" in rc.local.... but it doesn't work....
2013/04/10
[ "https://Stackoverflow.com/questions/15935752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1410231/" ]
I got it to work.. sudo -u ubuntu -i git --git-dir=/home/ubuntu/blastoff/.git --work-tree=/home/ubuntu/blastoff/ fetch origin sudo -u ubuntu -i git --git-dir=/home/ubuntu/blastoff/.git --work-tree=/home/ubuntu/blastoff/ merge origin/master
If you want to do the `git pull` when the instance has been created (first boot), you could use [cloud-init](https://cloud-init.io/). Check the AWS docs [To pass a shell script to an instance with user data](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) This could be automated by using [ansible](http://docs.ansible.com/)/[saltstack](https://docs.saltstack.com) etc but for testing, you could manually upload your script. In step 3 "Configure instance" in the Advance Details, select option As file and put the script below. [![enter image description here](https://i.stack.imgur.com/sV0ca.png)](https://i.stack.imgur.com/sV0ca.png) You could upload there your custom script: ``` #!/bin/sh echo "git pull or any other custom commands here" ```
41,978,225
I have fetched an HTML page,How i can replace relative img src with these URLs absolute? In my content html: ``` <img width="23" height="23" class="img" src="/static/img/facebook.png" alt="Facebook"> <img width="23" height="23" class="img" src="/static/img/tw.png" alt="tw"> ``` (Paths not stable) ``` <img width="130" =="" height="200" alt="" src="http://otherdomain/files/ads/00905819.gif"> ``` in html contents i have other images src with absolute src,i want change only relative src images. ex : ``` <img width="23" height="23" class="img" src="/static/img/facebook.png" alt="Facebook"> <img width="23" height="23" class="img" src="/images/xx.png" alt="xxx"> ``` to ``` <img width="23" height="23" class="img" src="http://example.com/static/img/facebook.png" alt="Facebook"> ``` My preg\_replace: ``` $html = preg_replace("(]*src\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)", '$1http://www.example.com$2$3', $x1); ``` But this replace all images src
2017/02/01
[ "https://Stackoverflow.com/questions/41978225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950500/" ]
Try using this code, it should work in your case. ``` $html = str_replace('src="/static', 'src="http://example.com/static', $html); ```
If you know that your relative path always starts with `'/static/img/'` then you can use simple `str_replace` function instead of regexp. For example: ``` $html = str_replace('src="/static/img/', 'src="http://example.com/static/img/', $html); ```
67,952,611
I want to run an npm script that needs the server to be up for the duration the script is being run. My script is like this ``` "scripts" :{ "start": "tsc && node dist/app.js"} ``` That is my basic script to start my server which works fine. However, I have a script within my node project called `get_data.js` that I will use to collect data and save to a database (`npm run save_data`). I want the server to be stopped when `get_data.js` finishes as I am just interested in getting data. ``` "scripts" :{ "start": "tsc && node dist/app.js", "save_data": "tsc && node dist/get_data.js" } ``` Obviously my `save_data` script is not right. Any ideas or recommendation what I can do?
2021/06/12
[ "https://Stackoverflow.com/questions/67952611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4652113/" ]
I may be misinterpreting your question but i think what you want is `process.exit(0);` At the end of "get\_data.js" or whenever youve determined that you want the process to end in your script. (Although i should note that get\_data.js should run its course and end itself unless there is something in your code that is preventing this.)
You can directly call `save_data` inside `start`: ```js "start": "tsc && node dist/app.js && npm run save_data" ```
36,228,977
I want to pass a dictionary as an additional argument to a function. The function is to be applied over each row of a data frame. So I use 'apply'. Below I have a small example of my attempt: ``` import pandas as pd import numpy as np def fun(df_row, dict1): return df_row['A']*2*max(dict1['x']) df = pd.DataFrame(np.random.randn(6,2),columns=list('AB')) dict_test = {'x': [1,2,3,4], 'y': [5,6,7,8]} df['D'] = df.apply(fun, args = (dict_test), axis = 1) ``` I get the following error message: ('fun() takes exactly 1 argument (3 given)', u'occurred at index 0') I use \*\*dict1 to indicate key-value pairs in the function 'fun' Curiously enough if I pass two arguements, things work fine ``` def fun(df_row, dict1, dict2): return df_row['A']*2*max(dict1['x']) df = pd.DataFrame(np.random.randn(6,2),columns=list('AB')) dict_test = {'x': [1,2,3,4], 'y': [5,6,7,8]} df['D'] = df.apply(fun, axis = 1, args = (dict_test, dict_test)) ```
2016/03/25
[ "https://Stackoverflow.com/questions/36228977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/491410/" ]
The problem is that you are not passing a tuple, `(dict_test)` is not a tuple, it's just the same as `dict_test`. You want a tuple with `dict_test` as the only element, that is `(dict_test,)`. ``` df['D'] = df.apply(fun, args=(dict_test,), axis=1) ```
From `pd.DataFrame.apply` doc: > > > ``` > Parameters > ---------- > ... > args : tuple > Positional arguments to pass to function in addition to the > array/series > Additional keyword arguments will be passed as keywords to the function > > ``` > > That last line means that if you want to unpack `dict_test` to pass arguments *as keywords* to `fun`, you can do: ``` df['D'] = df.apply(fun, axis=1, **dict_test) ``` Previously you were using: ``` df['D'] = df.apply(fun, args = (dict_test), axis = 1) ``` That means `apply` will try to call `fun` this way: ``` fun(df_row, dict_test) ``` But this is **not** how you defined `fun` (you'll get the difference once you know a bit more about positional and keyword arguments).
79,947
I'm trying to read 4 ints in C in a golfing challenge and I'm bothered by the length of the code that I need to solve it: ``` scanf("%d%d%d%d",&w,&x,&y,&z) ``` that's 29 chars, which is huge considering that my total code size is 101 chars. I can rid of the first int since I don't really need it, so I get this code: ``` scanf("%*d%d%d%d",&x,&y,&z) ``` which is 27 chars, but it's still lengthy. So my question is, is there any other way (tricks, functions, K&R stuff) to read ints that I don't know of that could help me reduce this bit of code? --- Some users have reported that my question is similar to [Tips for golfing in C](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c) While this topic contain a lot of useful information to shorten C codes, it isn't relevant to my actual use case since it doesn't provide a better way to read inputs. I don't know if there is actually a better way than scanf to read multiple integers (that's why I'm asking the question in the first place), but if there is, I think my question is relevant and is sufficiently different than global tips and tricks. If there is no better way, my question can still be useful in the near future if someone find a better solution. I'm looking for a full program (so no function trick) and all libraries possible. It needs to be C, not C++. Currently, my whole program looks like this: ``` main(w,x,y,z){scanf("%*d%d%d%d",&x,&y,&z)} ``` Any tricks are welcome, as long as they shorten the code (this is code golf) and work in C rather than C++.
2016/05/15
[ "https://codegolf.stackexchange.com/questions/79947", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/53734/" ]
Thanks to @DialFrost for drawing my attention to this question. I believe for reading 4 numbers your solution is optimal. However, I found a solution that saves bytes when reading 5 or more numbers at a time. It will also consume the entire input (i.e. it can't be used in a loop). Depending on the context it might help you with only 4 variables too If you define your variables in a sequence like this: ```c a,b,c,d,e;main(){ ``` In this case, the variables will be layed out in successive memory addresses, we can abuse that. ```c for(;~scanf("%d",&a+e);e++); ``` Full program: ```c // new a,b,c,d,e;main(){for(;~scanf("%d",&a+e);e++);} // original a,b,c,d;main(e){scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);} ``` This 29 byte segment will paste all the input in successive variables starting in `a`. We re-use `e`, (the last variable) as the index variable. This saves declaring one variable. Size comparison --------------- | Number of inputs | Original | New | Original (full program) | new (full program) | | --- | --- | --- | --- | --- | | 1 | 14 | 28 | 24 | 38 | | 2 | 19 | 28 | 31 | 40 | | 3 | 24 | 28 | 38 | 42 | | 4 | 29 | 28 | 45 | 44 | | 5 | 34 | 28 | 52 | 46 | | 6 | 39 | 28 | 59 | 48 | Note that the new method gains a 1 byte disadvantage in full programs because you can't use function arguments, however, this doesn't matter if you can use another variable as the argument to `main`. Note there is also a slot in the initialization portion of the for loop. If you can put another expression there this method can save 1 byte even with only 4 arguments. [Try it online!](https://tio.run/##S9YtSU7@n6iTpJOsk6KTap2bmJmnoVn9Py2/SMPawKY4OTEvTUNJNUVJRy1RO1XTOlVbW9P6f0FRZl4JWBwGlXTgZmha1/43VDBSMFYwUTAFAA "C (tcc) – Try It Online") @JDT ponted out you can save 1 byte at the cost of having 1 added to `e` at the end: ``` for(;0<scanf("%d",&a+e++);); ```
If you want to e.g. print all the inputs then we have this, being 64 bytes long: ``` main(x,y,z){scanf("%*d%d%d%d",&x,&y,&z);printf("%d%d%d",x,y,z);} ``` We can actually shorten this with a loop, bringing the total down to 47 bytes: ``` main(z){for(;scanf("%d",&z)>0;)printf("%d",z);} ``` So the reading part is only [23 bytes long](https://tio.run/##S9YtSU7@/z83MTNPo0qzOi2/SMO6ODkxL01DSTVFR0lHrUrTzsBas6AoM68ELKakU6VpXfv/v6EOGAIA): ``` for(;scanf("%d",&z)>0;) ``` Note that this only works when you don't want to assign a value to a specific variable and only want to **read** the values. [A method that is 29 bytes long](https://tio.run/##S9YtSU7@n6iTpJOsk6KTaZ2bmJmnoVn9Py2/SMO6ODkxL01DSTVFR0lHLVE7U9POwDpTW1vT@n9BUWZeCVgKApV0oEZoWtf@N9Qx0jHWMQEA): ``` for(;scanf("%d",&a+i)>0;i++); ``` Shout out to @mousetail for helping me out!
79,947
I'm trying to read 4 ints in C in a golfing challenge and I'm bothered by the length of the code that I need to solve it: ``` scanf("%d%d%d%d",&w,&x,&y,&z) ``` that's 29 chars, which is huge considering that my total code size is 101 chars. I can rid of the first int since I don't really need it, so I get this code: ``` scanf("%*d%d%d%d",&x,&y,&z) ``` which is 27 chars, but it's still lengthy. So my question is, is there any other way (tricks, functions, K&R stuff) to read ints that I don't know of that could help me reduce this bit of code? --- Some users have reported that my question is similar to [Tips for golfing in C](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c) While this topic contain a lot of useful information to shorten C codes, it isn't relevant to my actual use case since it doesn't provide a better way to read inputs. I don't know if there is actually a better way than scanf to read multiple integers (that's why I'm asking the question in the first place), but if there is, I think my question is relevant and is sufficiently different than global tips and tricks. If there is no better way, my question can still be useful in the near future if someone find a better solution. I'm looking for a full program (so no function trick) and all libraries possible. It needs to be C, not C++. Currently, my whole program looks like this: ``` main(w,x,y,z){scanf("%*d%d%d%d",&x,&y,&z)} ``` Any tricks are welcome, as long as they shorten the code (this is code golf) and work in C rather than C++.
2016/05/15
[ "https://codegolf.stackexchange.com/questions/79947", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/53734/" ]
If you want to e.g. print all the inputs then we have this, being 64 bytes long: ``` main(x,y,z){scanf("%*d%d%d%d",&x,&y,&z);printf("%d%d%d",x,y,z);} ``` We can actually shorten this with a loop, bringing the total down to 47 bytes: ``` main(z){for(;scanf("%d",&z)>0;)printf("%d",z);} ``` So the reading part is only [23 bytes long](https://tio.run/##S9YtSU7@/z83MTNPo0qzOi2/SMO6ODkxL01DSTVFR0lHrUrTzsBas6AoM68ELKakU6VpXfv/v6EOGAIA): ``` for(;scanf("%d",&z)>0;) ``` Note that this only works when you don't want to assign a value to a specific variable and only want to **read** the values. [A method that is 29 bytes long](https://tio.run/##S9YtSU7@n6iTpJOsk6KTaZ2bmJmnoVn9Py2/SMO6ODkxL01DSTVFR0lHLVE7U9POwDpTW1vT@n9BUWZeCVgKApV0oEZoWtf@N9Qx0jHWMQEA): ``` for(;scanf("%d",&a+i)>0;i++); ``` Shout out to @mousetail for helping me out!
[C (gcc)](https://gcc.gnu.org/), ~~44~~ 43 bytes ================================================== ```c main(i,a,b,c,d){for(;i+=scanf("%d",i+&i);); ``` [Try it online!](https://tio.run/##Pc3BCsIwEATQe75iCRiSdku19bb4MenGlAUbJa0n8deNWqnMHN8w3IzMpUxekhX0OCBjcI94zZakPs3sU7R6FzRKbcSRo9JWanW0jj74j37RaDyaAQ2jCY5U1apblrRE@BrYqhG2O4J8Xu45wZ6e5QAd9HB8cbz4cS7N1Hdv "C (gcc) – Try It Online") This frees up an extra integer `i=0`, while [mousetail's solution](https://codegolf.stackexchange.com/a/252554/76323) make `i=5`(can't find a compiler that allow reusing `e` as index without adding extra 1) Need `-m32` maybe because on x64 values are passed via registers [C (tcc)](http://savannah.nongnu.org/projects/tinycc), 44 bytes =============================================================== ```c a,b,c,d,i;main(){for(;i+=scanf("%d",i+&a);); ``` [Try it online!](https://tio.run/##Tc1NCgIxDEDhfU8RCpZmJjL@7YKHyaQWsrBKravBs1dwRORtP3i6baq9C82klMj4KlYiLvlWI9t4fqiUHP0mebIxCDJynwb38atNuPzQmqcgFGYKSiEhu2Fy92qlZfg38H0iQ720Zy2w41ffwwGOcHoD "C (tcc) – Try It Online")
79,947
I'm trying to read 4 ints in C in a golfing challenge and I'm bothered by the length of the code that I need to solve it: ``` scanf("%d%d%d%d",&w,&x,&y,&z) ``` that's 29 chars, which is huge considering that my total code size is 101 chars. I can rid of the first int since I don't really need it, so I get this code: ``` scanf("%*d%d%d%d",&x,&y,&z) ``` which is 27 chars, but it's still lengthy. So my question is, is there any other way (tricks, functions, K&R stuff) to read ints that I don't know of that could help me reduce this bit of code? --- Some users have reported that my question is similar to [Tips for golfing in C](https://codegolf.stackexchange.com/questions/2203/tips-for-golfing-in-c) While this topic contain a lot of useful information to shorten C codes, it isn't relevant to my actual use case since it doesn't provide a better way to read inputs. I don't know if there is actually a better way than scanf to read multiple integers (that's why I'm asking the question in the first place), but if there is, I think my question is relevant and is sufficiently different than global tips and tricks. If there is no better way, my question can still be useful in the near future if someone find a better solution. I'm looking for a full program (so no function trick) and all libraries possible. It needs to be C, not C++. Currently, my whole program looks like this: ``` main(w,x,y,z){scanf("%*d%d%d%d",&x,&y,&z)} ``` Any tricks are welcome, as long as they shorten the code (this is code golf) and work in C rather than C++.
2016/05/15
[ "https://codegolf.stackexchange.com/questions/79947", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/53734/" ]
Thanks to @DialFrost for drawing my attention to this question. I believe for reading 4 numbers your solution is optimal. However, I found a solution that saves bytes when reading 5 or more numbers at a time. It will also consume the entire input (i.e. it can't be used in a loop). Depending on the context it might help you with only 4 variables too If you define your variables in a sequence like this: ```c a,b,c,d,e;main(){ ``` In this case, the variables will be layed out in successive memory addresses, we can abuse that. ```c for(;~scanf("%d",&a+e);e++); ``` Full program: ```c // new a,b,c,d,e;main(){for(;~scanf("%d",&a+e);e++);} // original a,b,c,d;main(e){scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);} ``` This 29 byte segment will paste all the input in successive variables starting in `a`. We re-use `e`, (the last variable) as the index variable. This saves declaring one variable. Size comparison --------------- | Number of inputs | Original | New | Original (full program) | new (full program) | | --- | --- | --- | --- | --- | | 1 | 14 | 28 | 24 | 38 | | 2 | 19 | 28 | 31 | 40 | | 3 | 24 | 28 | 38 | 42 | | 4 | 29 | 28 | 45 | 44 | | 5 | 34 | 28 | 52 | 46 | | 6 | 39 | 28 | 59 | 48 | Note that the new method gains a 1 byte disadvantage in full programs because you can't use function arguments, however, this doesn't matter if you can use another variable as the argument to `main`. Note there is also a slot in the initialization portion of the for loop. If you can put another expression there this method can save 1 byte even with only 4 arguments. [Try it online!](https://tio.run/##S9YtSU7@n6iTpJOsk6KTap2bmJmnoVn9Py2/SMPawKY4OTEvTUNJNUVJRy1RO1XTOlVbW9P6f0FRZl4JWBwGlXTgZmha1/43VDBSMFYwUTAFAA "C (tcc) – Try It Online") @JDT ponted out you can save 1 byte at the cost of having 1 added to `e` at the end: ``` for(;0<scanf("%d",&a+e++);); ```
[C (gcc)](https://gcc.gnu.org/), ~~44~~ 43 bytes ================================================== ```c main(i,a,b,c,d){for(;i+=scanf("%d",i+&i);); ``` [Try it online!](https://tio.run/##Pc3BCsIwEATQe75iCRiSdku19bb4MenGlAUbJa0n8deNWqnMHN8w3IzMpUxekhX0OCBjcI94zZakPs3sU7R6FzRKbcSRo9JWanW0jj74j37RaDyaAQ2jCY5U1apblrRE@BrYqhG2O4J8Xu45wZ6e5QAd9HB8cbz4cS7N1Hdv "C (gcc) – Try It Online") This frees up an extra integer `i=0`, while [mousetail's solution](https://codegolf.stackexchange.com/a/252554/76323) make `i=5`(can't find a compiler that allow reusing `e` as index without adding extra 1) Need `-m32` maybe because on x64 values are passed via registers [C (tcc)](http://savannah.nongnu.org/projects/tinycc), 44 bytes =============================================================== ```c a,b,c,d,i;main(){for(;i+=scanf("%d",i+&a);); ``` [Try it online!](https://tio.run/##Tc1NCgIxDEDhfU8RCpZmJjL@7YKHyaQWsrBKravBs1dwRORtP3i6baq9C82klMj4KlYiLvlWI9t4fqiUHP0mebIxCDJynwb38atNuPzQmqcgFGYKSiEhu2Fy92qlZfg38H0iQ720Zy2w41ffwwGOcHoD "C (tcc) – Try It Online")
715,485
> > Evaluate $\lim\_{x \to 0+} \frac{x-\sin x}{(x \sin x)^{3/2}}$ > > > This is an exercise after introducing L'Hopital's rule. I directly apply L'Hopital's rule three times and it becomes more and more complex. So I try to substitute $t=\sqrt x$ but there's a square root remained in the denominator $t^3 (sin(t^2))^{3/2}$,apply L'Hopital's rule three times or more I still can't solve it. So I think maybe I have to write $t=\sqrt{x \sin x}$ ,but I can't find a way to convert $x- \sin x$ to a function about $t$ . Thanks in advance.
2014/03/17
[ "https://math.stackexchange.com/questions/715485", "https://math.stackexchange.com", "https://math.stackexchange.com/users/94283/" ]
$$\begin{align\*} \lim\_{x\to0^+}\frac{x-\sin x}{(x\sin x)^{3/2}}&=\lim\_{x\to0^+}\left(\frac{x}{\sin x}\right)^{3/2}\frac{x-\sin x}{x^3}\\ &=\lim\_{x\to0^+}\frac{x-\sin x}{x^3} \end{align\*}$$ And apply L'Hopital's rule three times.
By Taylor series we have $$\sin x\sim\_0 x-\frac{x^3}{6}$$ hence $$\lim\_{x \to 0+} \frac{x-\sin x}{(x \sin x)^{3/2}}=\lim\_{x \to 0+}\frac{x^3/6}{(x^2)^{3/2}}=\frac16$$
3,702,859
I am new to javascript/jquery . I have a small question. I have some thing like the following in the java script file. ``` <button id="button1" onclick=click() /> <button id="button2" onclick=click() /> <button id="button3" onclick=click() /> ``` so the click function looks like the follwoing ``` click(id){ /do some thing } ``` so my question is when ever the button is clicked how can we pass the button id to the function. ``` <button id="button1" onclick=click("how to pass the button id value to this function") /> ``` how can we pass the button id like "button1" to the click function when ever the button is clicked.. I would really appreciate if some one can answer to my question.. Thanks, Swati
2010/09/13
[ "https://Stackoverflow.com/questions/3702859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436175/" ]
I advise the use of unobtrusive script as always, but if you *have* to have it inline use `this`, for example: ``` <button id="button1" onclick="click(this.id)" /> ``` The unobtrusive way would look like this: ``` $("button").click(function() { click(this.id); }); ```
You don't need to. ``` function handleClick(){ //use $(this).attr("id"); //or $(this) to refer to the object being clicked } $(document).ready(function(){ $('#myButton').click(handleClick); }); ```