date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/20
475
1,528
<issue_start>username_0: I'm new to VBA and really trying to get working on a project for work, I apologize for my lack of knowledge but really trying to nail this for the boss. What I'm trying to accomplish is as follows: I have a list of numbers that start from H2 and go to H200, each ranging from 1~150. I am trying to write a macro that inserts rows under each number with the same count as the number. (ex. If the number is 42, create 42 rows under it. Then say the number under it is 13, then there would be 13 rows... and so on). *Current Code:* ``` Sub InsertRow() i = 2 count = Cells(i, H).Value Range("B2").EntireRow.Insert Range("B2").EntireRow.Resize(count).Insert shift:=xlDown End Sub ```<issue_comment>username_1: If you are inserting rows, you need to start at the bottom and work up. ``` Sub InsertRow() dim i as long with worksheets("sheet1") for i=.cells(.rows.count, "H").end(xlup).row-1 to 2 step -1 .cells(i, "H").offset(1, 0).resize(.cells(i, "H").value2, 1).entirerow.insert next i end with end sub ``` Upvotes: 2 <issue_comment>username_2: You are halfway there. You can use a for loop to go through all the cells. However, since you will insert rows and therefore expand the number of cells in the loop, I suggest to start from the bottom and go up: ``` For i = cells(Rows.count,"H").end(xlup).row to 2 step - 1 count = Cells(i, 8).Value Range("B" & i + 1).EntireRow.Resize(count).Insert shift:=xlDown Next i ``` Upvotes: 3
2018/03/20
950
3,474
<issue_start>username_0: I'm not exactly sure what to call this so I might have missed some things in my search for an answer for this but basically I have data that comes in from an external api and it gets inserted into an `innerHTML` tag now in the data that is being returned is some html which then gets processed thanks to `innerHTML` but I have certain keywords in the returned html like this `[username]` and I want to replace that with data I have stored. So in my **.ts** file I might have.. ``` username: 'name'; ``` then in my html I have ``` ``` and in my response from `data.html` the html is like so ``` Hey [userName] lorem ipsum... ============================= ``` so I want to replace the `[userName]` that comes in dynamically from the external api with the username that is stored in `username` I tried to put `{{username}}` in the html that is coming in.. but that didnt work and I also tried `${username}` but that also didnt work.. Im wondering if there is another way? **EDIT** Ive tried to use str.replace(); in the onChanges life cycle event but that isn't working either my code is .. ``` const html = document.querySelector('.inner-html'); html.innerHTML.replace('[userName]', this.username); ``` Now something like this must be possible, any help would be appreciated Thanks<issue_comment>username_1: It looks like you have control of the dynamic data. If that is so, It would make more sense if you could transform the html on the server to include the `username`. However if you don't have control, you could easily use replace the `[username]` with what you have. E.G: `str.replace('[username]', this.username);` Upvotes: 0 <issue_comment>username_2: Angular provides the Pipe precisely for this purpose: > > Pipe > > > An Angular pipe is a function that transforms input values to output > values for display in a view. > > > They provide *reusable* and *scalable* ways of accomplishing your goal. Please check this out as I think it is what you are after: [Live Solution](https://stackblitz.com/edit/angular-nedchs?file=app%2Fparse-inner-html.pipe.ts) Basically, you pipe the output of the `[innerHTML]` through a transform: ``` ``` `parseInnerHtml` is the custom pipe and it takes a hash of replacement keys and corresponding values to replace with: ``` import { Input, Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'parseInnerHtml'}) export class ParseInnerHtml implements PipeTransform { transform(text: string, replacements: Object): string { let search = Object.keys(replacements); for(let i = 0; i < search.length; i++){ text = text.replace('['+ search[i] +']', replacements[search[i]]); } return text; } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: ``` -- in hello.component.ts @Component({ selector: 'hello', template: ``, }) export class HelloComponent { @Input() username: string; private _html: string; @HostBinding('innerHTML') @Input() set html(html: string) { this._html = html.replace('[userName]', this.username); } get html() { return this._html; } } -- in app.component.html -- in app.component.ts @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { username = 'App user'; html = 'Hello [userName]! ================= '; } ``` [Live example](https://stackblitz.com/edit/angular-hchpcn) Upvotes: 0
2018/03/20
681
2,370
<issue_start>username_0: So basically I have these json values in my config.json file, but how can I read them from a .txt file, for example: ``` {"prefix": $} ``` This would set a variable configPrefix to $. Any help?<issue_comment>username_1: It looks like you have control of the dynamic data. If that is so, It would make more sense if you could transform the html on the server to include the `username`. However if you don't have control, you could easily use replace the `[username]` with what you have. E.G: `str.replace('[username]', this.username);` Upvotes: 0 <issue_comment>username_2: Angular provides the Pipe precisely for this purpose: > > Pipe > > > An Angular pipe is a function that transforms input values to output > values for display in a view. > > > They provide *reusable* and *scalable* ways of accomplishing your goal. Please check this out as I think it is what you are after: [Live Solution](https://stackblitz.com/edit/angular-nedchs?file=app%2Fparse-inner-html.pipe.ts) Basically, you pipe the output of the `[innerHTML]` through a transform: ``` ``` `parseInnerHtml` is the custom pipe and it takes a hash of replacement keys and corresponding values to replace with: ``` import { Input, Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'parseInnerHtml'}) export class ParseInnerHtml implements PipeTransform { transform(text: string, replacements: Object): string { let search = Object.keys(replacements); for(let i = 0; i < search.length; i++){ text = text.replace('['+ search[i] +']', replacements[search[i]]); } return text; } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: ``` -- in hello.component.ts @Component({ selector: 'hello', template: ``, }) export class HelloComponent { @Input() username: string; private _html: string; @HostBinding('innerHTML') @Input() set html(html: string) { this._html = html.replace('[userName]', this.username); } get html() { return this._html; } } -- in app.component.html -- in app.component.ts @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { username = 'App user'; html = 'Hello [userName]! ================= '; } ``` [Live example](https://stackblitz.com/edit/angular-hchpcn) Upvotes: 0
2018/03/20
745
2,624
<issue_start>username_0: I'm trying to dynamically create a query and filter from a table not known at compile time (specifically, I want to filter on `id` if I'm querying the `requests` table, `operation_ParentId` otherwise). The following fails because `id` is not a column in the `exceptions` table: ``` let dataset = exceptions; dataset | where (itemType == "request" and id == "test") or (itemType != "request" and operation_ParentId == "test") ``` Thanks in advance!<issue_comment>username_1: It looks like you have control of the dynamic data. If that is so, It would make more sense if you could transform the html on the server to include the `username`. However if you don't have control, you could easily use replace the `[username]` with what you have. E.G: `str.replace('[username]', this.username);` Upvotes: 0 <issue_comment>username_2: Angular provides the Pipe precisely for this purpose: > > Pipe > > > An Angular pipe is a function that transforms input values to output > values for display in a view. > > > They provide *reusable* and *scalable* ways of accomplishing your goal. Please check this out as I think it is what you are after: [Live Solution](https://stackblitz.com/edit/angular-nedchs?file=app%2Fparse-inner-html.pipe.ts) Basically, you pipe the output of the `[innerHTML]` through a transform: ``` ``` `parseInnerHtml` is the custom pipe and it takes a hash of replacement keys and corresponding values to replace with: ``` import { Input, Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'parseInnerHtml'}) export class ParseInnerHtml implements PipeTransform { transform(text: string, replacements: Object): string { let search = Object.keys(replacements); for(let i = 0; i < search.length; i++){ text = text.replace('['+ search[i] +']', replacements[search[i]]); } return text; } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: ``` -- in hello.component.ts @Component({ selector: 'hello', template: ``, }) export class HelloComponent { @Input() username: string; private _html: string; @HostBinding('innerHTML') @Input() set html(html: string) { this._html = html.replace('[userName]', this.username); } get html() { return this._html; } } -- in app.component.html -- in app.component.ts @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { username = 'App user'; html = 'Hello [userName]! ================= '; } ``` [Live example](https://stackblitz.com/edit/angular-hchpcn) Upvotes: 0
2018/03/20
863
3,036
<issue_start>username_0: I'm currently interested in F# as it is different to everything I have used before. I need to access the first element of each list contained within a large list. If I assume that the main list contains 'x' amount of lists that themselves contain 5 elements, what would be the easiest way to access each of the first elements. let listOfLists = [ [1;2;3;4;5]; [6;7;8;9;10]; [11;12;13;14;15] ] My desired output would be a new list containing [1;6;11] Currently I have ``` let rec firstElements list = match list with | list[head::tail] -> match head with | [head::tail] -> 1st @ head then firstElements tail ``` To then expand on that, how would I then get all of the second elements? Would it be best to create new lists without the first elements (by removing them using a similar function) and then reusing this same function?<issue_comment>username_1: It looks like you have control of the dynamic data. If that is so, It would make more sense if you could transform the html on the server to include the `username`. However if you don't have control, you could easily use replace the `[username]` with what you have. E.G: `str.replace('[username]', this.username);` Upvotes: 0 <issue_comment>username_2: Angular provides the Pipe precisely for this purpose: > > Pipe > > > An Angular pipe is a function that transforms input values to output > values for display in a view. > > > They provide *reusable* and *scalable* ways of accomplishing your goal. Please check this out as I think it is what you are after: [Live Solution](https://stackblitz.com/edit/angular-nedchs?file=app%2Fparse-inner-html.pipe.ts) Basically, you pipe the output of the `[innerHTML]` through a transform: ``` ``` `parseInnerHtml` is the custom pipe and it takes a hash of replacement keys and corresponding values to replace with: ``` import { Input, Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'parseInnerHtml'}) export class ParseInnerHtml implements PipeTransform { transform(text: string, replacements: Object): string { let search = Object.keys(replacements); for(let i = 0; i < search.length; i++){ text = text.replace('['+ search[i] +']', replacements[search[i]]); } return text; } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: ``` -- in hello.component.ts @Component({ selector: 'hello', template: ``, }) export class HelloComponent { @Input() username: string; private _html: string; @HostBinding('innerHTML') @Input() set html(html: string) { this._html = html.replace('[userName]', this.username); } get html() { return this._html; } } -- in app.component.html -- in app.component.ts @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { username = 'App user'; html = 'Hello [userName]! ================= '; } ``` [Live example](https://stackblitz.com/edit/angular-hchpcn) Upvotes: 0
2018/03/20
731
2,507
<issue_start>username_0: How would you take a list of strings, eg. ``` ["jeff", "bezos", "21"] ``` and map that to a struct ``` %{:fistname => "jeff", :lastname => "bezos", :age => "21"} ``` Is it possible to use the Enum functions or would you use the map functions. I need this struct in the specified format so that I can then send it to a database<issue_comment>username_1: It looks like you have control of the dynamic data. If that is so, It would make more sense if you could transform the html on the server to include the `username`. However if you don't have control, you could easily use replace the `[username]` with what you have. E.G: `str.replace('[username]', this.username);` Upvotes: 0 <issue_comment>username_2: Angular provides the Pipe precisely for this purpose: > > Pipe > > > An Angular pipe is a function that transforms input values to output > values for display in a view. > > > They provide *reusable* and *scalable* ways of accomplishing your goal. Please check this out as I think it is what you are after: [Live Solution](https://stackblitz.com/edit/angular-nedchs?file=app%2Fparse-inner-html.pipe.ts) Basically, you pipe the output of the `[innerHTML]` through a transform: ``` ``` `parseInnerHtml` is the custom pipe and it takes a hash of replacement keys and corresponding values to replace with: ``` import { Input, Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'parseInnerHtml'}) export class ParseInnerHtml implements PipeTransform { transform(text: string, replacements: Object): string { let search = Object.keys(replacements); for(let i = 0; i < search.length; i++){ text = text.replace('['+ search[i] +']', replacements[search[i]]); } return text; } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: ``` -- in hello.component.ts @Component({ selector: 'hello', template: ``, }) export class HelloComponent { @Input() username: string; private _html: string; @HostBinding('innerHTML') @Input() set html(html: string) { this._html = html.replace('[userName]', this.username); } get html() { return this._html; } } -- in app.component.html -- in app.component.ts @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { username = 'App user'; html = 'Hello [userName]! ================= '; } ``` [Live example](https://stackblitz.com/edit/angular-hchpcn) Upvotes: 0
2018/03/20
923
2,849
<issue_start>username_0: I'm making a form where i have to insert in my dB several values from a checkbox btn group into different columns. I also have to insert two different values depending if the btn is checked or not. I made it work in the following way, but is there another way for this became more simple? It´s a lot of issets :). Thanks for your time. Best regards! NM --- ``` php if(isset($_POST["submit"])){ // Create connection include ('connection.php'); if(isset($_POST['fixvalue']) && ($_POST['fixvalue'] == 0)) { $fixvalue= "fixvalue"; } else { $fixvalue= 0; }; if(isset($_POST['frtvalue']) && ($_POST['frtvalue'] == 0)) { $valueone= "valueone"; } else { $valueone= 0; }; if(isset($_POST['secvalue']) && ($_POST['secvalue'] == 0)) { $valuetwo= "valuetwo"; } else { $valuetwo= 0; }; if(isset($_POST['thevalue']) && ($_POST['thevalue'] == 0)) { $valuethree= "valuethree"; } else { $valuethree= 0; }; if(isset($_POST['fovalue']) && ($_POST['fovalue'] == 0)) { $valuefour= "valuefour"; } else { $valuefour= 0; }; if(isset($_POST['fitvalue']) && ($_POST['fitvalue'] == 0)) { $valuefive= "valuefive"; } else { $valuefive= 0; }; $sql = "INSERT INTO values(fixvalue,valueone,valuetwo, valuethree,valuefour,valuefive) VALUES('".$fixvalue."','".$valueone."','".$valuetwo."', '".$valuethree."','".$valuefour."','".$valuefive."')"; if ($con-query($sql) === TRUE) { echo'Sucess'; echo "alert('New record OK');"; } else { echo "alert('Error: " . $sql . "<br>" $con->error."');"; } $con->close(); } ?> ```<issue_comment>username_1: ``` $checks = array( 'fixvalue', 'frtvalue', 'secvalue', 'thevalue', 'fovalue', 'fitvalue' ); $data = array(); foreach( $checks as $value){ $data[$value] = isset($_POST[$value]) && $_POST[$value] != '' ? $_POST[$value] : 0; } ``` Than use `$data['frtvalue']` etc in a prepared sql statement Upvotes: 0 <issue_comment>username_2: Here's what I would do: ``` Checkbox Checkbox 1 Checkbox 2 Checkbox 3 Checkbox 4 Checkbox 5 php $fields = [ 'fixvalue' = 0, 'valueone' => 0, 'valuetwo' => 0, 'valuethree' => 0, 'valuefour' => 0, 'valuefive' => 0 ]; if($_POST['submit']){ foreach($_POST as $key => $value) { if($key !== 'submit') { $fields[$key] = $key; } } extract($fields); $sql = $db->prepare("INSERT INTO table_name (fixvalue, valueone, valuetwo, valuethree, valuefour, valuefive) VALUES(:fixvalue, :valueone, :valuetwo, :valuethree, :valuefour, :valuefive)"); foreach ($fields as $key => $value) { $sql->bindValue(':'.$key, $$value); } $sql->execute(); } ?> ``` Upvotes: 2 [selected_answer]
2018/03/20
412
1,299
<issue_start>username_0: I am trying to develop a subquery to get the average attendance from two tables along with full details<issue_comment>username_1: ``` $checks = array( 'fixvalue', 'frtvalue', 'secvalue', 'thevalue', 'fovalue', 'fitvalue' ); $data = array(); foreach( $checks as $value){ $data[$value] = isset($_POST[$value]) && $_POST[$value] != '' ? $_POST[$value] : 0; } ``` Than use `$data['frtvalue']` etc in a prepared sql statement Upvotes: 0 <issue_comment>username_2: Here's what I would do: ``` Checkbox Checkbox 1 Checkbox 2 Checkbox 3 Checkbox 4 Checkbox 5 php $fields = [ 'fixvalue' = 0, 'valueone' => 0, 'valuetwo' => 0, 'valuethree' => 0, 'valuefour' => 0, 'valuefive' => 0 ]; if($_POST['submit']){ foreach($_POST as $key => $value) { if($key !== 'submit') { $fields[$key] = $key; } } extract($fields); $sql = $db->prepare("INSERT INTO table_name (fixvalue, valueone, valuetwo, valuethree, valuefour, valuefive) VALUES(:fixvalue, :valueone, :valuetwo, :valuethree, :valuefour, :valuefive)"); foreach ($fields as $key => $value) { $sql->bindValue(':'.$key, $$value); } $sql->execute(); } ?> ``` Upvotes: 2 [selected_answer]
2018/03/20
1,572
4,113
<issue_start>username_0: I have a solution containing 4 projects. * One .NET Framework project *(Ananas)* * Two .NET Core project *(Bananas & Cherries)* * One Xamarin project *(Dewberries)* Every time I start Visual Studio 2017 Community (15.6.2) and load the solution, it hangs itself while loading in the first project (Ananas). [![screenshot](https://i.stack.imgur.com/PT2To.png)](https://i.stack.imgur.com/PT2To.png) I can sit and wait for it to load for 30 minutes or more, but the progress bar will just keep animating. I have to totally kill Visual Studio to stop this. If I then delete the solution folder, and unpack it anew from a backup archive that I have stashed away and load it up again, it loads the first time without hanging. But when I close the solution, close Visual Studio, restart and load it again, it starts to hang again.<issue_comment>username_1: If you inspect the Solution (SLN) file, you may find duplicate GUIDs for two or more of the projects. See the example below. ``` Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ananas", "Ananas\Ananas.csproj", "{F16C0F09-8509-4370-B4FF-C6E1C1C27C31}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Bananas", "Bananas\Bananas.csproj", "{9D7771AE-8A04-438E-858A-7DBD42025BF4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cherries", "Cherries\Cherries.csproj", "{91FB0CB7-5DC1-4B86-B33C-F22BE6A11CF2}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dewberries", "Dewberries\Dewberries.csproj", "{424ABA82-B745-4376-8A52-632B9016608E}" EndProject ``` As you can see the first and the last project have the same GUID, and the two projects in the middle have the same GUID as well. What you need to do is generate a valid GUID to differentiate the conflicting projects. Such that, you get something like the following. ``` Project("{2CD1389C-9B3D-41E9-9AC4-FB6402671C81}") = "Ananas", "Ananas\Ananas.csproj", "{F16C0F09-8509-4370-B4FF-C6E1C1C27C31}" EndProject Project("{73ED998E-CD14-48E9-8193-A60F496F9CD7}") = "Bananas", "Bananas\Bananas.csproj", "{9D7771AE-8A04-438E-858A-7DBD42025BF4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cherries", "Cherries\Cherries.csproj", "{91FB0CB7-5DC1-4B86-B33C-F22BE6A11CF2}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dewberries", "Dewberries\Dewberries.csproj", "{424ABA82-B745-4376-8A52-632B9016608E}" EndProject ``` To generate valid GUIDs, I suggest that you use an online tool for this, such as [Online GUID Generator](https://www.guidgenerator.com/). Upvotes: -1 [selected_answer]<issue_comment>username_2: Try opening Visual Studio in Administrator Mode. Upvotes: 0 <issue_comment>username_3: There are lots of different guids in the Visual Studio solution files. As per my comment to @samirg's answer: The first Guid `Project("{ }")` is the .net project type, the second Guid `".csproj", "{ }"` is the unique project identifier. You should not change the first, but you can set the second to a unique ID. Visual studio generates both, the first from the project type you select when creating a new project, the second uniquely identifies that project. It appears you have a mix of both new and old project guids as seen here in the .net Project System repo README.md <https://github.com/dotnet/project-system/blob/master/docs/opening-with-new-project-system.md> The project type guid (at this point now that there are 2 for each language) tells Visual Studio to treat the project like an old or new project type. `FAE04EC0-301F-11D3-BF4B-00C04F79EFBC` is the **old** C# project guid. `9A19103F-16F7-4668-BE54-9A1E7A4F7556` is the **new** C# project guid. Since you have a mix of both I would change all of the old guids to the new ones for consistency in the behavior of the solution. The new VS2017 project system has a [bunch of benefits](https://github.com/dotnet/project-system/blob/master/docs/feature-comparison.md). Upvotes: 0 <issue_comment>username_4: I had the same problem and removing of the hidden .vs folder in solution directory fixed the problem. Upvotes: 2
2018/03/20
477
1,631
<issue_start>username_0: I'm sure there is a perfectly logical explanation to why this isn't working the way I want it to but I am new to JavaScript so would love some help. Is there any reason you would know as to why it prints out yes even when I want it to print out no. Thanks in advance ``` var username = prompt("What is your VC?"); if (username = "wow") { greeting = document.write("yes"); } else { document.write("no"); } ```<issue_comment>username_1: Yes. One `=` is assignment. Two `==` tests equality. And three `===` tests [strict equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators). ```js var username = prompt("What is your VC?"); if (username === "wow") { document.write("yes"); } else { document.write("no"); } ``` Upvotes: 0 <issue_comment>username_2: The `=` operator is used for assignment, for checking the value you can use `===`. So, change the if as follows: ``` if (username === "wow") ``` Working code is given below: ```js var username = prompt("What is your VC?"); if (username === "wow") { greeting = document.write("yes"); } else { document.write("no"); } ``` Upvotes: 2 <issue_comment>username_3: When you say: ``` a = b ``` You're saying "set a to the value in b." If you out that in an if statement's expression, it assigns b to a and thrn checks if a's new value is "truthy." If you want to ask "is a equal to b," you have to say: ``` a == b ``` I know that there is a difference between == and ===, but I am not a JavaScript master, so I cannot tell you what the difference is! Upvotes: 0
2018/03/20
1,009
3,753
<issue_start>username_0: I am creating an API using ASP.NET Core, and below is my controller code. I have given the controller and Startup code below, along with fiddler request/response log. I am getting a 404 Not Found error. Please advise what am I missing? ``` [Route("api/[controller]")] public class UserController : Controller { [HttpPost] public string RegisterUser(User newUser) { // Code to register user in system return succecss/failure message } } ``` I tried suggested attribute routing from <https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing> but still no luck. I am not sure what I am missing. Please note that with the Web API template , there is no default routing in Startup.cs: ``` public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } ``` The following is my fiddler request: ``` URL: http://localhost:8011/api/User/RegisterUser Verb= post User-Agent: Fiddler Host: localhost:8011 Content-Type: application/json Content-Length: 77 Request body {"FirstName": "TEST FirstName", "LastName": "Test Last Name", "EmailId":"<EMAIL>","Password":"1"} Output in response header: HTTP/1.1 404 Not Found ```<issue_comment>username_1: `[Route("api/[controller]")]` on the controller, together with a `[HttpPost]` on the action means that the action will be available at `/api/[controller]`. So in your case `/api/User`. Unless you include `[action]` in the route template, the method name of the action will not be included in the route. So, try a POST to `/api/User`, or change the route attribute on the controller to `[Route("api/[controller]/[action]")]`. --- Note that the reason the API project template does not include default routes in the `Startup` is because with APIs you are expected to configure them explicitly. That way, the routes are part of your application design. With [RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer) APIs, you are usually designing APIs in a way that they represent “resources”. And then you are using HTTP verbs to indicate what you are actually doing. The included `ValuesController` is actually a good example for that: ``` // GET api/values [HttpGet] Get() // => Get all values // GET api/values/5 [HttpGet("{id}")] Get(int id) // => Get a single value // POST api/values [HttpPost] Post([FromBody] string value) // => Add a new value // PUT api/values/5 [HttpPut("{id}")] Put(int id, [FromBody] string value) // => Set/replace a value // DELETE api/values/5 [HttpDelete("{id}")] Delete(int id) // => Delete a value ``` By not having any routing there by default, you don’t accidentally end up with method names within the route (since method names are usually imperative word combinations, making it more [RPC](https://en.wikipedia.org/wiki/Remote_procedure_call) instead of REST). Instead, you will have to deliberately expose your methods as actual routes with verbs. In your exapmle, your `UserController` would probably be for a “User” resource. So registering a user would probably be a POST request to `/api/User`. Upvotes: 4 [selected_answer]<issue_comment>username_2: You have not fully defined your route. `[Route("api/[controller]")]` creates the `/api/User` portion of the url, but you have not specified the rest of the route on your action. So your request should change from to `http://localhost:8011/api/User/RegisterUser` to `http://localhost:8011/api/User` Upvotes: 0
2018/03/20
377
1,268
<issue_start>username_0: I'm trying to invoke the iris endpointfrom the [SageMaker example notebooks](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-python-sdk/tensorflow_iris_dnn_classifier_using_estimators/tensorflow_iris_dnn_classifier_using_estimators.ipynb) using the aws cli. I've tried using the following command: ``` !aws sagemaker-runtime invoke-endpoint \ --endpoint-name sagemaker-tensorflow-py2-cpu-2018-03-19-21-27-52-956 \ --body "[6.4, 3.2, 4.5, 1.5]" \ --content-type "application/json" \ output.json ``` I get the following response: ``` { "InvokedProductionVariant": "AllTraffic", "ContentType": "*/*" } ``` What am I doing wrong?<issue_comment>username_1: If you've gotten that response, your request is successful. The output should be in the output file you specified - output.json :) Upvotes: 4 [selected_answer]<issue_comment>username_2: Just FYI, I was running the command for a flask endpoint and wanted to add that when mentioning --body as json I had to add the quotes as: ``` --body "{ \"host\": \"some.example.com\", \"userId\": [ \"some-string\" ] }" ``` I am now looking for a way to specify a json file instead of this body which would be easier for a CI/CD pipeline, per say ! Upvotes: 1
2018/03/20
411
1,212
<issue_start>username_0: I have a table with dates in this format "12/14/2017" and I want to create another column that separates month from this date string and states it like "January" not "01". I think I need a mix of CASE function with some kind of DATE function. Table: ``` Column A 12/14/2017 12/11/2017 2/16/2018 1/2/2017 ``` Output I need which I will Column B: ``` Column A Column B (Output) 12/14/2017 December 12/11/2017 December 2/16/2018 February 1/2/2017 January ```<issue_comment>username_1: ``` SELECT columnA, CASE EXTRACT(MONTH FROM TO_DATE(columnA,'mm/dd/yyyy')) WHEN 1 THEN 'January' WHEN 2 THEN 'February' WHEN 3 THEN 'March' WHEN 4 THEN 'April' WHEN 5 THEN 'May' WHEN 6 THEN 'June' WHEN 7 THEN 'July' WHEN 8 THEN 'August' WHEN 9 THEN 'September' WHEN 10 THEN 'October' WHEN 11 THEN 'November' WHEN 12 THEN 'December' END AS columnB FROM yourTable ``` Upvotes: 0 <issue_comment>username_2: You can convert the value to a date and then to a month string: ``` DATE_FORMAT(TO_DATE(columnA, 'MM/DD/YYYY', 'MMMM') ``` Upvotes: 2 [selected_answer]
2018/03/20
307
1,150
<issue_start>username_0: The problem is that I have a file input field that takes only one file at a time, I need it to be like this. If I try to upload one file, everything is fine. But if I need to upload more files it seems like the "change" handler method is not being called unless I reload the page, which is not what anyone would want. The HTML looks like this: ``` archivo {{ newActivity.fileName }} ``` The function in the component is: ``` selectFile(file: File): void { console.log('Hello'); if(file == undefined) return; this.newActivity.fileName = file.name; this.newActivity.file = file; } ``` On the first file upload the "Hello" shows, no problem. But the method doesn't seem to be called more than once. How can this be solved?<issue_comment>username_1: Set the value of the input to null in the onclick event... ``` ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: it happens only when you try to upload the same file/image. When **(change)** sees the same event, it doesn't trigger the given method. To fix it add `(click)="$event.taget.value=null"` in your **input** tag Upvotes: -1
2018/03/20
669
2,384
<issue_start>username_0: I need to know when a UIKit notification has been closed. The UIkit notification plugin (<https://getuikit.com/docs/notification>) mentions that it has a close event. Is it possible to use this for instances triggered programatically? e.g. ``` UIkit.notification({ message: 'my-message!', status: 'primary', timeout: null }); UIKit.o ``` I've tried putting the nofication on a variable, (as suggested <https://getuikit.com/docs/javascript#programmatic-use>, where it even states `You'll receive the initialized component as return value` - but you don't) ``` let foo = UIkit.notification('message'); // foo is undefined ``` I've tried chaining the on method ``` UIkit.notification.on('close', function() { ... }); // on is undefined ``` but the `.on` method is part of `UIkit.util.on($el, event, fn)` and there is no `$el` when calling notification programatically. The only other way I can think of doing it is putting a mutation observer onto the body and watching to the notification element to change state, but this seems like overkill.<issue_comment>username_1: You could try this instead ``` UIkit.util.on(document, 'close', function() { alert('Notification closed'); }); ``` See this [Pen](https://codepen.io/anon/pen/zjWvLO) Upvotes: 2 <issue_comment>username_2: A bit Hacky, but the following seems to "work" : ```js function notify(){ var params = Array.prototype.slice.call(arguments); new_f = params.shift() foo = UIkit.notification.apply(this, params); return function(foo, new_f, old_f){ foo.close = function(){new_f(); foo.close = old_f; old_f.apply(this, arguments); } return foo }(foo, new_f, foo.close); } notify(function(){alert('ok');}, 'message'); ``` Upvotes: 1 <issue_comment>username_3: You can store a handle to the notification... ```js warning_notification = UIkit.notification({message: 'Warning message...', status: 'warning', timeout: 1000}); ``` ... and check if this is the origin of the close event: ``` UIkit.util.on(document, 'close', function(evt) { if (evt.detail[0] === warning_notification) { alert('Warning notification closed'); } }); ``` Now, you will only see the alert when exactly this notification was closed. [Check out this demo](https://codepen.io/anon/pen/jdaEQN). Upvotes: 3 [selected_answer]
2018/03/20
945
2,914
<issue_start>username_0: ``` def f(c: String) = { val array = ("google.com|yahoo.com|gmail.com|mail.com").split("\\|") for (i <- array) { if (c.contains(i)) { println("comparing " + c + " with " + i) i } } "N/A" } ``` My intention for the above function is that, it will return `N/A` if `c` does not contain any of the elements of the array. And, if it does, it will return the element in the array. So if `c="www.google.com/1234"` , ideally the function would return `google.com` and if `c="bloomberg.com/example"`, the function will return `N/A`. But when I do `println(f("www.google.com/1234"))` I get `N/A`. Can anyone tell me what am I doing wrong.<issue_comment>username_1: Your function always returns `N/A`, because it's the last value in its definition. To leave a value in the end like this means in Scala the same as writing `return "N/A"`. But even without `N/A` in the end, your function wouldn't return what you want, because: 1. the last statement would be `for { ... }` which is of type `Unit` 2. your function is side-effecting, by calling `println`, it's not the same as returning a value Let's write first a function that tries to find a match: ``` def findMatch(c: String): Option[String] = { val array = "google.com|yahoo.com|gmail.com|mail.com".split('|') array.find(c.contains) } ``` Notice that the return type is `Option[String]` which comes from the call to the [`find` method](http://scala-lang.org/api/current/scala/Array.html#find(p:A=%3EBoolean):Option[A]). Now you can use it to print the result if it's there or `N/A` otherwise: ``` def f(c: String): Unit = { println(findMatch(c).getOrElse("N/A")) } ``` Upvotes: 2 <issue_comment>username_2: While username_1s solution looks fine, another one, on your track, is possible too: ``` def f (c: String) : List[String] = { val array = ("google.com|yahoo.com|gmail.com|mail.com").split("\\|") val list = (for (i <- array if (c.contains(i))) yield { println("comparing " + c + " with " + i) i }).toList if (list.isEmpty) List ("N/A") else list } ``` It prints while iterating and either returns a list of matches, or a List with the String "N/A", which should, in practice, in most cases result in a List of exactly one String, not less or more, but depending on the input, more than one match is possible. ``` scala> f ("www.google.com/1234") comparing www.google.com/1234 with google.com res61: List[String] = List(google.com) scala> f ("www.göögle.com/1234") res62: List[String] = List(N/A) scala> f ("www.google.com/1234?param:subject='mail.com'") comparing www.google.com/1234?param:subject='mail.com' with google.com comparing www.google.com/1234?param:subject='mail.com' with mail.com res63: List[String] = List(google.com, mail.com) ``` The main difference to your approach is the use of a yield, to return something from the for-construct. Upvotes: 0
2018/03/20
534
2,146
<issue_start>username_0: I have a main storyboard which consists of a single `UITabBarController`, and each `UITabBarItem` simply takes you to another storyboard. My issue is that not all the tabs should always show. There is anywhere between 2 and 5 tabs, and the combination of tabs can be completely different based on the user. How does one go about conditionally hiding tabs? This seems like it should be pretty straight forward but I have not found a general way of going about this.<issue_comment>username_1: 1.Instantiate view controller form stroryboard. ``` let sb = UIStoryboard(name: "you storyboard name", bundle: nil) let vc = sb.instantiateViewController(withIdentifier: "storyboard id set") ``` 2.Create tabbar controller and add child view controller. ``` let tabBarController = UITabBarController() let nav = UINavigationController(rootViewController: vc) // if you didn't ember in navigation controller tabBarController.addChildViewController(nav) ``` 3.Customize tabbar item. ``` nav.tabBarItem.image = ... // your normal image nav.tabBarItem.selectedImage = ... // your select image nav.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue], for: .normal) nav.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue], for: .selected) ``` Upvotes: 0 <issue_comment>username_2: I ended up doing something like the following: ``` let user = User.sharedInstance if let vcs = self.viewControllers { var newVcs = [UIViewController]() for vc in vcs { if let title = vc.title { switch title { case "Feature1": if user.isFeature1Enabled() { newVcs.append(vc) } case "Feature2": if user.isFeature2Enabled() { newVcs.append(vc) } default: break } } } self.setViewControllers(newVcs, animated: false) ``` I feel like there should be a better way. I was expecting to do something like `something.hide()` but this works. Upvotes: 2 [selected_answer]
2018/03/20
1,037
3,249
<issue_start>username_0: This is my first attempt of reversing a dynamic array: ``` bool reverse() { T *newArray = NULL; // Validate operation. if (!isValid() || isReadOnly()) return false; // Allocate new array newArray = new (std::nothrow)T[m_size]; if (newArray == NULL) return false; // Reverse the array's contents. for (int i = m_size - 1; i >= 0; i--) newArray[i] = m_array[i]; // Delete old array. delete[] m_array; m_array = NULL; // Assign new array m_array = newArray; return true; } ``` As you can imagine, this is very costly for large arrays: * Allocation and dealocation takes time. * A linear algorithm with 'for' takes time, too. I'm aware of std::reverse, but unfortunately it doesn't work on dynamic arrays. Should I use std::vector? Yes. But this is for learning. I'm reading from a data structures game programming book and extending my learning. So I'm interested in reducing this member function of Array to the algorithm itself: ``` // Reverse the array's contents. for (int i = m_size - 1; i >= 0; i--) newArray[i] = m_array[i]; ``` I feel like there's an easy way to go about this that is much less costly. I looked on Google but I'm just finding solutions for static arrays. Extra: I'm trying std::reverse again, but no luck so far. ``` std::reverse(std::begin(m_array), std::end(m_array)); ``` Error on compile: > > error C2672: 'begin': no matching overloaded function found > > > Also, std::end wouldn't know the end of a dynamic array, as no size is specified, so maybe I'm just using the wrong functions to achieve this goal. It'd be nice to use std::reverse somehow.<issue_comment>username_1: ``` std::reverse(m_array+0, m_array+m_size); ``` `std::reverse` takes iterators as parameters, and pointers are one form of iterator. Upvotes: 4 [selected_answer]<issue_comment>username_2: It works fine as you can use pointers with every std function which can use iterators: ``` int size = 10; int *i = new int[size]; iota(i, i + size, 0); copy(i, i + size, ostream_iterator(cout, " ")); reverse(i, i + size); copy(i, i + size, ostream\_iterator(cout, " ")); ``` > > > ``` > 0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 0 > > ``` > > You can check this article [Raw pointers are also Iterators!](http://cppisland.com/?p=134). Upvotes: 1 <issue_comment>username_3: You could manually swap the starting indices with the ending indices to effectively reverse the array. ``` #include #include #include int main() { int\* array = new int[6]{ 1, 2, 3, 4, 5, 6 }; constexpr std::size\_t size = 6; //swap ending and starting iterators for (std::size\_t index = 0, end = size / 2; index != end; ++index) { std::swap(array[index], array[size - index - 1]); } for (std::size\_t index = 0; index != size; ++index) { std::cout << array[index] << ' '; } std::cout << std::endl << std::endl; std::reverse(array, array + size); for (std::size\_t index = 0; index != size; ++index) { std::cout << array[index] << ' '; } delete[] array; return 0; } ``` `std::reverse` Will also work since it accepts a starting and ending iterator to which pointers can act as iterators. Upvotes: 1
2018/03/20
1,533
4,371
<issue_start>username_0: I'm stuck on how to get a name stored in a string including white space characters, and then get the rest of the input stored separately as an int, char, and double. In other words, four separate data types: string, int, char, double. Here is the file contents I need to read and extract data from line by line. I need the name extraction to work for all types of names. Also, the following file contents are in this order, respectively: String: Name Int: Account Number Char: Account Type Double: Usage Amount <NAME> 1001 H 5693.3 <NAME>, Jr. 3333 H 1000.0 Sara Lawrence-Smith 2456 H 3999999.5 Good Time Industries 4678 C 10000000.1 Big Business, Inc. 6757 I 12500849.9 Mom and Pop Shop 5002 C 4000000.7 The O'Leary Company 8022 I 9999999.9 Here is my little bit of code thus far: ``` #include #include #include #include using namespace std; void readBillingRecord(ifstream& fin, string& name, int& accNum, char& type, double& usage); int main() { string billingDataFile = "Water Bill Records.txt"; string billingReportFile = "Water Bill Report.txt"; ifstream fin; ofstream fout; string name; int accNum; char type; double usage; fin.open(billingDataFile); if (fin.fail()) { cout << "\nError opening " << billingDataFile << " file for reading. \nProgram Terminated. \n"; system("pause"); return EXIT\_FAILURE; } readBillingRecord(fin, name, accNum, type, usage); system("pause"); return 0; } void readBillingRecord(ifstream& fin, string& name, int& accNum, char& type, double& usage) { fin >> name >> accNum >> type >> usage; cout << name << accNum << type << usage << endl; } ```<issue_comment>username_1: It is difficult to parse the names with the stream functions. Here is a [regex](https://regex101.com/r/cnzoLT/2) solution: ``` void readBillingRecord(ifstream& fin, string& name, int& accNum, char& type, double& usage) { std::string line; std::regex r{R"(([\D]*) (\d*) (\w) (\d*.?\d*))"}; std::smatch m; while(getline(fin, line)){ std::regex_match(line, m, r); name = m[1]; accNum = std::stoi(m[2]); type = std::string{m[3]}[0]; usage = std::stod(m[4]); std::cout << name << accNum << type << usage << endl; } } ``` With some more error checking: ``` void readBillingRecord(ifstream& fin, string& name, int& accNum, char& type, double& usage) { std::string line; std::regex r{R"(([\D]*) (\d*) (\w) (\d*.?\d*))"}; std::smatch m; while(getline(fin, line)){ static int line_count{-1}; ++line_count; if(!std::regex_match(line, m, r)) { std::cout << "No match for line " << line_count << " with text: " << line << '\n'; continue; } name = m[1]; accNum = std::stoi(m[2]); type = std::string{m[3]}[0]; usage = std::stod(m[4]); std::cout << name << accNum << type << usage << endl; } } ``` For the following input: ``` <NAME> 1001 H 5693.3 <NAME>, Jr. 3333 H 1000.0 Sara Law3rence-Smith 2456 H 3999999.5 Good Time Industries 4678 C 10000000.1 Big Business, Inc. 6757 I 12500849.9 Mom and Pop Shop 5002 C 4000000.7 The O'Leary Company 8022 I 9999999.9 ``` Produces: ``` <NAME> 1001H5693.3 No match for line 1 with text: James Randolph, Jr. 3333H1000 No match for line 3 with text: Sara Law3rence-Smith 2456 H 3999999.5 Good Time Industries 4678C1e+07 Big Business, Inc. 6757I1.25008e+07 Mom and Pop Shop 5002C4e+06 The O'Leary Company 8022I1e+07 ``` Upvotes: 0 <issue_comment>username_2: I hate to be “that guy” but, this really cries out for 1. Regular expressions (although any method of counting back from the end of the string would do) 2. Not using C++ (sorry, I say this as a big fan of the language) However, failing that, and presuming that none of the trailing fields is ever missing (or “empty”), your next best bet for extracting those string values is (sadly): For each line in the file: 1. scan backwards for the separators (spaces), three times, being careful not to go past the start of the line; then use the start of the line and that offset (well, an iterator, hopefully) to construct a new string value 2. extract the remaining three values whatever way you choose To do this efficiently, you possibly want to look at `mmap()` and `string_view`. Upvotes: 1
2018/03/20
347
1,226
<issue_start>username_0: ``` var csv = require('fast-csv'); var fs = require('fs'); const app = express(); exportCSVfile: function(req, res){ var ws = fs.createWriteStream('my.xls'); console.log(req.body.save); session = req.session; if(session.uniqueID){ if(session.uniqueID.access == 2){ csv.write([ ["a1","b1"], ["a2","b2"] ],{headers:true}).pipe(ws); } } } ``` that is my current code, i can get the csv file, but rather than directly write on my disk, i want to make the browser download it. how can i to do that?<issue_comment>username_1: First write out a response header setting proper content type and disposition for download. ``` res.writeHead(200, { 'Content-Type': 'text/csv', 'Content-Disposition': 'attachment; filename=' + csvFileName }); ``` Then simply pipe the stream created by csv() to response. ``` csv.write([...]).pipe(res); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use `attachment()` function to attach your file to response. You can try something like this ``` var stream = fs.createReadStream(filename); res.attachment(filename); stream.pipe(res); ``` Upvotes: 1
2018/03/20
1,252
4,536
<issue_start>username_0: I want to make a new process that runs a Common Lisp program with parameters given from my C# program. In other words, I'm looking for interoperability between those programs. Right now I'm using this code to open `clisp` in `cmd`: ``` Process cmd = new Process(); cmd.StartInfo.FileName = "cmd.exe"; cmd.StartInfo.RedirectStandardInput = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.Start(); cmd.StandardInput.WriteLine("clisp"); cmd.StandardInput.WriteLine("(load " + '"' + "CargarNodos.lisp" + '"' + ")"); cmd.StandardInput.WriteLine("(cargar-cds)"); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); cmd.WaitForExit(); Console.WriteLine(cmd.StandardOutput.ReadToEnd()); ``` I can load my .lisp file, but the program crashes when I call the function "cargar-cds" (if I run directly the lisp function from cmd it works fine). I think the part of the .lisp that crashes is this code: ``` (SETQ NODOS () ) (defun cargar-cds() (SETQ L (OPEN "adyacencias.txt" :IF-DOES-NOT-EXIST NIL)) (WHEN L (LOOP FOR LINEA = (READ-LINE L nil) WHILE LINEA DO (setq lst (loop for i = 0 then (1+ j) as j = (position #\tab LINEA :start i) collect (subseq LINEA i j) while j )) (formato-plano lst) (setq NODOS (append NODOS (list LISTAF)))) ) NODOS) ```<issue_comment>username_1: > > Visual Studio doesn't show me an error, even when the c# code posted is inside a try/catch, the application running only freezes > > > The error is thrown in another process, `clisp`, and so you cannot expect a `try/catch` in the calling environment to catch those errors. The freezing is probably because the underlying Lisp environment, which is defined to be interactive, enters the debugger. You might want to add `-on-error exit` (see <https://clisp.sourceforge.io/impnotes/clisp.html>) to disable this behavior. Also, you could redirect the output/error of the process to the C# process's output stream. This should help you detect errors from the underlying process. > > It runs fine,but the code I posted is missing an apostrophe: (SETQ NODOS '() ). > > > The apostrophe is superfluous here, both `()` and `'()` denote the same value. > > the complete code is quite large, it calls another function, but I think the main problem is in the one posted, maybe because it reads a text file. > > > Your priority should be to be able to replicate the bug using only the clisp interpreter and/or trying to see why it behaves differently in both cases (from C# and directly). Maybe the relative pathname you are using is resolved to a file that is non-existent in different contexts. It is however difficult to test your Lisp code: there seems to be other parts that are not detailed. For example, `LISTAF` is referenced only once, as well as other parts. If you could try to reformat the code to be exactly as the one which works (maybe remove comments) and provide a minimal example that works from within clisp but fails from C#, that could help us determine what is wrong. Upvotes: 2 <issue_comment>username_2: There are a bunch of problems in the code. The first is that it is not formatted correctly. This makes it extra hard to find bugs. ``` (defun cargar-cds() ; L is undefined. ; Why use OPEN instead of WITH-OPEN-FILE ? (SETQ L (OPEN "adyacencias.txt" :IF-DOES-NOT-EXIST NIL)) (WHEN L (LOOP FOR LINEA = (READ-LINE L nil) WHILE LINEA DO ;(PRINT LINEA) ;Separar datos de una fila ; the variable lst is undefined (setq lst (loop for i = 0 then (1+ j) as j = (position #\tab LINEA :start i) collect (subseq LINEA i j) while j)) ;Darle formato (IDCd NombreCd Latitud Longitud (IDVecino1 Distancia1) ... (IDVecinoN DistanciaN)) (formato-plano lst) (setq NODOS (append NODOS (list LISTAF)))) ; here your function is ending ) ; this closes the defun above ; commented out, but makes no sense, you probably wanted to close the stream L ;(CLOSE LINEA)) ; dangling code follows. Why is it there? NODOS) ``` Upvotes: 1 <issue_comment>username_3: The child process initiated by the c# code was longer than expected, due to the size of the data; the father process didn't give him the time needed to finish. The solution was waiting a moment before closing the process `cmd.WaitForExit(1000);` Upvotes: 2 [selected_answer]
2018/03/20
1,425
4,208
<issue_start>username_0: I have the following data (you can reproduce it by copying and pasting): ``` from pyspark.sql import Row l = [Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=None), Row(value=None), Row(value=None), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=True), Row(value=None), Row(value=None), Row(value=None), Row(value=True), Row(value=None), Row(value=True), Row(value=None)] l_df = spark.createDataFrame(l) ``` Let's take a look at the schema of `l_df`: ``` l_df.printSchema() root |-- value: boolean (nullable = true) ``` Now I want to use `cube()` to count the frequency of each distinct value in the `value` column: ``` l_df.cube("value").count().show() ``` But I see two types of `null` values! ``` +-----+-----+ |value|count| +-----+-----+ | true| 67| | null| 100| | null| 33| +-----+-----+ ``` To verify that I don't actually have two types of `null`: ``` l_df.select("value").distinct().collect() ``` And there is indeed only one type of `null`: ``` [Row(value=None), Row(value=True)] ``` Just to double check: ``` l_df.select("value").distinct().count() ``` And it returns `2`. I also noticed that `len(l)` is `100` and the first `null` is equal to this number. Why is this happening? System info: Spark 2.1.0, Python 2.7.8, `[GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2`<issue_comment>username_1: These are not two types of nulls but results of different level aggregations. As explained in [What is the difference between cube, rollup and groupBy operators?](https://stackoverflow.com/q/37975227/8371915) your `cube` application is equivalent to: ``` SELECT NULL AS value, COUNT(*) FROM df UNION ALL SELECT value, COUNT(*) FROM df GROUP BY value ``` The first query generates tuple `(null, 100)` (total number of records) where `NULL` is just a placeholder, and the second query generates tuples `(true, 67)`, `(null, 33)` where `NULL` is one of the levels of `value` column. It is easy to check with `grouping` (or `grouping_id`): ``` from pyspark.sql.functions import grouping, count l_df.cube("value").agg(count("*"), grouping("value")).show() # +-----+--------+---------------+ # |value|count(1)|grouping(value)| # +-----+--------+---------------+ # | true| 67| 0| # | null| 100| 1| # | null| 33| 0| # +-----+--------+---------------+ ``` Upvotes: 1 <issue_comment>username_2: df.groupBy('value').count().show() will do as @pault said. In case of cube, adding a "filter" method works for me ``` df.cube("value").count().filter( col('count') ``` but an extra process gets added. See the screenhot from my work where I used cube(). [![See my example](https://i.stack.imgur.com/g3aX4.png)](https://i.stack.imgur.com/g3aX4.png) Upvotes: 0
2018/03/20
6,719
21,746
<issue_start>username_0: Thank you for taking time to read all this, its a lot! Appreciate all you fellow enthusiasts! How to natural sort? ie. order a set of alpha numeric data to appear as: ``` Season 1, Season 2, Season 10, Season 20 ``` instead of ``` Season 1, Season 10, Season 2, Season 20 ``` I use a very practical example of tv seasons in a very practical format as case. I am looking to accomplish the following: 1. Share my working solution for others 2. Ask your help in figuring how to shorten it (or find better solution) to my solution 3. Can you solve criteria 7 below? I spent about 2 hours researching online and another 3 hours building this solution. Some of the reference material came from: * [SO Post](https://stackoverflow.com/questions/34509/natural-human-alpha-numeric-sort-in-microsoft-sql-2005) * [MSDN](https://www.essentialsql.com/use-sql-server-to-sort-alphanumeric-values/) * [Essential SQL](https://www.essentialsql.com/use-sql-server-to-sort-alphanumeric-values/) * [Code Project](https://www.codeproject.com/Articles/842541/How-Do-I-Use-SQL-Server-to-Sort-Alphanumeric-Value) * [DBA Stack Exchange](https://dba.stackexchange.com/questions/14831/natural-numeric-sort-on-string) Some of the solutions found on SO and other sites only work for 90% of cases. However, most/all do NOT work if you have multiple numeric values in your text, or will cause SQL error if there isn't a number found in the text at all. I have created this [SQLFiddle](http://sqlfiddle.com/#!18/70b23/1/0) link to play around with (includes all below code). Here is the create statement: ``` create table tvseason ( title varchar(100) ); insert into tvseason (title) values ('100 Season 03'), ('100 Season 1'), ('100 Season 10'), ('100 Season 2'), ('100 Season 4'), ('Show Season 1 (2008)'), ('Show Season 2 (2008)'), ('Show Season 10 (2008)'), ('Another Season 01'), ('Another Season 02'), ('Another 1st Anniversary Season 01'), ('Another 2nd Anniversary Season 01'), ('Another 10th Anniversary Season 01'), ('Some Show Another No Season Number'), ('Some Show No Season Number'), ('Show 2 Season 1'), ('Some Show With Season Number 1'), ('Some Show With Season Number 2'), ('Some Show With Season Number 10'); ``` Here is my working solution (only unable to solve criteria #7 below): ``` select title, "index", titleLeft, convert(int, coalesce(nullif(titleRightTrim2, ''), titleRight)) titleRight from (select title, "index", titleLeft, titleRight, titleRightTrim1, case when PATINDEX('%[^0-9]%', titleRightTrim2) = 0 then titleRightTrim2 else left(titleRightTrim2, PATINDEX('%[^0-9]%', titleRightTrim2) - 1) end as titleRightTrim2 from (select title, len(title) - PATINDEX('%[0-9] %', reverse(title)) 'index', left(title, len(title) - PATINDEX('%[0-9] %', reverse(title))) titleLeft, ltrim(right(title, PATINDEX('%[0-9] %', reverse(title)))) titleRight, ltrim(right(title, PATINDEX('%[0-9] %', reverse(title)))) titleRightTrim1, left(ltrim(right(title, PATINDEX('%[0-9] %', reverse(title)))), PATINDEX('% %', ltrim(right(title, PATINDEX('%[0-9] %', reverse(title)))))) titleRightTrim2 from tvseason) x) y order by titleLeft, titleRight ``` Criteria to consider: 1. Text contains no numbers 2. Text contains numbers at beginning and end 3. Text contains numbers at beginning only 4. Text contains numbers at end only 5. Text may contain (YYYY) at end 6. Text may end with single digit OR double digit (ex. 1 or 01) 7. Optional: Any combination of above, plus numbers in middle of text Here is the output: ``` title 100 Season 1 100 Season 2 100 Season 03 100 Season 4 100 Season 10 **Case 7 here** Another 10th Anniversary Season 01 Another 1st Anniversary Season 01 Another 2nd Anniversary Season 01 Another Season 01 Another Season 02 Show (2008) Season 1 Show (2008) Season 2 Show 2 The 75th Anniversary Season 1 Show Season 1 (2008) Show Season 2 (2008) Show Season 10 (2008) Some Show Another No Season Number Some Show No Season Number Some Show With Season Number 1 Some Show With Season Number 2 Some Show With Season Number 10 ```<issue_comment>username_1: Personally, I would try to avoid doing complex string manipuluation in SQL. I would probably dump it out to a text file and process it using a regular expression in something like C# or Python. Then write it back to the DB in a separate column. SQL is notoriously bad at string manipulation. However here's my stab at a SQL approach. The idea is basically to first eliminate any rows which don't have the string `Season [number]` in them. That handles the case where there are no seasons to parse. I chose to include them with nulls, but you could just as easily omit them in your where clause, or give them some default value. I use the `stuff()` function to cut off everything up to the string `Season [number]`, so it's easier to work with. Now we have the string starting with the season number, and potentially ending in some garbage. I use a case statement to see if there is garbage (anything non-numeric) and if there is, i take the leftmost numeric characters and throw away the rest. If there is only numeric to begin with, I just leave it as it is. Finally, cast it as an int, and sort by it. ``` if object_id('tempdb.dbo.#titles') is not null drop table #titles create table #titles (Title varchar(100)) insert into #titles (TItle) select title = '100 Season 1' union all select '100 Season 2' union all select '100 Season 03' union all select '100 Season 4' union all select '100 Season 10' union all select 'Another 10th Anniversary Season 01' union all select 'Another 1st Anniversary Season 01' union all select 'Another 2nd Anniversary Season 01' union all select 'Another Season 01' union all select 'Another Season 02' union all select 'Show (2008) Season 1' union all select 'Show (2008) Season 2' union all select 'Show 2 The 75th Anniversary Season 1' union all select 'Show Season 1 (2008)' union all select 'Show Season 2 (2008)' union all select 'Show Season 10 (2008)' union all select 'Some Show Another No Season Number' union all select 'Some Show No Season Number' union all select 'Some Show With Season Number 1' union all select 'Some Show With Season Number 2' union all select 'Some Show With Season Number 10' ;with src as ( select Title, Trimmed = case when Title like '%Season [0-9]%' then stuff(title, 1, patindex('%season [0-9]%', title) + 6, '') else null end from #titles ) select Season = cast(case when Trimmed like '%[^0-9]%' then left(Trimmed, patindex('%[^0-9]%', Trimmed)) else Trimmed end as int), Title from src order by Season ``` Upvotes: 2 <issue_comment>username_2: I think this will do the trick... I simply recognizes changes from non-numeric to numeric. I haven't done any large scale testing but It should be reasonably fast. ``` SET QUOTED_IDENTIFIER ON; GO SET ANSI_NULLS ON; GO ALTER FUNCTION dbo.tfn_SplitForSort /* =================================================================== 11/11/2018 JL, Created: Comments =================================================================== */ --===== Define I/O parameters ( @string VARCHAR(8000) ) RETURNS TABLE WITH SCHEMABINDING AS RETURN WITH cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)), cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b), cte_Tally (n) AS ( SELECT TOP (LEN(@string)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM cte_n2 a CROSS JOIN cte_n2 b ), cte_split_string AS ( SELECT col_num = ROW_NUMBER() OVER (ORDER BY t.n) + CASE WHEN LEFT(@string, 1) LIKE '[0-9]' THEN 0 ELSE 1 END, string_part = SUBSTRING(@string, t.n, LEAD(t.n, 1, 8000) OVER (ORDER BY t.n) - t.n) FROM cte_Tally t CROSS APPLY ( VALUES (SUBSTRING(@string, t.n, 2)) ) s (str2) WHERE t.n = 1 OR SUBSTRING(@string, t.n - 1, 2) LIKE '[0-9][^0-9]' OR SUBSTRING(@string, t.n - 1, 2) LIKE '[^0-9][0-9]' ) SELECT so_01 = ISNULL(MAX(CASE WHEN ss.col_num = 1 THEN CONVERT(FLOAT, ss.string_part) END), 99999999), so_02 = MAX(CASE WHEN ss.col_num = 2 THEN ss.string_part END), so_03 = MAX(CASE WHEN ss.col_num = 3 THEN CONVERT(FLOAT, ss.string_part) END), so_04 = MAX(CASE WHEN ss.col_num = 4 THEN ss.string_part END), so_05 = MAX(CASE WHEN ss.col_num = 5 THEN CONVERT(FLOAT, ss.string_part) END), so_06 = MAX(CASE WHEN ss.col_num = 6 THEN ss.string_part END), so_07 = MAX(CASE WHEN ss.col_num = 7 THEN CONVERT(FLOAT, ss.string_part) END), so_08 = MAX(CASE WHEN ss.col_num = 8 THEN ss.string_part END), so_09 = MAX(CASE WHEN ss.col_num = 9 THEN CONVERT(FLOAT, ss.string_part) END), so_10 = MAX(CASE WHEN ss.col_num = 10 THEN ss.string_part END) FROM cte_split_string ss; GO ``` The function in use... ``` SELECT ts.* FROM #tvseason ts CROSS APPLY dbo.tfn_SplitForSort (ts.title) sfs ORDER BY sfs.so_01, sfs.so_02, sfs.so_03, sfs.so_04, sfs.so_05, sfs.so_06, sfs.so_07, sfs.so_08, sfs.so_09, sfs.so_10; ``` Results: ``` id title ----------- ------------------------------------------ 2 100 Season 1 4 100 Season 2 1 100 Season 03 5 100 Season 4 3 100 Season 10 11 Another 1st Anniversary Season 01 12 Another 2nd Anniversary Season 01 13 Another 10th Anniversary Season 01 9 Another Season 01 10 Another Season 02 16 Show 2 Season 1 6 Show Season 1 (2008) 7 Show Season 2 (2008) 8 Show Season 10 (2008) 14 Some Show Another No Season Number 15 Some Show No Season Number 17 Some Show With Season Number 1 18 Some Show With Season Number 2 19 Some Show With Season Number 10 ``` --===================================================================== [Edit 2020-09-23] I was looking back at some of my old posts and when I came across this one and wanted to see if I could get to work with a single value output. Adding 10 columns to the ORDER BY is just clunky... After a bit of thought, it occurred to me that converting the FLOATs to BINARY and the BINARY back to VARCHAR, I could reassemble the string with the STRING\_AGG() function. The net result would be string that produces the desired sort. ``` CREATE FUNCTION dbo.human_sort_string /* =================================================================== 09/23/2020 JL, Created: Just a test =================================================================== */ --===== Define I/O parameters ( @string varchar(8000) ) RETURNS TABLE WITH SCHEMABINDING AS RETURN WITH cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)), -- 10 cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b), -- 100 cte_Tally (n) AS ( SELECT TOP (LEN(@string)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM cte_n2 a CROSS JOIN cte_n2 b -- 10,000 ), cte_Parsed AS ( SELECT t.n, parsed_val = SUBSTRING(@string, ISNULL(NULLIF(t.n, 1), 0) + 1, LEAD(t.n, 1, 8000) OVER (ORDER BY t.n) - ISNULL(NULLIF(t.n, 1), 0)) FROM cte_Tally t CROSS APPLY ( VALUES (SUBSTRING(@string, t.n, 2)) ) sv (sub_val) WHERE t.n = 1 OR sv.sub_val LIKE '[0-9][^0-9]' OR sv.sub_val LIKE '[^0-9][0-9]' ) SELECT sort_string = STRING_AGG(ISNULL(CONVERT(varchar(8000), CONVERT(binary(8), TRY_CONVERT(float, p.parsed_val)), 2), p.parsed_val), '') WITHIN GROUP (ORDER BY p.n) FROM cte_Parsed p; GO ``` Now, the outer query looks like this... ``` SELECT ts.id, td.title FROM #tvseason ts CROSS APPLY dbo.human_sort_string(ts.title) hss ORDER BY hss.sort_string; ``` The actual results are identical to the previous function. Upvotes: 3 <issue_comment>username_3: This question requirement is complex. So it can't be achieved by a simple query. So my solution is below: First I create a sample data which will be use in this query. ``` CREATE TABLE #TVSEASON (TITLE VARCHAR(100)); INSERT INTO #TVSEASON (TITLE) VALUES ('100'), ('100 SEASON 03'), ('100 SEASON 1'), ('100 SEASON 10'), ('100 SEASON 2'), ('100 SEASON 4'), ('SHOW (2008) SEASON 1'), ('SHOW (2008) SEASON 2'), ('SHOW SEASON 1 (2008)'), ('SHOW SEASON 2 (2008)'), ('SHOW SEASON 10 (2008)'), ('ANOTHER 1ST ANNIVERSARY SEASON 01'), ('ANOTHER 2ND ANNIVERSARY SEASON 01'), ('ANOTHER 10TH ANNIVERSARY SEASON 01'), ('ANOTHER SEASON 01'), ('ANOTHER SEASON 02'), ('SOME SHOW ANOTHER NO SEASON NUMBER'), ('SOME SHOW NO SEASON NUMBER'), ('SHOW 2 THE 75TH ANNIVERSARY SEASON 1'), ('SOME SHOW WITH SEASON NUMBER 1'), ('SOME SHOW WITH SEASON NUMBER 2'), ('SOME SHOW WITH SEASON NUMBER 10') ``` For the achieved desired result I create a function for split all words and numbers from the text. (Note: I also remove st from 1st, nd from 2nd etc through function after trim the spaces between 1 st for safe side if any user mistakely type spaces between 1st, so if you think there is no chance of error then you remove LTRIM from that function, because for removing that values it is also remove th if text has value like "1 the title" which will be convert into 1 e title) ``` --CREATE SPLIT FUNCTION CREATE FUNCTION [dbo].[SplitAlphaNumeric] ( @LIST NVARCHAR(2000) ) RETURNS @RTNVALUE TABLE ( ID INT IDENTITY(1,1), WORDS NVARCHAR(100), NUMBERS INT ) AS BEGIN WHILE (PATINDEX('%[0-9]%',@LIST) > 0) BEGIN INSERT INTO @RTNVALUE (WORDS, NUMBERS) SELECT CASE WHEN PATINDEX('%[0-9]%',@LIST) = 0 THEN @LIST WHEN (PATINDEX('%[0-9]%',@LIST) = 1 AND PATINDEX('%[^0-9]%',@LIST) = 0) THEN '' WHEN PATINDEX('%[0-9]%',@LIST) = 1 THEN '' ELSE SUBSTRING(@LIST, 1, PATINDEX('%[0-9]%',@LIST) - 1) END, CASE WHEN PATINDEX('%[0-9]%',@LIST) = 0 THEN NULL WHEN (PATINDEX('%[0-9]%',@LIST) = 1 AND PATINDEX('%[^0-9]%',@LIST) = 0) THEN CAST(LTRIM(RTRIM(@LIST)) AS INT) WHEN PATINDEX('%[0-9]%',@LIST) = 1 THEN SUBSTRING(@LIST, 1, PATINDEX('%[^0-9]%',@LIST) - 1) ELSE NULL END SET @LIST = LTRIM(RTRIM(CASE WHEN PATINDEX('%[0-9]%',@LIST) = 0 OR (PATINDEX('%[0-9]%',@LIST) = 1 AND PATINDEX('%[^0-9]%',@LIST) = 0) THEN '' WHEN PATINDEX('%[0-9]%',@LIST) = 1 THEN CASE WHEN LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))) LIKE 'ST%' THEN SUBSTRING(LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))),3, LEN(LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))))) WHEN LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))) LIKE 'ND%' THEN SUBSTRING(LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))),3, LEN(LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))))) WHEN LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))) LIKE 'RD%' THEN SUBSTRING(LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))),3, LEN(LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))))) WHEN LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))) LIKE 'TH%' THEN SUBSTRING(LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))),3, LEN(LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))))) ELSE LTRIM(SUBSTRING(@LIST, PATINDEX('%[^0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[^0-9]%',REVERSE(@LIST)))) END ELSE SUBSTRING(@LIST, PATINDEX('%[0-9]%',@LIST), LEN(@LIST)-PATINDEX('%[0-9]%',REVERSE(@LIST))) END)) END INSERT INTO @RTNVALUE (WORDS) SELECT VALUE = LTRIM(RTRIM(@LIST)) RETURN END ``` In third step I use cross apply on calling function because function return table against given string value. On select query I insert all columns into temp table for sort values as per requirement in next step. ``` SELECT T.TITLE, A.ID, A.NUMBERS, A.WORDS INTO #FINAL FROM #TVSEASON T CROSS APPLY dbo.SplitAlphaNumeric(TITLE) A ``` From the temp table #Final I use stuff for concate all words to make title again without any number occurence in the text, and then use that values to order the title. > > You can change that query for order in any sequence like if you want > to order against the text then you order first textval column then > numbers, but if you want to order against summation of all the numbers > which are used in title then order numbers first after sum like I do > or else if you want to order on simple number without sum then don't > use group by clause and subquery and directly order against numbers. > In short you can achieved all the sequences respected to alpha numeric > values after modify that below query and the upper one are the base > query for all the goals. > > > ``` SELECT A.TITLE--, A.NUMBERS, A.TEXTVAL FROM ( SELECT A.TITLE, STUFF(( SELECT ' ' + B.WORDS FROM #FINAL B WHERE B.TITLE = A.TITLE FOR XML PATH(''),TYPE).VALUE('(./TEXT())[1]','VARCHAR(MAX)') ,1,1,'') TEXTVAL, SUM(ISNULL(A.NUMBERS,0)) NUMBERS FROM #FINAL A GROUP BY A.TITLE ) A ORDER BY A.TEXTVAL, A.NUMBERS DROP TABLE #FINAL DROP TABLE #TVSEASON ``` In last I drops both temp table from memory. I think it is the query for sorting values which you want because if anyone have different order requirement agains alphanumeric values they can achieved their requirement after litle bit modify that query. Upvotes: 2 <issue_comment>username_4: My answer takes advantage of OPEN\_JSON to split each title into words, it then replaces numbers with the same number of 'a's. e.g. 2 becomes aa and 10 becomes aaaaaaaa. This leaves us with a set of rows, 1 for each word. I then join these back together again using STRING\_AGG within each title to create a new title containing the numbers replaced with a's. I then sort by this and report the original title: ``` with Words1 as ( select title, REPLACE(REPLACE(value, '(', ''), ')', '') word, [key] as RowN from tvseason CROSS APPLY OPENJSON('["' + REPLACE(REPLACE(REPLACE(title,' ','","'),'\','\\"'),'"','\"') + '"]') ), Words2 AS ( SELECT title, CASE WHEN ISNUMERIC(word) = 1 THEN Replicate('a', CAST(Word as INT)) WHEN word like '%st' AND ISNUMERIC(LEFT(word, LEN(Word)-2)) = 1 THEN Replicate('a', CAST(LEFT(Word, LEN(Word)-2) as INT)) WHEN word like '%nd' AND ISNUMERIC(LEFT(word, LEN(Word)-2)) = 1 THEN Replicate('a', CAST(LEFT(Word, LEN(Word)-2) as INT)) WHEN word like '%rd' AND ISNUMERIC(LEFT(word, LEN(Word)-2)) = 1 THEN Replicate('a', CAST(LEFT(Word, LEN(Word)-2) as INT)) WHEN word like '%th' AND ISNUMERIC(LEFT(word, LEN(Word)-2)) = 1 THEN Replicate('a', CAST(LEFT(Word, LEN(Word)-2) as INT)) else Word END As Word, rowN from words1 ), Words3 AS ( SELECT title, STRING_AGG(Word, ' ') WITHIN GROUP (Order By rowN ASC) AS TitleLong FROM Words2 GROUP BY Title ) SELECT title FROM Words3 ORDER BY TitleLong ``` This gives the following results: ``` **title** 100 Season 1 100 Season 2 100 Season 03 100 Season 4 100 Season 10 Another 1st Anniversary Season 01 Another 2nd Anniversary Season 01 Another 10th Anniversary Season 01 Another Season 01 Another Season 02 Show 2 Season 1 Show Season 1 (2008) Show Season 2 (2008) Show Season 10 (2008) Some Show Another No Season Number Some Show No Season Number Some Show With Season Number 1 Some Show With Season Number 2 Some Show With Season Number 10 ``` Upvotes: 0
2018/03/20
966
3,541
<issue_start>username_0: I'm trying to make a basic contact form (using HTML and PHP). I usually host my websites as gh-pages on GitHub. However, the form won't work on GitHub as GitHub doesn't allow PHP because "GitHub Pages is a static site hosting service and doesn't support server-side code such as, PHP, Ruby, or Python." My question is: how can I try out my code to see if it works? This is the code. Html: ``` Send e-mail ``` PHP: ``` if (isset($_POST['submit'])) { $name = $_POST['name']; $subject = $_POST['subject']; $mailFrom = $_POST['mail']; $message = $_POST['message']; $mailTo = "<EMAIL>"; $headers = "From: ".$mailFrom; $txt = "You have received an e-mail from ".$name.".\n\n".$message; mail($mailTo, $subject, $txt, $headers); header("Location: index.php?mailsend"); } ``` PS. I know that I can use free services to make forms (such as <http://www.enformed.io> or <https://formspree.io>) but my question is whether there is a way to (even locally) check whether my code would work if I hosted it on a proper domain. Thank you<issue_comment>username_1: You can install XAMPP and run your pages locally. This package has PHP, Sendmail and Apache server in it. As well as MySQL if you need it. [XAMPP Installer](https://www.apachefriends.org/index.html) Upvotes: 2 <issue_comment>username_2: You need to install a web server and PHP to test it locally. You can install PHP since it comes with a simple web server. If instead you want more power over it you could easily install [XAMPP](https://apachefriends.org/). If you don't want to install anything, the easiest thing is to use a web hosting where you can upload your code and test it there, but you won't have too much flexibility over it. Upvotes: 1 <issue_comment>username_3: You can try Wamp service! Have a look: [Wamp](http://www.wampserver.com/en/) Upvotes: 1 <issue_comment>username_4: On Mac you can use MAMP for local On WINDOWS you can use WAMP for local If you have a domain and hosting you can upload to the domain and access the PHP directly with a browser to debug. Browsers output the errors of PHP also you can check your log of your server Upvotes: 1 <issue_comment>username_5: The easiest way out to your problem is downloading a package. There are a few packages that consist of all the components you will need to run your PHP files. If you're a Windows user, you can either download XAMPP here <https://www.apachefriends.org/download.html> or WAMP here <http://www.wampserver.com/en/> I personally prefer XAMPP over WAMP due to easier user interface. But both of them are equally good for your purpose. Otherwise, if you're a MAC user, you can go with downloading MAMP <https://www.mamp.info/en/downloads/> Installation is pretty straight forward, then you can run the XAMPP/WAMP/MAMP control panel which will start PHP/Apache/mySQL.. for you. You can type in localhost in your browser and if you've installed everything correctly it will show you a related XAMPP/WAMP/MAMP page. From there onward, you can setup and test your code. If you go with XAMPP/MAMP, you will place your code inside htdocs folder and type in localhost/foldername to access your code. So if you've installed XAMPP in C: drive, you will find htdocs inside your XAMPP folder in C. For WAMP, you will have to find www folder inside WAMP folder. Hope that helps. Upvotes: 0 <issue_comment>username_6: You need to have a local server that can be best provided by **WAMP**. Try installing it and running your pages through it. Upvotes: 0
2018/03/20
742
2,824
<issue_start>username_0: I am working on a searching system with pagination, and I am just confused while using my code, ``` SELECT * FROM musics WHERE name LIKE '%".$query."%' AND id BETWEEN $start_from AND $end_to ``` But it is not working as expected, it results 0 rows; I want to use LIKE query with within the range, like **id** from 4-8.<issue_comment>username_1: You can install XAMPP and run your pages locally. This package has PHP, Sendmail and Apache server in it. As well as MySQL if you need it. [XAMPP Installer](https://www.apachefriends.org/index.html) Upvotes: 2 <issue_comment>username_2: You need to install a web server and PHP to test it locally. You can install PHP since it comes with a simple web server. If instead you want more power over it you could easily install [XAMPP](https://apachefriends.org/). If you don't want to install anything, the easiest thing is to use a web hosting where you can upload your code and test it there, but you won't have too much flexibility over it. Upvotes: 1 <issue_comment>username_3: You can try Wamp service! Have a look: [Wamp](http://www.wampserver.com/en/) Upvotes: 1 <issue_comment>username_4: On Mac you can use MAMP for local On WINDOWS you can use WAMP for local If you have a domain and hosting you can upload to the domain and access the PHP directly with a browser to debug. Browsers output the errors of PHP also you can check your log of your server Upvotes: 1 <issue_comment>username_5: The easiest way out to your problem is downloading a package. There are a few packages that consist of all the components you will need to run your PHP files. If you're a Windows user, you can either download XAMPP here <https://www.apachefriends.org/download.html> or WAMP here <http://www.wampserver.com/en/> I personally prefer XAMPP over WAMP due to easier user interface. But both of them are equally good for your purpose. Otherwise, if you're a MAC user, you can go with downloading MAMP <https://www.mamp.info/en/downloads/> Installation is pretty straight forward, then you can run the XAMPP/WAMP/MAMP control panel which will start PHP/Apache/mySQL.. for you. You can type in localhost in your browser and if you've installed everything correctly it will show you a related XAMPP/WAMP/MAMP page. From there onward, you can setup and test your code. If you go with XAMPP/MAMP, you will place your code inside htdocs folder and type in localhost/foldername to access your code. So if you've installed XAMPP in C: drive, you will find htdocs inside your XAMPP folder in C. For WAMP, you will have to find www folder inside WAMP folder. Hope that helps. Upvotes: 0 <issue_comment>username_6: You need to have a local server that can be best provided by **WAMP**. Try installing it and running your pages through it. Upvotes: 0
2018/03/20
1,548
6,154
<issue_start>username_0: Look at the GIF first: [![enter image description here](https://i.stack.imgur.com/a9l20.gif)](https://i.stack.imgur.com/a9l20.gif) The 2nd page is listening to the actions on the 1st page. At first, the 2nd page has states: `counter = 2` and `language = Chinese`. But when buttons are pressed on the 1st page, 2nd page's states get updated. I am using a module called `ReSwift`, if you're familiar with `redux`, it is the Swift version of `redux`. However, I wonder how this can be done without using this module. (I'm not asking how to achieve exactly what's happening in the GIF, but `listen to updates/events on another page` in general, therefore, I hope there's no "hacky" solution). **If you're interested in the `ReSwift` way, here is the code** **Things below don't have much to do with the question** Language.swift: ``` enum Language { case English case Chinese } ``` LanguageState.swift: ``` import ReSwift struct LanguageState: StateType { var language: Language = .English } ``` CounterState.swift: ``` import ReSwift struct CounterState: StateType { var counter: Int = 0 } ``` AppState.swift: ``` import ReSwift struct AppState: StateType { var counterState: CounterState = CounterState() var languageState: LanguageState = LanguageState() } ``` Actions.swift: ``` import ReSwift struct CounterActionIncrease: Action {} struct CounterActionDecrease: Action {} struct ChangeLanguageToEnglish: Action {} struct ChangeLanguageToChinese: Action {} ``` LanguageReducer.swift: ``` import ReSwift func LanguageReducer(action: Action, state: LanguageState?) -> LanguageState { var state = state ?? LanguageState() switch action { case _ as ChangeLanguageToEnglish: state.language = .English case _ as ChangeLanguageToChinese: state.language = .Chinese default: break } return state } ``` CounterReducer.swift: ``` import ReSwift func CounterReducer(action: Action, state: CounterState?) -> CounterState { var state = state ?? CounterState() switch action { case _ as CounterActionIncrease: state.counter += 1 case _ as CounterActionDecrease: state.counter -= 1 default: break } return state } ``` AppReducer.swift: ``` import ReSwift func AppReducer(action: Action, state: AppState?) -> AppState { return AppState( counterState: CounterReducer(action: action, state: state?.counterState), languageState: LanguageReducer(action: action, state: state?.languageState) ) } ``` Then, in your `AppDelegate.swift`: ``` import UIKit import ReSwift let store = Store(reducer: AppReducer, state: nil) ... ... ``` Finally, you can subscribe to store in your `ViewControllers` in the standard way<issue_comment>username_1: You can paste this into a playground to get a handle of the flow. ``` import UIKit class ObjectA { let interestedData = "slick daddy" init() { updateData() } func updateData() { NotificationCenter.default.post(name: Notification.Name("objectADataUpdate"), object: interestedData) } } class ObjectB { init() { addObserver() } func addObserver() { NotificationCenter.default.addObserver(self, selector: #selector(objectADataUpdateHandler(_:)), name: Notification.Name("objectADataUpdate"), object: nil) } @objc func objectADataUpdateHandler(_ sender: Notification) { guard let data = sender.object as? String else { return } print(data) } } let b = ObjectB() let a = ObjectA() // prints "slick daddy" ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use `NotificationCenter` to accomplish that. First we have to create a singleton class and also create a global variable `didUpdateNotificationName` that we are going to use to post events and also to subscribe for events: ``` let didUpdateDataNotificationName = "didUpdateDataNotificationName" class AppState { static var shared = AppState() private init(){ self.counter = 0 self.language = "English" } private (set) var counter: Int { didSet { NotificationCenter.default.post(name: NSNotification.Name(rawValue: didUpdateDataNotificationName), object: nil) } } private (set) var language: String { didSet { NotificationCenter.default.post(name: NSNotification.Name(rawValue: didUpdateDataNotificationName), object: nil) } } func update(counter: Int){ self.counter = counter } func update(language: String){ self.language = language } } ``` After that, on each UIViewController you can add a listener for updates: ``` NotificationCenter.default.addObserver( self, selector: #selector(updateView), name: NSNotification.Name(rawValue: didUpdateDataNotificationName), object: nil) ``` Also make sure to implement the method that are going to be executed on each notification, in our case `updateView`: ``` @objc func updateView(){ label.text = "\(DataModel.shared.counter) \(DataModel.shared.language)" } ``` Now, every time that you update your variables in `AppState` class, a notification is going to be sent to all observers. One really important note is that when you're working with notifications, you should remove the observer when you no longer needs it. For instance in the `deinit` method of your class: ``` deinit { NotificationCenter.default.removeObserver( self, name: NSNotification.Name(rawValue: didUpdateDataNotificationName), object: self) } ``` Upvotes: 1 <issue_comment>username_3: In case of UITabBarController you can simply access the SecondViewController in FirtsViewController by using the below code ``` var svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController! ``` Upvotes: 0
2018/03/20
422
1,630
<issue_start>username_0: I'm trying to calculate the number of payments but output was wrong so i tried to calculate a simple operation on the month value.But "+" operator doesn't sum my values it acts like string.For example 3 and 5,output isnt 8 its 35. ``` Mortgage Calculator function validateForm() { var principal = princ.value; var interestrate = interest.value; var monthlypayment = monthly.value; var months=(principal)+(interestrate); document.getElementById("demo").innerHTML=months; } Principal: Interest Rate: Run ```<issue_comment>username_1: The actual type of the value is `string`. That's why string concatenation is happening. You have to use `parseInt` to convert string to integer to perform intended arithmetic operation. **Change:** `var months=(principal)+(interestrate);` **To:** `var months = parseInt(principal) + parseInt(interestrate);` Upvotes: 1 <issue_comment>username_2: The values you are summing are strings. You need to convert them to integers: ``` parseInt(principal)+parseInt(interestate) ``` The reason for this is that input values are always strings. AFAIK, this is even if you set the type to `number`. `parseInt(s)` converts a string s to an int. Upvotes: 1 <issue_comment>username_3: ``` var months=parseInt(principal)+parseInt(interestrate); ``` Values need to be converted to an integer first. Upvotes: -1 <issue_comment>username_4: Your input values are treated as string as they are textbox inputs. Parse the values first before adding them up. e.g. `var principal = parseInt(princ.value); var interestrate = parseInt(interest.value);` Upvotes: -1
2018/03/20
378
1,221
<issue_start>username_0: The program is meant to invert the values in the array. When the program is run, the only values that show are 3 and 2, then it ends. I've been looking online but I can't figure out why this happens. Switching val[i] for temp in the SOP gives values of 0 and 1 then ends. ``` int[] val = {0, 1, 2, 3}; int temp; for(int i=0;i ```<issue_comment>username_1: Because your for loop only iterate for values 0 and 1, then at the end it prints only 0th and 1st elements, try following ``` int[] val = {0, 1, 2, 3}; int temp; for(int i=0;i ``` Upvotes: 2 <issue_comment>username_2: It makes sense to use val.lenth/2 to only traverse half of the array, swapping values as you go. It does not make sense to only traverse half of the array while trying to print the entire array. Try using another for loop to print out the contents of the ENTIRE array. edit: I tried not to just give the answer Upvotes: 1 <issue_comment>username_3: ``` for(int i=0;i ``` val.length/2= 4/2 = 2 so that the for loop will only run twice. Thats why it prints only the 3 and 2. ``` int[] val = {0, 1, 2, 3}; int temp; for(int i=0;i ``` Upvotes: 1
2018/03/20
776
2,633
<issue_start>username_0: This is something that makes sense in my head but I haven't been able to find any facts/articles to back this up. Essentially is doing something like ``` render() { return ( someBoolean && Some Markup ) } ``` less performant than ``` render() { return ( someBoolean && ) } ``` where `SomeComponent` has the same exact markup as the previous example. My reasoning is since the markup will have to be created on every re-render it'll take up more memory whereas the saved component `SomeComponent` will be referenced in memory and won't have to be created on every re-render. Is there somewhere in the react docs that explains this more thoroughly? Or is this reasoning not accurate?<issue_comment>username_1: JSX is syntactic sugar for `React.createElement`. As it can be seen in [Babel REPL](https://babeljs.io/repl/#?babili=false&browsers=&build=&builtIns=false&code_lz=MYGwhgzhAEDCD2BbADvAdgUzQF2gbwCgAnLAEwyIAoBKfA6aE7AVyLWkvoegiQwCF48EBjDsAZOOgAeUgEsAbgD4Ayn2gBZMEQDWzZNID085V2oEAvgWJkKNOgyat2nbjz6DhoiVOlrEGAgo6Fi4hkpmlpZAA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=true&fileSize=false&lineWrap=false&presets=es2015%2Ces2016%2Ces2017%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3%2Ces2015-loose&prettier=false&targets=&version=6.26.0&envVersion=), they are ``` return someBoolean && React.createElement( "div", null, "Some Markup" ); ``` and ``` return someBoolean && React.createElement(SomeComponent, null); ``` respectively. When `someBoolean` is falsy, `React.createElement` isn't called and `render` becomes no-op. `SomeComponent` isn't cached, it is re-created every time. In comparison with raw markup, it provides negligible overhead, considering that it is a stateless component: ``` const SomeComponent = () => Some Markup; ``` Both options are very fast and aren't supposed to be optimized. Upvotes: 3 [selected_answer]<issue_comment>username_2: Whether it's conditional or not is not an issue, as neither will be evaluated past the `&&` if `someBoolean` is false. The real question is whether a defined React subcomponent has a performance advantage or penalty versus plain JSX markup defined within another component. For practical purposes, there is no performance difference unless you are making use of custom functions for lifecycle hooks. For example, if you use a subcomponent, you may define a separate `shouldComponentUpdate` method within that component and thereby decouple its updates from the parent. In the case of plain JSX, it will update as part of the parent component. Upvotes: 1
2018/03/20
661
2,216
<issue_start>username_0: I dynamically create a button in the way I found in the Internet: ``` ... outPut += "" + ""+ "[![\"\"](\"http://placehold.it/700x400\")](\"#\")"+ ""+ "#### "+ "["+ nome +"](\"#\")"+ " "+ "##### "+ preco +" "+ ""+ descricao +" "+ ""+ ""+ "+ Carrinho"+ ""+ ""+ ""; ... $("#divCards").html(outPut); ``` And Imply the method of click on each one in this way: ``` $(".btn-success-cart").click(function(event){ event.preventDefault(); var _id = Number( $(this).attr("data-id") ); var _nome = $(this).attr("data-nome"); var _descricao = $(this).attr("data-descricao"); var _preco = Number( $(this).attr("data-preco") ); console.log("Item add"); addItem(_id, _nome, _descricao, _preco, 1); updateCart(); }); ``` But nothing happens when I click the generated buttons.<issue_comment>username_1: > > Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on() > > > You need to bind on a static element that exists when the code `.on()` is executing. Use event delegation: ``` $('#divCards').on('click', '.btn-success-cart', function(event){ event.preventDefault(); var _id = Number( $(this).attr("data-id") ); var _nome = $(this).attr("data-nome"); var _descricao = $(this).attr("data-descricao"); var _preco = Number( $(this).attr("data-preco") ); console.log("Item add"); addItem(_id, _nome, _descricao, _preco, 1); updateCart(); }); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: I know it's a bit late to answer here but similar situation happened to me and above accepted answer worked sort of. But it fires the event multiple times because my script included to call that function which creates click event several times for different occasions. So each call would create the click event repeatedly. Then when a user click the button, the function will be called multiple times. Therefore I had to off click then on click. Just adding this answer so that anyone else has same issue with me may get help. ``` ('#divCards').off('click', '.btn-success-cart').on('click', '.btn-success-cart', (event) => { ...... } }); ``` Upvotes: 0
2018/03/20
1,460
4,512
<issue_start>username_0: Is there anyway to get a type from a static base class method? For instance ``` class A { static std::type_info getClassType { // What do I do here } }; class B : public A { }; B instance; auto my_type = instance::getClassType() ``` With C++'s lack of static variable overloading, I am having a hard time figuring out a way to determine class type across classes without doing a special virtual function in every child class which I am trying to avoid due to the sheer number.<issue_comment>username_1: Make a class that will be a template. Subclass from it. Pass the child type as the template parameter. With that, base class will know the child. The `T` will be the child type. Code: ``` #include using namespace std; template class thebase { static T instance; public: static T& getInstance() { return instance; } }; template T thebase::instance; class sub1 : public thebase { public: void tell() { std::cout << "hello1: " << this << std::endl; } }; class sub2 : public thebase { public: void tell() { std::cout << "hello2: " << this << std::endl; } }; int main() { sub1& ref1 = sub1::getInstance(); sub1& ref2 = sub1::getInstance(); std::cout << ((&ref1) == (&ref2)) << std::endl; sub1::getInstance().tell(); sub2::getInstance().tell(); sub1::getInstance().tell(); sub2::getInstance().tell(); return 0; } ``` Output: ``` 1 hello1: 0x55874bff1193 hello2: 0x55874bff1192 hello1: 0x55874bff1193 hello2: 0x55874bff1192 ``` This kind of code pattern is sometimes called [CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) Upvotes: 3 [selected_answer]<issue_comment>username_2: Someone above mentioned the CRTP or "Curiously recurring template pattern". Using this, I have not tested it, but it appears I may be able to write: ``` template class A { static std::type\_info getClassType { return typeid(T); } }; class B : public A**{ }; B instance; auto my\_type = instance::getClassType()** ``` Upvotes: 0 <issue_comment>username_3: > > it boils down to there being a manager class that keeps track of one instance of a variety of classes and their states. You may use this singleton "instance" of these sub classes, but I want to be able to say MySubClass::instance() and then have it get the correct instance from the manager without having to write it in each sub class. > > > You can implement the managed classes using [CRTP ("Curiously recurring template pattern")](https://stackoverflow.com/questions/4173254/) so a base class knows the derived class types and can then delegate that information to the manager class. Try something like this: ``` #include #include #include class Base { public: virtual ~Base() {} }; class Manager { private: static std::map m\_instances; public: template static void addInstance(Base \*inst) { if (!m\_instances.insert(std::make\_pair(std::type\_index(typeid(T)), inst)).second) throw ...; // only 1 instance allowed at a time! } template static void removeInstance() { auto iter = m\_instances.find(std::type\_index(typeid(T))); if (iter != m\_instances.end()) m\_instances.erase(iter); } template static T\* getInstance() { auto iter = m\_instances.find(std::type\_index(typeid(T))); if (iter != m\_instances.end()) return static\_cast(iter->second); return nullptr; } }; ``` ``` std::map Manager::m\_instances; ``` ``` template class A : public Base { public: A() { Manager::addInstance(this); } ~A() { Manager::removeInstance(); } static Derived\* getInstance() { return Manager::getInstance(); } }; class B : public A**{ ... }; class C : public A { ... };** ``` ``` B b_inst; C c_inst; ... B *pB = B::getInstance(); if (pB) ... C *pC = C::getInstance(); if (pC) ... ``` [Live Demo](https://ideone.com/3Y1EF2) Upvotes: 2 <issue_comment>username_4: Based on your own example of code in your own answer, here's a final result working: ``` # include # include template class A { public: static const std::type\_info& getClassType() { return typeid(T); } }; class B : public A**{ /\* ... \*/ }; class C : public A { /\* ... \*/}; class D : public A { /\* ... \*/}; int main() { B b; C c; D d; auto& b\_type = b.getClassType(); auto& c\_type = c.getClassType(); auto& d\_type = d.getClassType(); std::cout << b\_type.name() << std::endl; std::cout << c\_type.name() << std::endl; std::cout << d\_type.name() << std::endl; }** ``` > > Output: > 1B 1C 1D > > > Upvotes: 1
2018/03/20
537
2,247
<issue_start>username_0: I am new to front end web development. I work with a designer who makes mockups (no html) wire frames and the finished product is a React/Angular single page application. I was thinking of this workflow. 1) Get the mockup wireframe 2) Recreate it in HTML/CSS and collaborate with the designer to make quick changes. 3) After completion, then take the HTML and convert it to the React/Angular single page application. Thanks.<issue_comment>username_1: Hi Mitch welcome to web dev! So I can't say I'd recommend that workflow exactly, only because you don't want to have to write and rewrite code and make it into components. Working with a designer myself we collaborate closely on a daily basis. If your designer is using sketch (which he loves) he can create wireframes and prototypes. Our workflow is similar to what you are proposing, this is what we do: 1. We have a feature request that we need to design and build 2. He creates a mockup / wireframe 3. Then he whips that up into a prototype (optional) 4. From there I turn the prototype into working code (we use angular) 5. When I think I have recreated his prototype I ask him to look it over and we discuss from there. For me, it is easy to go back and fix some CSS or change some HTML around, just keep everything organized and well commented so you can easily change stuff in the future as your app grows. One other thing I would recommend is that you should create your own form of a wireframe so that you can see how your components are going to be placed and interacting with one another. I hope that this helps you and your designer come up with a workflow that you both enjoy! Upvotes: 1 <issue_comment>username_2: This is my workflow. I import the figma, sketch, adobexd design file into Desech Studio to get a clean html structure positioned with css grids. Then I need to adjust the margins and sizes and I'm done with the conversion. And finally I work on the responsiveness of the website. Then I install and enable the react plugin and when I save the project, it will export react code. And then I work on the react code and components. Here's the [github repository](https://github.com/desech/studio-react) for the react plugin. Upvotes: 0
2018/03/20
3,501
8,841
<issue_start>username_0: My Postgresql database stopped working, which has shut down all of my Django applications that use it. I tried restarting with 'service postgresql restart', but it gives me this response ``` * Starting PostgreSQL 9.3 database server * The PostgreSQL server failed to start. Please check the log output. ``` I checked the logs at /var/log/postgresql, but the most recent logs file has nothing in it. I checked the one before that, and I don't think anything in particular besides a lot of errors that say there is no disc space. **/var/log/postgresql/postgresql-9.3-main.log.1** ``` 2018-03-15 08:46:09 CDT LOG: could not write temporary statistics file "pg_stat_tmp/db_12061.tmp": No space left on device 2018-03-15 08:46:09 CDT LOG: could not close temporary statistics file "pg_stat_tmp/db_0.tmp": No space left on device 2018-03-15 08:46:09 CDT LOG: could not close temporary statistics file "pg_stat_tmp/global.tmp": No space left on device 2018-03-15 08:46:10 CDT LOG: could not close temporary statistics file "pg_stat_tmp/db_0.tmp": No space left on device 2018-03-15 08:46:10 CDT LOG: could not close temporary statistics file "pg_stat_tmp/global.tmp": No space left on device 2018-03-15 08:46:15 CDT ERROR: could not extend file "base/16385/616778.1": No space left on device 2018-03-15 08:46:15 CDT HINT: Check free disk space. 2018-03-15 08:46:15 CDT STATEMENT: INSERT INTO "vehicle_vehicleimage" ("vehicle_id", "image_url", "display_sequence") VALUES (1606764, 'https://content.homenetiol.com/2001722/2120878/640x480/43d0a25930554cdbbbd0834c9803e5ad.jpg', 1) RET$ 2018-03-15 08:46:19 CDT LOG: using stale statistics instead of current ones because stats collector is not responding 2018-03-15 08:46:20 CDT LOG: using stale statistics instead of current ones because stats collector is not responding 2018-03-16 08:45:49 CDT LOG: could not close temporary statistics file "pg_stat_tmp/db_0.tmp": No space left on device 2018-03-16 08:45:49 CDT LOG: could not close temporary statistics file "pg_stat_tmp/global.tmp": No space left on device 2018-03-16 08:45:53 CDT ERROR: could not extend file "base/16385/616778.1": No space left on device 2018-03-16 08:45:53 CDT HINT: Check free disk space. 2018-03-16 08:45:53 CDT STATEMENT: INSERT INTO "vehicle_vehicleimage" ("vehicle_id", "image_url", "display_sequence") VALUES (1587463, 'https://content.homenetiol.com/2001722/2120878/640x480/c80fb80f8dc04c2581872ad2cf221cbc.jpg', 1) RET$ 2018-03-16 08:45:59 CDT LOG: using stale statistics instead of current ones because stats collector is not responding 2018-03-17 08:45:48 CDT ERROR: could not extend file "base/16385/616778.1": No space left on device 2018-03-17 08:45:48 CDT HINT: Check free disk space. 2018-03-17 08:45:48 CDT STATEMENT: INSERT INTO "vehicle_vehicleimage" ("vehicle_id", "image_url", "display_sequence") VALUES (1144699, 'https://content.homenetiol.com/2001722/2120878/640x480/4e7711dd0d5148eeaadd1e8a7f00b0eb.jpg', 1) RET$ 2018-03-18 08:45:44 CDT LOG: could not close temporary statistics file "pg_stat_tmp/db_0.tmp": No space left on device 2018-03-18 08:45:44 CDT LOG: could not close temporary statistics file "pg_stat_tmp/global.tmp": No space left on device 2018-03-18 08:45:47 CDT ERROR: could not extend file "base/16385/616778.1": No space left on device 2018-03-18 08:45:47 CDT HINT: Check free disk space. 2018-03-18 08:45:47 CDT STATEMENT: INSERT INTO "vehicle_vehicleimage" ("vehicle_id", "image_url", "display_sequence") VALUES (1144694, 'https://content.homenetiol.com/2001722/2120878/640x480/3dee837dd31942c5a26bc73775f07dba.jpg', 0) RET$ 2018-03-18 08:45:54 CDT LOG: using stale statistics instead of current ones because stats collector is not responding 2018-03-18 10:21:40 CDT FATAL: password authentication failed for user "socialauto" 2018-03-18 10:21:40 CDT DETAIL: Connection matched pg_hba.conf line 17: "local all all md5" 2018-03-15 08:46:15 CDT ERROR: could not extend file "base/16385/616778.1": No space left on device 2018-03-15 08:46:15 CDT HINT: Check free disk space. 2018-03-15 08:46:15 CDT STATEMENT: INSERT INTO "vehicle_vehicleimage" ("vehicle_id", "image_url", "display_sequence") VALUES (1606764, 'https://content.homenetiol.com/2001722/2120878/640x480/43d0a25930554cdbbbd0834c9803e5ad.jpg', 1) RET$ 2018-03-15 08:46:19 CDT LOG: using stale statistics instead of current ones because stats collector is not responding 2018-03-15 08:46:20 CDT LOG: using stale statistics instead of current ones because stats collector is not responding 2018-03-16 08:45:49 CDT LOG: could not close temporary statistics file "pg_stat_tmp/db_0.tmp": No space left on device 2018-03-16 08:45:49 CDT LOG: could not close temporary statistics file "pg_stat_tmp/global.tmp": No space left on device 2018-03-16 08:45:53 CDT ERROR: could not extend file "base/16385/616778.1": No space left on device 2018-03-16 08:45:53 CDT HINT: Check free disk space. 2018-03-16 08:45:53 CDT STATEMENT: INSERT INTO "vehicle_vehicleimage" ("vehicle_id", "image_url", "display_sequence") VALUES (1587463, 'https://content.homenetiol.com/2001722/2120878/640x480/c80fb80f8dc04c2581872ad2cf221cbc.jpg', 1) RET$ 2018-03-16 08:45:59 CDT LOG: using stale statistics instead of current ones because stats collector is not responding 2018-03-17 08:45:48 CDT ERROR: could not extend file "base/16385/616778.1": No space left on device 2018-03-17 08:45:48 CDT HINT: Check free disk space. 2018-03-17 08:45:48 CDT STATEMENT: INSERT INTO "vehicle_vehicleimage" ("vehicle_id", "image_url", "display_sequence") VALUES (1144699, 'https://content.homenetiol.com/2001722/2120878/640x480/4e7711dd0d5148eeaadd1e8a7f00b0eb.jpg', 1) RET$ 2018-03-18 08:45:44 CDT LOG: could not close temporary statistics file "pg_stat_tmp/db_0.tmp": No space left on device 2018-03-18 08:45:44 CDT LOG: could not close temporary statistics file "pg_stat_tmp/global.tmp": No space left on device 2018-03-18 08:45:47 CDT ERROR: could not extend file "base/16385/616778.1": No space left on device 2018-03-18 08:45:47 CDT HINT: Check free disk space. 2018-03-18 08:45:47 CDT STATEMENT: INSERT INTO "vehicle_vehicleimage" ("vehicle_id", "image_url", "display_sequence") VALUES (1144694, 'https://content.homenetiol.com/2001722/2120878/640x480/3dee837dd31942c5a26bc73775f07dba.jpg', 0) RET$ 2018-03-18 08:45:54 CDT LOG: using stale statistics instead of current ones because stats collector is not responding 2018-03-18 10:21:40 CDT FATAL: password authentication failed for user "socialauto" ``` I checked the disc space on the virtual machine hosting the database with the 'df' command, and it does indeed look like all the space has been used up ``` Filesystem 1K-blocks Used Available Use% Mounted on /dev/root 49300032 49283648 0 100% / devtmpfs 2014088 4 2014084 1% /dev none 4 0 4 0% /sys/fs/cgroup none 403388 340 403048 1% /run none 5120 0 5120 0% /run/lock none 2016924 0 2016924 0% /run/shm none 102400 0 102400 0% /run/user ``` I also get this weird message whenever I try to autocomplete a path with tab ``` -bash: cannot create temp file for here-document: No space left on device ``` Is the only way to get Postgres up and running to increase the disc space on my machine. Is there any way to use **'service postgresql restart'** with some debug flag to see the error its facing without having to go into a log file ?<issue_comment>username_1: You can `strace` the server process ... But seriously — if you are out of space, that is the reason. If PostgreSQL cannot allocate a new transaction log, it will refuse to start. Upvotes: 3 [selected_answer]<issue_comment>username_2: the easiest would be starting the postgres and tailing the log, smth like ``` tail -f ${PGDATA}/postgresql-$(date --iso-8601)* | grep "ERROR\|FATAL" ``` or whatever your log looks like. And surely you can't run database without free space. As you mentioned yourself you can't even use bash autocompletion. Upvotes: 1 <issue_comment>username_3: How do you expect the database to operate if the disk is full? Where is new data stored, or logs, or transaction logs? Why don't you start by cleaning up disk space. Find out what is using disk space, and remove what is unnecessary. Uninstall packages you don't need, clean up old logfiles in /var/log, or temporary files in /tmp or /var/tmp. And please do not delete PostgreSQL WAL files! Upvotes: 1
2018/03/20
754
2,373
<issue_start>username_0: I want to print a constant message in the form of: ``` Time remaining: X Seconds ``` Where `X` will be a count-down number. But I don't want to have an output like: ``` Time remaining: 5 Seconds Time remaining: 4 Seconds Time remaining: 3 Seconds Time remaining: 2 Seconds ... ``` I want only the number to change in the same text line. Is it possible using escape sequences or other way?<issue_comment>username_1: Yes you can! Please refer to the answer found [here](https://stackoverflow.com/questions/17436240/python-2-7-carriage-return-countdown) The code has been modified a little to look more like you want, and to use the more recent string formatting. ``` from time import sleep import sys for i in range(10): sys.stdout.write("\rTime remaining: {} Seconds".format(i)) sys.stdout.flush() sleep(1) print '\n' ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Add argument `end='\r'` in your `print` function. ``` import time x = 10 width = str(len(str(x))) while x > 0: print('Time remaining: {{:{:}}} seconds'.format(width).format(x), end='\r') x -= 1 time.sleep(1) ``` You may also refer to [this post](https://stackoverflow.com/questions/4897359/output-to-the-same-line-overwriting-previous-output-python-2-5). Upvotes: 1 <issue_comment>username_3: [I found this link](https://stackoverflow.com/questions/2122385/dynamic-terminal-printing-with-python) And got it to work. The "stuff" is there to show that texted displayed before the count down is not getting 'clear'ed ``` import time import sys num = 5 print('stuff') while(num >= 0): sys.stdout.write("\rTime remaining: {} Seconds".format(num)) sys.stdout.flush() time.sleep(1) num -= 1 ``` Upvotes: 1 <issue_comment>username_4: You can set end= " " to remove newlines and add a carriage return '\r' So the correct program which should work for you is: ``` n = 100 while n > 0: print('\rTime remaining: {} Seconds'.format(n), end=' ') n -= 1 time.sleep(1) print(' ') ``` Upvotes: 1 <issue_comment>username_5: You also have the `flush` parameter in the [`print`](https://docs.python.org/3/library/functions.html#print) method (I just discovered it as well): ``` from time import sleep for i in range(10): print(f"\rTime remaining: {i} Seconds", end='', flush=True) sleep(1) ``` Upvotes: 2
2018/03/20
280
965
<issue_start>username_0: I'm trying to read all the bytes of a file using Julia into an array. So far I have: ``` s = open(file_path,"r") ``` I'm not sure how to tell how big the file is. I'm also not sure that I need to. Perhaps I can just pass an empty array into readbytes!<issue_comment>username_1: The simplest way do do it is to use `read` function. You can either pass an open stream to it like `data = read(s)` if `s` was opened with the code you have provided above. Alternatively you can simply write `data = read(file_path)`. In this way you do not have to close the stream yourself. You can find out the details by reading help of `read` by executing `?read` in Julia REPL. To get the size of the file in bytes you can use `filesize(file_path)` function. Upvotes: 4 [selected_answer]<issue_comment>username_2: After a bit of testing this seems to work ... ``` s = open(file_path,"r") data = UInt8[] readbytes!(s,data,Inf) close(s) ``` Upvotes: 1
2018/03/20
547
1,771
<issue_start>username_0: I can't figure out how to access the enum class enumerators, either as a returning value or just a value, from a templatized class. As you can see in the following example I'm totally clueless. I've googled over the error messages with no luck. Glad if you point me out to the correct syntax. First these are the errors: $ g++ -Wall -std=c++11 -o main.out main.cpp main.cpp:25:1: **error: need ‘typename’ before ‘C::Values’ because ‘C’ is a dependent scope** C::Values C::Get() // <-- Error here ... ^ main.cpp: In function ‘int main()’: main.cpp:35:2: **error: ‘template class C’ used without template parameters** C::Values values; // <-- ... and here ^ $ And this is the complete example so it can be tested: ``` template class C { public: enum class Values{ one, two }; C(); Values Get(); private: int val; }; template C::C() : val{ Val } {} template C::Values C::Get() // <-- Error here ... { return Values::one; } int main(void) { C<5> aVariable; C::Values values; // <-- ... and here return 0; } ``` Thank your in advanced!!<issue_comment>username_1: The simplest way do do it is to use `read` function. You can either pass an open stream to it like `data = read(s)` if `s` was opened with the code you have provided above. Alternatively you can simply write `data = read(file_path)`. In this way you do not have to close the stream yourself. You can find out the details by reading help of `read` by executing `?read` in Julia REPL. To get the size of the file in bytes you can use `filesize(file_path)` function. Upvotes: 4 [selected_answer]<issue_comment>username_2: After a bit of testing this seems to work ... ``` s = open(file_path,"r") data = UInt8[] readbytes!(s,data,Inf) close(s) ``` Upvotes: 1
2018/03/20
254
952
<issue_start>username_0: I added dotnet task (.Net Core) to do a nuget push. In the Nuget server section it asked me to use create a new Nuget Connection. I went with the API Key option and game in connection name,Feed URL, and API Key. when I run this step I get the following error > > Error: DotNetCore currently does not support using an encrypted Api > Key. > > > is this a limitation or am i doing something wrong? Please note from my desktop I am about to create package and push the package using apikey.<issue_comment>username_1: Pushing package to NuGet server through Command Line task by calling `dotnet nuget push` command to deal with this issue. Upvotes: 3 [selected_answer]<issue_comment>username_2: I faced this issue and found a alternative way for this. Instead of using `dotnet nuget push` use `nuget push`. [![Azure build pipeline](https://i.stack.imgur.com/CuDvK.png)](https://i.stack.imgur.com/CuDvK.png) Upvotes: 3
2018/03/20
1,496
5,805
<issue_start>username_0: I define mContext as val and I need to assign a value to it in the fun onCreate. The code `private lateinit val mContext: Context` isn't correct, how can I do? ``` class UIMain : AppCompatActivity() { private val mContext: Context override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_main) mContext = this } } ``` **Answer Strelok** The keyword `this` isn't always fit, just like the following code, so I think it's more handier to assign `this` to mContext. ``` private Context mContext; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_main); mContext=this; findViewById(R.id.btnClose).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Hello A", Toast.LENGTH_LONG).show(); Toast.makeText(mContext, "Hello B", Toast.LENGTH_LONG).show(); //Toast.makeText(this, "Hello C", Toast.LENGTH_LONG).show(); //Doesn't work finish(); } }); } ```<issue_comment>username_1: I agree with the person commenting, it's rather strange why you want to keep a reference to `this` in a private property (potential memory leak). But, in any case, Kotlin has a `lateinit` modifier that let's you delay setting a property value, but it must be set before the property is used for the first time. ``` class UIMain : AppCompatActivity() { private lateinit var mContext: Context override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_main) mContext = this } } ``` Upvotes: 1 <issue_comment>username_2: If you're using the `lateinit` keyword, you'll have to change from `val` to `var`, thus losing the immutability. If that's ok for you, username_1's answer will suffice. But if you really need a `val` on your code for any reason, you can try the [lazy delagate property](https://kotlinlang.org/docs/reference/delegated-properties.html#lazy). As stated on the [Android Essense](https://androidessence.com/android/understanding-nullability-in-kotlin/) blog: > > This property takes in a lambda, **which is executed the first time the > property is accessed**. After that, it will return the value that was > assigned to it. This way we can declare the property as immutable, and > non-null, so that as long as the fragment (or Activity) is created before we access it the first time. > > > For example, in your case you could try to do this: ``` private val mContext : Context by lazy { this } ``` **In short:** * If your value can or need to be mutable, use `lateinit` * If your value is meant to be initialized once, and shared across your methods, use `lazy` with `val`. But as stated by the others, in your specific case it's better to just call `this` when you need the Activity/Context reference. **Edit:** As per your example on why you would need a `mContext` inside your Activity, I still say you don't need it. Instead of trying to call `this` and use it on the `Toast#makeText()` inside your anonymous function directly, you could either: * Change `this` to `UIMain.this`. * Create a method inside your Activity, and call that method inside the anonymous function. e.g.: `findViewById(R.id.btnClose).setOnClickListener { otherMethod() }`, and inside that method you can reference the Activity using `this` again. Upvotes: 4 [selected_answer]<issue_comment>username_3: I think what you really want is a **qualified this expression** like ``` this@UIMain ``` as in ``` Toast.makeText(this@UIMain, "Hello C", Toast.LENGTH_LONG).show(); //works everytime ``` that solves all your issues. See [Kotlin this expression](https://kotlinlang.org/docs/reference/this-expressions.html) PS: If that solves your problem you should rename the question to "how to use outer this in nested object" Upvotes: 2 <issue_comment>username_4: We have never liked Toast even with jelly Here is a way to replace that little slice of toast with a custom visible error message. Yes we included the toast since the question is about Toast. To use this concept you need to add a TextView some where on your screen. This code is testing for valid entry in two EditText fields. ``` fun onLAMmultiply(view: View ){ if(etValOne.text.length == 0){ error("Enter First Value") toast("Enter First Value TOAST") etValOne.requestFocus() return@onLAMmultiply } if(etValTwo.text.length == 0){ error("Enter Second Value") toast("Enter Second Value TOAST") etValTwo.requestFocus() return@onLAMmultiply } var X = etValOne.text.toString() var Y = etValTwo.text.toString() val multB = {X:Double,Y:Double -> X.times(Y)} val df = DecimalFormat("0.00") //val df = DecimalFormat("#.##") df.roundingMode = RoundingMode.CEILING df.format(multB(X.toDouble(),Y.toDouble())) etANS.setText(df.format(multB(X.toDouble(),Y.toDouble())).toString()) etANS.setText(multB(X.toDouble(),Y.toDouble()).toString()) } fun Context.toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun error(msg:String){ object : CountDownTimer(4000, 1000) { override fun onTick(millisUntilFinished: Long) { tvError.visibility = View.VISIBLE tvError.setText(msg) } override fun onFinish() { tvError.visibility = View.INVISIBLE tvError.setText("") } }.start() } ``` Upvotes: 1
2018/03/20
541
1,810
<issue_start>username_0: I am working with a json object that has nested arrays as well as names with spaces such as `Account ID`. I need to display just the `Account ID`'s in my Vue.js application. I am able to get my entire `response.data` json object but not too sure how to get just the `Account ID` when it's nested like the example below. **JSON** ``` "response": { "result": { "Accounts": { "row": [ { "no": "1", "FL": [ { "val": "ACCOUNT ID", "content": "123456789" }, ... ``` **Vue.js** ``` import axios from "axios"; export default { name: 'HelloWorld', data () { return { accounts: [], accountIDs: [] } }, mounted() { var self = this; axios.get('https://MYAPIGETREQUEST') .then( function(res){ self.accounts = res.data; self.accountIDs = //This is where I want to get the Account ID console.log('Data: ', res.data); }) .catch( function(error){ console.log('Error: ', error); }) } } ```<issue_comment>username_1: Try something like this ``` if(res.data.response.result.Accounts.row[0].FL[0].val === 'ACCOUNT ID') { self.accountIDs = res.data.response.result.Accounts.row[0].FL[0].content; ... } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: You can also try something like this: ``` let rowAccounts = response.result.Accounts.row .map(row => row.FL .filter(FL => FL.val === 'ACCOUNT ID') .map(acc => acc.content) ); self.accountIDs = [].concat.apply([], rowAccounts); ``` In `rowAccounts`, you get and array of accounts array per row like: ``` [ 0: ['acc row 1', 'another acc row1'], 1: ['acc row 2'....] ] ``` Now it all depends upon your implementation the way you like it. Upvotes: 0
2018/03/20
1,143
3,482
<issue_start>username_0: I have a directory containing a number of .cntl files - I am using a For Loop to delete all the files however I want to keep 2 of the .cntl files. This is a basic version on what I have so far ``` MY_DIR=/home/shell/ CNTL_FILE_LIST=`find ${MY_DIR}*.cntl -type f` CNTL_EXCEPTION_LIST="/home/shell/test4.cntl /home/shell/test5.cntl" ``` I am having some syntax issues with my below nested For Loop. I am trying to delete all cntl files in MY\_DIR except test4.cntl and test5.cntl ``` for file in CNTL_FILE_LIST do for exception in CNTL_EXCEPTION_LIST do if [ "${file}" != ${exception} ] rm $file fi done done ``` Can anyone see what I am doing wrong?<issue_comment>username_1: Well file4.cntl is != file5.cntl and get's therefore deleted on comparing it, file5.cntl gets deleted when compared to file4.cntl. ``` MY_DIR=/home/shell/ CNTL_FILE_LIST=`find ${MY_DIR}*.cntl -type f` CNTL_EXCEPTION_LIST="/home/shell/test4.cntl /home/shell/test5.cntl" for file in CNTL_FILE_LIST do for exception in CNTL_EXCEPTION_LIST do if [ "${file}" != ${exception} ] rm $file fi done done ``` Instead use just find: ``` find ${MY_DIR} -maxdepth 1 -type f -name "*.cntl" -not -name "file4.cntl" -not -name "file5.cntl" -delete ``` But not every find supports -delete, Gnu-find does, and you have to know, if -maxdepth 1 applies for you. Try first with -ls instead of -delete. Upvotes: 1 <issue_comment>username_2: [user unknow](https://stackoverflow.com/a/49375082/7714132) is right. So you should probably not doing this. **Instead, you can remove `$CNTL_EXCEPTION_LIST` from `$CNTL_FILE_LIST` before doing the deletion.** ``` for i in $CNTL_EXCEPTION_LIST do CNTL_FILE_LIST=${CNTL_FILE_LIST//$i/} done ``` You can reference to `man bash` for this usage, just search `Pattern substitution`. After this, $CNTL\_FILE\_LIST will NOT inclued the exceptions anymore, and now you can safely delete them by `rm $CNTL_FILE_LIST`. Upvotes: 0 <issue_comment>username_3: In practice, you should **let `find` itself do the work of excluding files, as described in the second part (using `-not`) of [the answer by username_1](https://stackoverflow.com/a/49375082/14122)**. That said, to demonstrate how one might safely use bash for this: ``` #!/usr/bin/env bash case $BASH_VERSION in ''|[1-3].*) echo "ERROR: Bash 4.0 or newer required" >&2; exit 1;; esac # Use of lowercase names here is deliberate -- POSIX specifies all-caps names for variables # ...meaningful to the operating system or shell; other names are available for application # ...use; see http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html, # fourth paragraph. my_dir=/home/shell # Using an associative array rather than a regular one allows O(1) lookup declare -A cntl_exception_list cntl_exception_list=( ["${my_dir}/test4.cntl"]=1 ["${my_dir}/test5.cntl"]=1 ) while IFS= read -r -d '' file; do [[ ${cntl_exception_list[$file]} ]] && continue rm -f -- "$file" done < <(find "$my_dir" -type f -print0) ``` --- Note: * `declare -A` creates an associative array. These can have arbitrary strings as keys; here, we can use our names to match again as such keys. * Using NUL-delimited filenames (`-print0`) ensures that even names with whitespace or literal newlines are unambiguously represented. * See [BashFAQ #1](http://mywiki.wooledge.org/BashFAQ/001) for the syntax used for the `while read` loop. Upvotes: 2
2018/03/20
1,616
5,255
<issue_start>username_0: I have this simple express code: ``` const api = Router() api.post('/some-point', async (req, res, next) => { const someStuffToSend = await Promise.resolve("hello"); res.json({ someStuffToSend }); }) ``` It works well on my dev environment, but on the prod I get the error bellow: ``` TypeError: argument entity must be string, Buffer, or fs.Stats at etag (/[...]/node_modules/etag/index.js:83:11) at generateETag ([...]/node_modules/express/lib/utils.js:280:12) at ServerResponse.send ([...]/node_modules/express/lib/response.js:200:17) at ServerResponse.json ([...]/node_modules/express/lib/response.js:267:15) at api.post (/the/code/above) ``` I checked at `node_modules/etag/index.js:83:11` and saw ``` if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { throw new TypeError('argument entity must be string, Buffer, or fs.Stats') } ``` Before this code I added a printf to check the type of entity: ``` console.log("Entity contains", entity, "is of type", typeof entity, "with constructor", entity.constructor, "and is it a buffer?", Buffer.isBuffer(entity)) ``` Which got me the output bellow: ``` Entity contains is of type object with constructor function Buffer(arg, encodingOrOffset, length) { if (!Buffer.TYPED\_ARRAY\_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } and is it a buffer? false ``` So it looks like the entity is a buffer, but not recognized as such. If I comment the test out, it crashed at a different location ``` TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer at ServerResponse.end (_http_outgoing.js:747:13) at ServerResponse.send ([...]/node_modules/express/lib/response.js:221:10) at ServerResponse.json ([...]/node_modules/express/lib/response.js:267:15) at api.post (/the/code/above) ``` If you check at `/node_modules/express/lib/response.js:221:10` you see ``` this.end(chunk, encoding); ``` where encoding is from a few lines above (l. 189, I checked with a printf) ``` chunk = Buffer.from(chunk, encoding) ``` I could hack the lib out to make that work, but I suspect some broken `node_modules` folder. However the error persists even after a `rm package-lock.json; rm -rf node_modules; npm i`. Any clue on how to solve this would be very appreciated. Below are my version numbers: * node 9.8.0 (also tried with 8.4.0), installed locally with nvm * npm 5.6.0 * express 4.16.3 * ts-node 5.0.1 * typescript 2.7.2 **Edit 1** * replace the async call by something simpler * specify express version **Edit 2** I removed the `node_modules` folder then `npm i` the packages one by one: ``` npm i aws-sdk body-parser bunyan check-types deepcopy duck-type express fast-csv glob handlebars http-auth md5 moment moment-timezone multer node-stream object-path randomstring ``` Still get the same error. **Edit 3** Add further information about the environment. **Edit 4** OK, figured out. It was a ts-node config related problem. I was launching my server with ``` ts-node --harmony_async_iteration -r tsconfig-paths/register ./src/index.ts ``` With the following lines in my `tsconfig.json`: ``` { "compilerOptions": { "module": "commonjs", "target": "es2017", "lib": [ "es2017", "esnext.asynciterable" ], "noImplicitAny": true, "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "baseUrl": ".", "pretty": true, "paths": { "*": [ "*", "src/*", "src/types/*", "node_modules/*" ] } }, "include": [ "src/**/*" ] } ``` Because of the `-r tsconfig-paths/register` in the command line, the paths specified in the `tsconfig.json` were loaded, including the `"node_modules/*"` in `paths['*']`. I'm not sure why, but it looks like this was causing the libs in `node_modules` to be loaded twice, breaking the type checks based on constructors (such as `instanceof`). **Question** I'm not sure to completely understand the reason of that. Any light?<issue_comment>username_1: I had very similar issue with `typeorm` and later with `express` too. The hint was in [this conversation](https://github.com/mysqljs/mysql/issues/2084). My solution was to get rid `*` from `paths`. Upvotes: 1 <issue_comment>username_2: I was getting this error, ``` TypeError: argument entity must be string, Buffer, or fs.Stats at etag (/[...]/node_modules/etag/index.js:83:11) at generateETag ([...]/node_modules/express/lib/utils.js:280:12) ..... ``` I was trying to run a express project, and using webpack as bundler, My error got resolved when I set target in webpack as **'node'** ``` module.exports = (env) => { return { //.... target: "node", //...., plugins: [ // new NodePolyfillPlugin() // Don't add this plugin ] } } ``` And make sure not to add `NodePolyfillPlugin` as pluging Upvotes: 0
2018/03/20
955
2,924
<issue_start>username_0: In R you can perform a condition across all rows in a column variable by using the all() or any() function. Is there an equivalent method in SAS? I want condition if ANY rows in column x are negative, this should return TRUE. Or, if ALL rows in column y are negative, this should return TRUE. For example ``` x y -1 -2 2 -4 3 -4 4 -3 ``` In R: * `all(x<0)` would give the output FALSE * `all(y<0)` would give the output TRUE I wish to replicate the same column-wise operation in SAS.<issue_comment>username_1: If you want to operate on all observations that might be easiest to do using SQL summary functions. SAS will evaluate boolean expressions as 1 for true and 0 for false. So to find out if any observation has a condition you want to test if the `MAX( condition )` is true (ie equal to 1). To find out if all observations have the condition you want to test if the `MIN( condition )` is true. ``` data have ; input x y @@; cards; -1 -2 2 -4 3 -4 4 -3 ; proc sql ; create table want as select min(x<0) as ALL_X , max(x<0) as ANY_X , min(y<0) as ALL_Y , max(y<0) as ANY_Y from have ; quit; ``` Result ``` Obs ALL_X ANY_X ALL_Y ANY_Y 1 0 1 1 1 ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: SQL is probably the most feels-like similar way to do this, but the data step is just as efficient, and lends itself a bit better to any sort of modification - and frankly, if you're trying to learn SAS, is probably the way to go simply from the point of view of learning how to do things the SAS way. ``` data want; set have end=eof; retain any_x all_x; *persist the value across rows; any_x = max(any_x, (x>0)); *(x>0) 1=true 0=false, keep the MAX (so keep any true); all_x = min(all_x, (x>0)); *(x>0) keep the MIN (so keep any false); if eof then output; *only output the final row to a dataset; *and/or; if eof then do; *here we output the any/all values to macro variables; call symputx('any_x',any_x); *these macro variables can further drive logic; call symputx('all_x',all_x); *and exist in a global scope (unless we define otherwise); end; run; ``` Upvotes: 3 <issue_comment>username_2: For completeness' sake, here is the SAS-IML solution. Of course, it's trivial as the `any` and `all` functions exist by the same name... I also include an example of using [loc](http://documentation.sas.com/?docsetId=imlug&docsetTarget=imlug_langref_sect235.htm&docsetVersion=14.3&locale=en) to identify the positive elements. ``` data have ; input x y @@; cards; 1 2 2 4 3 -4 4 -3 ; run; proc iml; use have; read all var {"x" "y"}; print x y; x_all = all(x>0); x_any = any(x>0); y_all = all(y>0); y_any = any(y>0); y_pos = y[loc(y>0)]; print x_all x_any y_all y_any; print y_pos; quit; ``` Upvotes: 3
2018/03/20
1,094
3,638
<issue_start>username_0: So, I am trying to create a visualizer for the peak volume and I found this piece of code in the website which uses CsCore. So when I tried running it, it threw the following error message: > > **System.InvalidOperationException:** 'RegisterSessionNotification has to be called from an MTA-Thread.' > > > This is the piece of code I am working with ``` public static void getVolume() { using(var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render)) { using(var sessionEnumerator = sessionManager.GetSessionEnumerator()) { foreach(var session in sessionEnumerator) { using(var audioMeterInformation = session.QueryInterface()) { Debug.WriteLine(audioMeterInformation.GetPeakValue()); } } } } } private static AudioSessionManager2 GetDefaultAudioSessionManager2(DataFlow dataFlow) { using(var enumerator = new MMDeviceEnumerator()) { using (var device = enumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia)) { Debug.WriteLine("DefaultDevice: " + device.FriendlyName); var sessionManager = AudioSessionManager2.FromMMDevice(device); return sessionManager; } } } ``` Thanks.<issue_comment>username_1: If you want to operate on all observations that might be easiest to do using SQL summary functions. SAS will evaluate boolean expressions as 1 for true and 0 for false. So to find out if any observation has a condition you want to test if the `MAX( condition )` is true (ie equal to 1). To find out if all observations have the condition you want to test if the `MIN( condition )` is true. ``` data have ; input x y @@; cards; -1 -2 2 -4 3 -4 4 -3 ; proc sql ; create table want as select min(x<0) as ALL_X , max(x<0) as ANY_X , min(y<0) as ALL_Y , max(y<0) as ANY_Y from have ; quit; ``` Result ``` Obs ALL_X ANY_X ALL_Y ANY_Y 1 0 1 1 1 ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: SQL is probably the most feels-like similar way to do this, but the data step is just as efficient, and lends itself a bit better to any sort of modification - and frankly, if you're trying to learn SAS, is probably the way to go simply from the point of view of learning how to do things the SAS way. ``` data want; set have end=eof; retain any_x all_x; *persist the value across rows; any_x = max(any_x, (x>0)); *(x>0) 1=true 0=false, keep the MAX (so keep any true); all_x = min(all_x, (x>0)); *(x>0) keep the MIN (so keep any false); if eof then output; *only output the final row to a dataset; *and/or; if eof then do; *here we output the any/all values to macro variables; call symputx('any_x',any_x); *these macro variables can further drive logic; call symputx('all_x',all_x); *and exist in a global scope (unless we define otherwise); end; run; ``` Upvotes: 3 <issue_comment>username_2: For completeness' sake, here is the SAS-IML solution. Of course, it's trivial as the `any` and `all` functions exist by the same name... I also include an example of using [loc](http://documentation.sas.com/?docsetId=imlug&docsetTarget=imlug_langref_sect235.htm&docsetVersion=14.3&locale=en) to identify the positive elements. ``` data have ; input x y @@; cards; 1 2 2 4 3 -4 4 -3 ; run; proc iml; use have; read all var {"x" "y"}; print x y; x_all = all(x>0); x_any = any(x>0); y_all = all(y>0); y_any = any(y>0); y_pos = y[loc(y>0)]; print x_all x_any y_all y_any; print y_pos; quit; ``` Upvotes: 3
2018/03/20
632
2,334
<issue_start>username_0: I am putting together a small mailing application within my application, and have run into a strange error - even just following the instructions for the advanced queries. I need to get -just- the mailboxes that are named: ``` $CoreMailboxes = TableRegistry::get('CoreMailboxes'); $query = $CoreMailboxes->find() ->where(function (QueryExpression $exp, Query $q) { return $exp->isNotNull('name'); }); $query->hydrate(false); return $query->toArray(); ``` This is a near duplicate, sans "hydrate: false", of the example in the Cake Cookbook. However, it's giving me an error of ``` Argument 1 passed to App\Model\Table\CoreMailboxesTable::App\Model\Table\{closure}() must be an instance of App\Model\Table\QueryExpression, instance of Cake\Database\Expression\QueryExpression given ``` The query in the Cookbook is this: ``` $query = $cities->find() ->where(function (QueryExpression $exp, Query $q) { return $exp->isNotNull('population'); }); ``` What am I doing wrong?<issue_comment>username_1: The problem is the instance definition's of your first argument, the [doc](https://book.cakephp.org/3.0/en/orm/query-builder.html#selecting-data) is clear: > > The passed anonymous function will receive an instance of \Cake\Database\Expression\QueryExpression as its first argument, and \Cake\ORM\Query as its second > > > Maybe you dont set the correct namespaces of this class, try this: ``` php use \Cake\Database\Expression\QueryExpression as QueryExp; //more code //more code -where(function (QueryExp $exp, Query $q) { //more code ``` Upvotes: 1 <issue_comment>username_2: You do not need to use the query expression for such a simple query.. You can just put the 'IS NOT NULL' in the where... Now to re-use the query and create a more usable finder(), expressions may be more useful ``` $result = $this->Table->find() ->where([ 'TableName.column_name IS NOT NULL' ])->toArray(); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: I've encounter today same error. Try to add ``` use Cake\ORM\Query; use Cake\Database\Expression\QueryExpression; ``` at beginning of your controller. It's help in my case. I also try username_1's answer but it doesn't work in my case Upvotes: 0
2018/03/20
522
1,933
<issue_start>username_0: I have a file hierarchy that gets files and folders from one of the users hub. All of these calls are on server side. Can these calls reside on the client side and still remain secure? None of these calls have my client secret from my Forge application. To clarify can you answer what calls can be client or server sided and still be 100% secure. Get 3 legged auth(exposes client secret) - secure or not on client side Get hubs - secure or not on client side Get projects - secure or not on client side Get files in folders - secure or not on client side Get versions of files - secure or not on client side Download files - secure or not on client side<issue_comment>username_1: The problem is the instance definition's of your first argument, the [doc](https://book.cakephp.org/3.0/en/orm/query-builder.html#selecting-data) is clear: > > The passed anonymous function will receive an instance of \Cake\Database\Expression\QueryExpression as its first argument, and \Cake\ORM\Query as its second > > > Maybe you dont set the correct namespaces of this class, try this: ``` php use \Cake\Database\Expression\QueryExpression as QueryExp; //more code //more code -where(function (QueryExp $exp, Query $q) { //more code ``` Upvotes: 1 <issue_comment>username_2: You do not need to use the query expression for such a simple query.. You can just put the 'IS NOT NULL' in the where... Now to re-use the query and create a more usable finder(), expressions may be more useful ``` $result = $this->Table->find() ->where([ 'TableName.column_name IS NOT NULL' ])->toArray(); ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: I've encounter today same error. Try to add ``` use Cake\ORM\Query; use Cake\Database\Expression\QueryExpression; ``` at beginning of your controller. It's help in my case. I also try username_1's answer but it doesn't work in my case Upvotes: 0
2018/03/20
707
2,574
<issue_start>username_0: I have a background image a and i want to right the text **align from bottom to top**.Just like the image showed as following. In my case, the background image is fixed, i cannot rotate it,so i just tried to rotate text!However, i cannot align it well! Background Image(**cannot be rotated**) [![background](https://i.stack.imgur.com/XySvu.png)](https://i.stack.imgur.com/XySvu.png) **The result i want**(just like left align,center align and rotate -90) [![enter image description here](https://i.stack.imgur.com/QAzMO.png)](https://i.stack.imgur.com/QAzMO.png) I tried this code,but not work! I think the reason is the rotation center! ``` Text { text: name; anchors.verticalCenter: parent.verticalCenter; // Centering text anchors.left: parent.left; anchors.leftMargin: 18; rotation: -90 } ``` If i rotate the background image 90 degree. Then apply my code and rotate the content(background and text) will get good result! However i cannot rotate the background image! How can i set text align from bottom to top in qml?<issue_comment>username_1: [Transform](http://doc.qt.io/qt-5/qml-qtquick-rotation.html) provides more complex transformations for the QML item. In your case, check demo in below, it shows `Text` rotate itself -90 degree. and you can adjust the rotate point by setting the `origin.x origin.y` properties. ``` Rectangle{ width: 100; height: 300 color: "lightblue" Text{ id: test text: "TestMe" transform: [ Rotation { origin.x: test.paintedWidth/2; origin.y: test.paintedWidth/2; angle: -90 }, Translate{ y: (test.parent.height - test.paintedWidth)/2 } ] } } ``` Upvotes: 0 <issue_comment>username_2: Anchoring with rotation might be at odds to manage. You can make it simple: ``` Rectangle{ color: "grey" width: 50 height: 300 Text{ //1. Place Text box symmetrically below background, edge to edge width: parent.height height: parent.width y:parent.height text: "TableA Description 15" verticalAlignment: Text.AlignVCenter // comment below 2 lines to see how it looks before rotation //2 pivot top left of text box and rotate text -90 transformOrigin: Item.TopLeft rotation: -90 } } ``` [![enter image description here](https://i.stack.imgur.com/84vnm.png)](https://i.stack.imgur.com/84vnm.png) Upvotes: 3 [selected_answer]
2018/03/20
547
2,348
<issue_start>username_0: I have a service bus trigger function that when receiving a message from the queue will do a simple db call, and then send out emails/sms. Can I run > 1000 calls in my service bus queue to trigger a function to run simultaneously without the run time being affected? My concern is that I queue up 1000+ messages to trigger my function all at the same time, say 5:00PM to send out emails/sms. If they end up running later because there is so many running threads the users receiving the emails/sms don't get them until 1 hour after the designated time! Is this a concern and if so is there a remedy? FYI - I know I can make the function run asynchronously, would that make any difference in this scenario?<issue_comment>username_1: I'm assuming you are talking about an Azure Service Bus Binding to an Azure Function. There should be no issue with >1000 Azure Functions firing at the same time. They are a Serverless runtime and should be able to scale greatly if you are running under a consumption model. If you are running the functions in a service plan, you may be limited by the service plan. In your scenario you are probably more likely to overwhelm the downstream dependencies: the database and SMS sending system, before you overwhelm the Azure Functions infrastructure. The best thing to do is to do some load testing, and monitor the exceptions coming out of the connections to the database and SMS systems. Upvotes: 0 <issue_comment>username_2: 1000 messages is not a big number. If your e-mail/sms service can handle them fast, the whole batch will be gone relatively quickly. Few things to know though: * Functions won't scale to 1000 parallel executions in this case. They will start with 1 instance doing ~16 parallel calls at the same time, and then observe how fast the processing goes, then maybe add a second instance, wait again etc. * The exact scaling behavior is not publicly described and can change over time. Thus, YMMV, and you need to test against your specific scenario. * Yes, make the functions async whenever you can. I don't expect a huge boost in processing speed just because of that, but it certainly won't hurt. Bottom line: your scenario doesn't sound like a problem for Functions, but if you need very short latency, you'll have to run a test before relying on it. Upvotes: 1
2018/03/20
510
1,837
<issue_start>username_0: So I'm trying to sort this Arraylist of "Movies" type, alphabetically based on the actor's name and containing no duplicates, which means using a treeSet. So I have implemented the "comparable" interface and then didn't know what to do after for making the list sorted by alphabets ``` public int compareTo(Movie m){ for(Movie movileTitle: moviesList){ return movileTitle.getActor().compareTo(m.getActor()); } return 0; } //this is where I'm trying add the arrayList of the movies and sort them using a treeSet public TreeSet movieListByOrder(){ TreeSet movieTemp = new TreeSet<>(); //Note, "allMoviesList" is the the list that contains all movies(duplicates) that I'm trying to add to the treeSet, so that it gets rid of duplicates and that is also ordered. movieTemp.addAll(allMoviesList); System.out.println(movieTemp); return movieTemp; } ```<issue_comment>username_1: Continuing in the direction in which you are already headed, you may try using an inline comparator when creating your `TreeSet`: ``` Set treeSet = new TreeSet(new Comparator() { @Override public int compare(Movie m1, Movie m2) { if (m1 == null) { if (m2 != null) return -1; else return 0; } else if (m2 == null) { return 1; } else { return m1.getActor().compareTo(m2.getActor()); } } }); ``` A `TreeSet` is a sorted collection, meaning it will maintain the sort order imposed by the above comparator. So if you want to print out the contents of the set in order, you need only iterate through it. Upvotes: 1 <issue_comment>username_2: All that looks archaic, sorry. Try to look into this code and decide if it's more interesting. ``` movies.stream() .sorted(comparing(Movie::getActor)) .distinct() .collect(toList()); ``` PS: play with performance tuning for extra credit Upvotes: 0
2018/03/20
1,186
5,171
<issue_start>username_0: I am making a game where the player first has to choose the type of control to use before playing. The three options being: Keyboard, Controller, Touch The player must click the button corresponding to his choice. Each button runs this script when clicked on: ``` public class KeyboardButton : MonoBehaviour { public static int controller; public void buttonClick () { controller = 1; } } ``` In reality, each button as its own script, where the value of controller is different depending on the script ran. The idea is that the value of this integer would be sent over to the script responsible of controlling the player so it will make use of the demanded input type. ie: if the keyboard button is selected, it will run the corresponding script, setting the integer value to 1. After the PlayerController script receives this value, it will know to only accept input from the keyboard. I have consulted a lot of documentation, but a lot of it contains context-specific C# things that I don't understand and are irrelevant to what I want to do. Also, I would not like an answer around the lines of: "You don't have to make the player choose a control type, here's how you can make your game accept all types of control at once." I already know all this stuff and there is a reason I want the player to make a choice. Furthermore, I would still like to know a way to transfer integers to be able to be more organized, rather than having a single script that does 90% of the things in the game.<issue_comment>username_1: There are three way you can pass value to another script. **GetComponent** You can use `GetComponent` method to get another script. ``` public class KeyboardButton : MonoBehaviour { public int controller; //this is anotherScript instance public AnotherScript anotherScript; Start() { anotherScript = GameObject.Find("Name of Object").GetComponent(); } public void buttonClick () { controller = 1; anotherScript.sendValue(controller); //send your value to another script } } ``` **Singleton** Let AnotherScript be a static *Singleton*,You can get the instance on other side. ``` public class AnotherScript : MonoBehaviour { //need to be static public static AnotherScript Current; Start() { if(Current == null) { Current = new AnotherScript(); } } public void sendValue(int val) { //todo } } public class KeyboardButton : MonoBehaviour { public int controller; public void buttonClick () { controller = 1; AnotherScript.Current.sendValue(controller);//send your value to another script } } ``` **SendMessage** If you want to send a value to otherscript,`SendMessage` is a simple way you can choose. ps:`SendMessage` method can just send a parameter. ``` public class KeyboardButton : MonoBehaviour { public void buttonClick () { controller = 1; GameObject.Find("name of object").SendMessage("sendValue",controller); } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: As pointed out in one of the comments, you already exposed that value, you can refer to is via ``` Debug.Log(KeyboardButton.controller); ``` without providing an instance. There's multiple other ways of doing it, as this way is only good to a certain level of complexity, after which it starts to get more muddy, but depending on what you need right know it might get you through. It is one of the valid ways, and probably the simplest one. You may also want to know when the value has changed, for example you could use UntiyEvent and trigger it when value is changed ``` public class KeyboardButton : MonoBehaviour { public UnityEvent OnValueChanged; public static int controller; public void buttonClick () { controller = 1; OnValueChanged.Invoke(); } } ``` this is if you like to wire events in the editor. You could also do: ``` public class KeyboardButton : MonoBehaviour { public static UnityEvent OnValueChanged; public static int controller; public void buttonClick () { controller = 1; OnValueChanged.Invoke(); } } ``` the downside is that the event won't show up in the editor,but the upside is that you can set up a trigger without having to have a reference to the KeyboardButton instance that just got clicked. ``` public class ControllerChangeReactor : MonoBehaviour { void Start() { KeyboardButton.OnValueChanged.AddListener(React); // add event listener } void React() // will get called when keyboard is clicked { Debug.Log(KeyboardButton.controller); } } ``` This approach can become limiting after you've written a dozen or so of those scripts, but a step up involves tailoring a custom system which is probably not worth it on your level (just yet). You can finish a simple game using the above approach, even if its not the most elegant. You could also parametrize your script (expose 'WHAT DOES IT CHANGE' in editor), to avoid unnecessary multiplication of code Upvotes: 0
2018/03/20
1,037
2,774
<issue_start>username_0: I have a data frame of participant questionnaire responses in wide format, with each column representing a particular question/item. The data frame looks something like this: ``` id <- c(1, 2, 3, 4) Q1 <- c(NA, NA, NA, NA) Q2 <- c(1, "", 4, 5) Q3 <- c(NA, 2, 3, 4) Q4 <- c("", "", 2, 2) Q5 <- c("", "", "", "") df <- data.frame(id, Q1, Q2, Q3, Q4, Q5) ``` I want R to remove columns that has all values in each of its rows that are either (1) NA or (2) blanks. Therefore, I do not want column Q1 (which comprises entirely of NAs) and column Q5 (which comprises entirely of blanks in the form of ""). According to this [thread](https://stackoverflow.com/questions/2643939/remove-columns-from-dataframe-where-all-values-are-na), I am able to use the following to remove columns that comprise entirely of NAs: ``` df[, !apply(is.na(df), 2, all] ``` However, that solution does not address blanks (""). As I am doing all of this in a dplyr pipe, could someone also explain how I could incorporate the above code into a dplyr pipe? At this moment, my dplyr pipe looks like the following: ``` df <- df %>% select(relevant columns that I need) ``` After which, I'm stuck here and am using the brackets [] to subset the non-NA columns. Thanks! Much appreciated.<issue_comment>username_1: You can use `select_if` to do this. Method: ``` col_selector <- function(x) { return(!(all(is.na(x)) | all(x == ""))) } df %>% select_if(col_selector) ``` Output: ``` id Q2 Q3 Q4 1 1 1 NA 2 2 2 3 3 4 3 2 4 4 5 4 2 ``` Upvotes: 3 <issue_comment>username_2: We can use a version of `select_if` ``` library(dplyr) df %>% select_if(function(x) !(all(is.na(x)) | all(x==""))) # id Q2 Q3 Q4 #1 1 1 NA #2 2 2 #3 3 4 3 2 #4 4 5 4 2 ``` Or without using an anonymous function call ``` df %>% select_if(~!(all(is.na(.)) | all(. == ""))) ``` --- You can also modify your `apply` statement as ``` df[!apply(df, 2, function(x) all(is.na(x)) | all(x==""))] ``` Or using `colSums` ``` df[colSums(is.na(df) | df == "") != nrow(df)] ``` and inverse ``` df[colSums(!(is.na(df) | df == "")) > 0] ``` Upvotes: 6 [selected_answer]<issue_comment>username_3: With `dplyr` version 1.0, you can use the helper function `where()` inside `select` instead of needing to use `select_if`. ``` library(tidyverse) df <- data.frame(id = c(1, 2, 3, 4), Q1 = c(1, "", 4, 5), Q2 = c(NA, NA, NA, NA), Q3 = c(NA, 2, 3, 4), Q4 = c("", "", 2, 2), Q5 = c("", "", "", "")) df %>% select(where(~ !(all(is.na(.)) | all(. == "")))) #> id Q1 Q3 Q4 #> 1 1 1 NA #> 2 2 2 #> 3 3 4 3 2 #> 4 4 5 4 2 ``` Upvotes: 4
2018/03/20
784
2,811
<issue_start>username_0: I have two dropdown menus. The first is to choose your location. The second is to choose what type of pictures you want to upload. (i.e. Option 1 - Akron, Option 2 - Skyline). I've setup a file request (DropBox generated upload link) in my DropBox account for these options (Akron, Skyline). If they choose (Akron, Houses), it'd be a different upload link. Similarly, (Cleveland, Streets) would be yet another upload link. Using JQuery, I have the link sent to my submit button HTML. Everything I've tried sends to that link no matter what options I choose. (i.e. everything goes to (Akron, Skyline) link even if I choose (Akron, Houses). There is something wrong in my if statement and I can't figure it out. Here is a sample of my code. The if statement is for the (Akron, Skyline) combination. Additional code will be written for other options once I get this one to work. I've replaced the upload link with a generic URL. ```html Choose Your Location Choose Location Akron Alliance Ashland Barberton Bellaire What Pictures or Videos are You Uploading? Choose Type Skyline Streets Houses [if("#Location Select").val("Akron") && ("#Type Select").val("Skyline"){ $("a").attr("href",'https://www.google.com'); }](URL) ```<issue_comment>username_1: This this code. It was missing `$` as well as brackets. ```js if($("#Location Select").val("Akron") && $("#Type Select").val("Skyline")){ $("a").attr("href",'https://www.google.com'); } ``` ```html Choose Your Location Choose Location Akron Alliance Ashland Barberton Bellaire What Pictures or Videos are You Uploading? Choose Type Skyline Streets Houses ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: Note <http://api.jquery.com/val/> .val() does not accept any arguments. Also note that you first have to identify the selected element, and then get its value. HTML IDs should not have spaces, and there should only be one ID of a particular string in any given document. If you want to describe a *type* of element, use `class` instead. For example: ``` Choose Your Location Choose Location Akron Alliance Ashland Barberton Bellaire What Pictures or Videos are You Uploading? Choose Type Skyline Streets Houses [$('input').click((e) => { e.preventDefault(); const location = $('#Location')[0]; const type = $('#Type')[0]; const locationVal = location.options[location.selectedIndex].value; const typeVal = type.options[type.selectedIndex].value; if (locationVal === 'Akron' && typeVal === 'Skyline') { console.log('Akron/Skyline'); } else { console.log(`Other, ${locationVal} ${typeVal}`); } });](URL) ``` (you don't actually need the `class="Select"` here at all, based on the code so far) Upvotes: 1
2018/03/20
864
3,024
<issue_start>username_0: Query: ``` where (table1.subject_1 like '%TEST1%' OR table1.subject_1 like '%TEST2%' OR table1.subject_1 like '%TEST3%' OR table1.subject_1 like '%TEST4%' ) OR (table1.subject_2 like '%TEST1%' OR table1.subject_2 like '%TEST2%' OR table1.subject_2 like '%TEST3%' OR table1.subject_2 like '%TEST4%' ) ``` Here `if subject_1 = TEST1` then no need to search for the remaining conditions, if not found then search for the other conditions. I need a record having either of `subject_1` from the above query. `If subject_1` does not match with any of the results then search for `subject_2`. **My problem:** from the above query, multiple records are being returned where `subject_1` matches `TEST1` and `TEST2` both. Example: ``` no, name, add1, occ, date, subject_1,subject_2,Exclusion_number ----------------------------------------------------------------------------- 446 REBECCA street1 Y 1/1/2001 TEST1 AB 10 446 REBECCA street1 Y 1/1/2001 TEST2 A 11 ``` I should be able to fetch one row as `subject_1 like '%TEST1%'` match found. I should not get the second row, as the first condition satisfied already. Currently with my query, I am getting 2 rows, where the requirement is to get only one row. In case first condition fails then I should check the second condition subject\_2 like '%TEST2%'.<issue_comment>username_1: This this code. It was missing `$` as well as brackets. ```js if($("#Location Select").val("Akron") && $("#Type Select").val("Skyline")){ $("a").attr("href",'https://www.google.com'); } ``` ```html Choose Your Location Choose Location Akron Alliance Ashland Barberton Bellaire What Pictures or Videos are You Uploading? Choose Type Skyline Streets Houses ``` Upvotes: 1 [selected_answer]<issue_comment>username_2: Note <http://api.jquery.com/val/> .val() does not accept any arguments. Also note that you first have to identify the selected element, and then get its value. HTML IDs should not have spaces, and there should only be one ID of a particular string in any given document. If you want to describe a *type* of element, use `class` instead. For example: ``` Choose Your Location Choose Location Akron Alliance Ashland Barberton Bellaire What Pictures or Videos are You Uploading? Choose Type Skyline Streets Houses [$('input').click((e) => { e.preventDefault(); const location = $('#Location')[0]; const type = $('#Type')[0]; const locationVal = location.options[location.selectedIndex].value; const typeVal = type.options[type.selectedIndex].value; if (locationVal === 'Akron' && typeVal === 'Skyline') { console.log('Akron/Skyline'); } else { console.log(`Other, ${locationVal} ${typeVal}`); } });](URL) ``` (you don't actually need the `class="Select"` here at all, based on the code so far) Upvotes: 1
2018/03/20
733
2,369
<issue_start>username_0: I am trying to remove entries from an `unordered_map`. A `vector` holds the keys that need to be removed from the `unordered_map`. I am trying to use `for_each` to iterate through the vector and call `erase` on the `unordered_map`. ``` #include #include #include int main() { std::unordered\_map sample\_map = { {0, false}, {1, true}, {2,false}}; std::vector keys\_to\_delete = { 0, 2}; std::for\_each(keys\_to\_delete.begin(), keys\_to\_delete.end(), &sample\_map.erase); } ``` I receive the error: ``` note: couldn't deduce template parameter '_Funct' std::for_each(keys_to_delete.begin(), keys_to_delete.end(), &sample_map.erase); ``` How do I correctly bind `sample_map`'s erase function?<issue_comment>username_1: `std::for_each` is not quite suitable there. The code would be cleaner with `for`. ``` #include #include #include int main() { std::unordered\_map sample\_map = { {0, false}, {1, true}, {2,false}}; std::vector keys\_to\_delete = { 0, 2}; for (auto key : keys\_to\_delete) sample\_map.erase(key); } ``` With using `for_each` the code will be heavy for understanding. `std::unordered_map::erase` has overloads, thus it can not be used directly, you would have to create a functional object that calls suitable overloaded method, or use lambda. Upvotes: 2 <issue_comment>username_2: The way to do what you want is to use a lambda like so: ``` std::for_each(keys_to_delete.begin(), keys_to_delete.end(), [&](const auto& key) { sample_map.erase(key); }); ``` Upvotes: 2 <issue_comment>username_3: You're missing a template argument for the vector key\_to\_delete. Anyways, this problem might be simpler if you manually wrote the code that looped through each key and called the function erase. However, if you'd like to use std::for\_each then you could bind it to the correct function to be called. In this case, one has to `static_cast` to get the correct function since erase has multiple overloads. ``` #include #include #include #include #include int main() { std::unordered\_map sample\_map = { { 0, false },{ 1, true },{ 2,false } }; std::vector keys\_to\_delete = { 0, 2 }; using type = std::unordered\_map; std::for\_each(keys\_to\_delete.begin(), keys\_to\_delete.end(), std::bind(static\_cast(&type::erase), &sample\_map, std::placeholders::\_1)); } ``` Upvotes: 3 [selected_answer]
2018/03/20
960
3,448
<issue_start>username_0: I am working on angularjs and bootstrap application. I'm trying to validate the simple form, when user click on submit button all the fields in the from should have a value. Please find the demo : <https://plnkr.co/edit/aHtODbTTFZfpIRO3BWhf?p=preview> In the demo above, when user click on submit button with out selecting the checkbox , an error message is shown 'Please Select the Color..' , after the error message is shown select the checkbox and click on submit button still the error message is displayed. Any inputs on this? html code: ``` Select Color : {{color}} Username : The Username is required Submit ```<issue_comment>username_1: Solution is to update your (1) input field for colors, (2) input field for user and (3) submitForm method ``` $scope.submitForm = function(form){ if ($scope.selectedColor.length > 0 && $scope.user != "") { console.log('fields are all entered'); } else{ } } ``` (1) You need to set the false condition to handle the checkbox when it is selected. (2) For your user input field, you need to set ng-model=user to link the $scope.user object to the input. (3) For the submitForm method, you want to know that the selectedColor array has at least one item, and that user is not empty. As an ending point, please format your code using proper linting and indentation. Otherwise, it is difficult to read at first glance. Upvotes: 1 [selected_answer]<issue_comment>username_2: **First** I have declared an array for all of the checkbox value: ``` $scope.selectedColor = [false,false,false]; ``` **Second** I added a method for check box validation check: ``` $scope.someSelected = function () { for(var i = 0; i < $scope.selectedColor.length; i++) { if($scope.selectedColor[i]) return true; } return false; }; ``` **Third** I use `ng-model` and update the HTML code, ng-model is used for two-way data binding, and change to bind value will reflected in view and controller: ``` ``` **Forth** The user input box also do not have the `ng-model` so the change in view not be updated in controller. To solve this `ng-model` is added. ``` ``` **Fifth** Updated the submit form validation: ``` $scope.submitForm = function(){ if ($scope.someSelected() && $scope.user != "" && $scope.user != undefined) { alert("all fields are entered"); }else{ } } ``` Thats all! Please check the working code snippet: ```html Example - example-checkbox-input-directive-production angular.module('checkboxExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.colorNames = ['RED', 'BLUE', 'BLACK']; $scope.selectedColor = [false,false,false]; $scope.userSelection = function userSelection(team) { var idx = $scope.selectedColor.indexOf(team); if (idx > -1) { $scope.selectedColor.splice(idx, 1); } else { $scope.selectedColor.push(team); } }; $scope.submitForm = function(){ if ($scope.someSelected() && $scope.user != "" && $scope.user != undefined) { alert("all fields are entered"); }else{ } } $scope.someSelected = function () { for(var i = 0; i < $scope.selectedColor.length; i++) { if($scope.selectedColor[i]) return true; } return false; }; }]); Select Color : {{color}} Username : The Username is required Submit ``` Upvotes: 1
2018/03/20
554
2,046
<issue_start>username_0: I have a bootstrap modal where I want to call functions when it is shown or hidden. Is it possible? I tried with focus/blur. Those work but those get triggered multiple times depending on where you click. Are there other events I could call just once each when the modal is shown or hidden? ``` Open Modal Other content in here ```<issue_comment>username_1: If you use ngx-bootstrap, you can define and use show/hide modal functions in .ts .ts ``` import {Component, ViewChild} from '@angular/core'; import {ModalDirective} from 'ngx-bootstrap'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { @ViewChild('childModalTest') public childModalTest:ModalDirective; public showChildModalOpen():void { this.childModalTest.show(); } public showChildModalClose():void { this.childModalTest.hide(); } } ``` .html ``` show hide ``` And <https://valor-software.com/ngx-bootstrap/#/modals> would be helpful :) Upvotes: 2 <issue_comment>username_2: I would definitely suggest that you migrate to ng-bootstrap and use those modals which are more intuitive. [ngbootstrap modal tutorial](https://ng-bootstrap.github.io/#/components/modal/examples) But, to do it without I would suggest using a Subject to emit and listen for the open close events. Here is a good video on how to use rxjs Subjects [rxjs Subjects tutorial](https://www.youtube.com/watch?v=-mwNLRbfKmU) After setting up the Subject, revise your functions, modalShown() and modalHidden(), to include a subject "next" event before firing the modal open/close. ``` import { Subject } from 'rxjs/Subject'; modalOpen(){ this._mySubject.next("open"); yourBootstrapModal.open(); } ``` Then subscribe the the event and perform your work ``` this.mySubject.subscribe(message=>{ if(message === "open") { doWork.... } } ``` Above code is handwritten but will get you where you need to go. Good luck! Upvotes: 1
2018/03/20
879
2,926
<issue_start>username_0: I am having some issues setting up django-crontab in my django project. I have followed the instructions given on the official documentation :- <https://pypi.python.org/pypi/django-crontab> I have defined my cron.py under an app named ciscoaci. So its location is project/ciscoaci(which is the app)/cron.py. Inside cron.py, is a function named sshpostGetMACIP\_scheduler(). I have defined 'django\_crontab' under my settings.py in INSTALLED\_APPS. ``` CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/1 * * * *', 'ciscoaci.cron.sshpostGetMACIP_scheduler', '>> /axphome/xxx/netadc/ciscoaci/tmp/scheduled_job.log'), ] ``` Nothing shows up in my logs. I have also tried changing /axphome/xxx/netadc/ciscoaci/tmp/scheduled\_job.log to ciscoaci/tmp/scheduled\_job.log and it doesn't work. Also when I do crontab -l, the cron shows up. ``` */1 * * * * /root/.venvs/netadc/bin/python /home/xxx/netadc/manage.py crontab run 4a2a96ea204eb26917961a9946493f0d >> /axphome/xxxx/netadc/ciscoaci/tmp/scheduled_job.log 2>&1 # django-cronjobs for netadc ``` But nothing shows up in my logs. Any help would be appreciated. I do not want to use celery at this point as this is used for a temporary feature in my project.<issue_comment>username_1: If you use ngx-bootstrap, you can define and use show/hide modal functions in .ts .ts ``` import {Component, ViewChild} from '@angular/core'; import {ModalDirective} from 'ngx-bootstrap'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { @ViewChild('childModalTest') public childModalTest:ModalDirective; public showChildModalOpen():void { this.childModalTest.show(); } public showChildModalClose():void { this.childModalTest.hide(); } } ``` .html ``` show hide ``` And <https://valor-software.com/ngx-bootstrap/#/modals> would be helpful :) Upvotes: 2 <issue_comment>username_2: I would definitely suggest that you migrate to ng-bootstrap and use those modals which are more intuitive. [ngbootstrap modal tutorial](https://ng-bootstrap.github.io/#/components/modal/examples) But, to do it without I would suggest using a Subject to emit and listen for the open close events. Here is a good video on how to use rxjs Subjects [rxjs Subjects tutorial](https://www.youtube.com/watch?v=-mwNLRbfKmU) After setting up the Subject, revise your functions, modalShown() and modalHidden(), to include a subject "next" event before firing the modal open/close. ``` import { Subject } from 'rxjs/Subject'; modalOpen(){ this._mySubject.next("open"); yourBootstrapModal.open(); } ``` Then subscribe the the event and perform your work ``` this.mySubject.subscribe(message=>{ if(message === "open") { doWork.... } } ``` Above code is handwritten but will get you where you need to go. Good luck! Upvotes: 1
2018/03/20
901
2,568
<issue_start>username_0: file1 ``` :once:echo Hello # this is a comment :once:echo 1 :once:echo 2 :once:echo 3 :once:echo 4 ``` Consider the file above, If I wanted to print out each line one by one how would I remove the "# this is a comment" and ':once:' ``` #include #include #include int main(int argc, char \*\*argv) { FILE \*file = fopen(argv[1], "r"); char buf[100]; char p; while (fgets(buf, sizeof(buf), file)) { if ((p = strchr(buf, '#'))) \*p = '\0'; printf("%s\n", buf); } fclose(file); } ``` I think I can use strchr to remove the comments but unsure how to go about this. I want the output to be this ``` $ gcc -Wall a.c $ ./a.out file1 echo Hello echo 1 echo 2 echo 3 echo 4 ``` Current output: ``` :once:echo Hello # This is a comment :once:echo 1 :once:echo 2 :once:echo 3 :once:echo 4 ``` Unsure why the extra space is there. I think I have the right approach with the strchr just unsure how to use.<issue_comment>username_1: You should change `char p;` to `char *p;`, otherwise this is not going to work at all. If you're looking for `:once:` only at the start of a line, you can use `strncmp()` to check the first six characters, and offset the start of the string if necessary. Also, since `fgets()` retains line break characters, you may as well add `\n` and `\0` when you encounter a `#` symbol, and then leave out the `\n` when printing each line. That way your output won't be filled with double line breaks. ``` #include #include #include int main(int argc, char \*\*argv) { FILE \*file = fopen(argv[1], "r"); char buf[100]; char \*p; while (fgets(buf, sizeof(buf), file)) { if ((p = strchr(buf, '#'))) { \*(p++) = '\n'; \*p = '\0'; } printf("%s", buf + (strncmp(buf, ":once:", 6) == 0 ? 6 : 0)); } fclose(file); } ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: This should work for you. I added a nested `for` inside of the `while`, to loop through `buf` and check for the **'#'** hash character. You should always be sure to check if the necessary file exists or not, instead of assuming that it does. ``` #include #include #include int main(int argc, char \*\*argv) { FILE \*file; if (!(file = fopen(argv[1], "r"))) { fprintf(stderr, "The specified file does not exist\n"); return 1; } char buf[100]; int x; while (fgets(buf, sizeof(buf), file)) { for (x = 0; x < sizeof(buf); x++) { if (buf[x] == '#') buf[x] = '\0'; } if (strncmp(buf, ":once:", 6) == 0) printf("%s\n", buf + 6); else printf("%s\n", buf); } fclose(file); return 0; } ``` Upvotes: 0
2018/03/20
611
1,990
<issue_start>username_0: I'm trying to monkey-patch the class "Tumble" with the module "Tinder". But when I add methods to the class, they aren't inherited. Constants, however, are. lib/tumble.rb: ``` class Tumble ... ``` lib/tumble/tinder.rb ``` module Tinder APP_ID = 1234567890 # Without self def xyz puts 'bar' end ``` config/initializers/tumble.rb ``` Tumble.include Tinder ``` The app loads Tumble and Tinder and I can access APP\_ID: ``` $ rails r 'puts Tumble::APP_ID' 1234567890 ``` But Tumble didn't inherit the methods: ``` [~/tinder]$ rails r 'puts Tumble.foo' Please specify a valid ruby command or the path of a script to run. Run 'bin/rails runner -h' for help. undefined method `foo' for Tumble:Class [~/tinder]$ rails r 'puts Tumble.xyz' Please specify a valid ruby command or the path of a script to run. Run 'bin/rails runner -h' for help. undefined method `xyz' for Tumble:Class ``` How do I patch Tumble to include these methods from Tinder? Thanks :)<issue_comment>username_1: When you call `Tumble.foo` that's calling `foo` as if it were a class method. Yet when you do `Tumble.include Tinder` that adds the module's instance methods *as instance methods of Tumble*. So, your current code should work if you do `Tumble.new.foo`. You can also make `Tumble.foo` work with `Tumble.extend Tinder`. Upvotes: 2 <issue_comment>username_2: ``` class Tinder def initialize # some code here end end ``` Imagine that this above was the class that you wanted to monkey-patch. To monkey-patch it you only need to write (on any place that gets loaded) the class Tinder again with the code to be added like this: ``` class Tinder def some_more_code # does great stuff end end ``` This is monkey-patch. Modules won't do monkey-patch. They extend functionality but in a different way. Just be aware not to override any methods of the original class that you want to monkey-patch, unless, of course, if that is your goal. Upvotes: 0
2018/03/20
994
2,788
<issue_start>username_0: I am writing a program that returns every rth element from a list. The list can be any type. I want to report an error when r is zero but my code isn't working (it is working fine when I comment out the error line). Can anyone tell me how to report an error in this situation ``` rthElem :: Int -> [a] -> [a] rthElem _ [] = [] rthElem 0 (x:xs) = "Error" rthElem n (x:xs) = rthElem' n 1 (x:xs) where rthElem' n i (x:xs) = (if (n `divides` i) then [x] else []) ++ (rthElem' n (i+1) xs) rthElem' _ _ [] = [] divides x y = y `mod` x == 0 ```<issue_comment>username_1: You could use `Maybe` or `Either` in this case. This is how `Maybe` looks. `Nothing` will be our "error". ``` rthElem :: Int -> [a] -> Maybe [a] rthElem _ [] = Just [] rthElem 0 (x:xs) = Nothing rthElem n (x:xs) = Just (rthElem' n 1 (x:xs)) where rthElem' n i (x:xs) = (if (n `divides` i) then [x] else []) ++ (rthElem' n (i+1) xs) rthElem' _ _ [] = [] divides x y = y `mod` x == 0 main :: IO () main = case (rthElem 0 [1..5]) of Nothing -> putStrLn "Error" Just elm -> print elm ``` Another way is using `Either`. `Either` will return `Left` or `Right`. `Left` will be our "error". ``` rthElem :: Int -> [a] -> Either String [a] rthElem _ [] = Right [] rthElem 0 (x:xs) = Left "Error" rthElem n (x:xs) = Right (rthElem' n 1 (x:xs)) where rthElem' n i (x:xs) = (if (n `divides` i) then [x] else []) ++ (rthElem' n (i+1) xs) rthElem' _ _ [] = [] divides x y = y `mod` x == 0 main :: IO () main = case (rthElem 0 [1..5]) of Left err -> putStrLn err Right elm -> print elm ``` The best way is using `Either`. Read more about error handling [here](https://www.schoolofhaskell.com/school/starting-with-haskell/basics-of-haskell/10_Error_Handling). Upvotes: 3 <issue_comment>username_2: If you really want to print an error and show it you could use the error function, `error :: String -> a` ``` rthElem 0 (x:xs) = error "Error msg here" ``` But there is a plenty better ways to do this , and you should figure out which one fits in your case , you can use Maybe, Either even monads , here is an interesting link with examples <http://www.randomhacks.net/2007/03/10/haskell-8-ways-to-report-errors/> Upvotes: 2 <issue_comment>username_3: You could use exceptions but you'd also have to transform your function into an IO action. ``` rthElem :: Int -> [a] -> IO [a] rthElem _ [] = return [] rthElem 0 _ = ioError $ userError "Error" rthElem n l = return $ rthElem' n 1 l where rthElem' n i (x:xs) = (if (n `divides` i) then [x] else []) ++ (rthElem' n (i+1) xs) rthElem' _ _ [] = [] divides x y = y `mod` x == 0 ``` Upvotes: 0
2018/03/20
1,336
4,113
<issue_start>username_0: I'm trying to display a GridView of images to allow a user to pick from within a Dialog Box and I'm having rendering issues. My UI fades as if a view was appearing on top of it, but nothing displays. Here is my code... ``` Future \_neverSatisfied() async { return showDialog( context: context, barrierDismissible: false, // user must tap button! child: new AlertDialog( title: new Text( 'SAVED !!!', style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.black), ), content: new GridView.count( crossAxisCount: 4, childAspectRatio: 1.0, padding: const EdgeInsets.all(4.0), mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, children: [ 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', ].map((String url) { return new GridTile( child: new Image.network(url, fit: BoxFit.cover, width: 12.0, height: 12.0,)); }).toList()), actions: [ new IconButton( splashColor: Colors.green, icon: new Icon( Icons.done, color: Colors.blue, ), onPressed: () { Navigator.of(context).pop(); }) ], ), ); } ```<issue_comment>username_1: I think you have to use scrolling widget in content, so that it can handle overflown widget. <https://docs.flutter.io/flutter/material/AlertDialog-class.html> If the content is too large to fit on the screen vertically, the dialog will display the title and the actions and let the content overflow. Consider using a scrolling widget, such as ListView, for content to avoid overflow. Upvotes: 0 <issue_comment>username_2: The issue is that, the `AlertDailog` tries to get the intrinsic width of the child. But `GridView` being lazy does not provide intrinsic properties. Just try wrapping the `GridView` in a `Container` with some `width`. Example: ``` Future \_neverSatisfied() async { return showDialog( context: context, barrierDismissible: false, // user must tap button! child: new AlertDialog( contentPadding: const EdgeInsets.all(10.0), title: new Text( 'SAVED !!!', style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.black), ), content: new Container( // Specify some width width: MediaQuery.of(context).size.width \* .7, child: new GridView.count( crossAxisCount: 4, childAspectRatio: 1.0, padding: const EdgeInsets.all(4.0), mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, children: [ 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', 'http://www.for-example.org/img/main/forexamplelogo.png', ].map((String url) { return new GridTile( child: new Image.network(url, fit: BoxFit.cover, width: 12.0, height: 12.0,)); }).toList()), ), actions: [ new IconButton( splashColor: Colors.green, icon: new Icon( Icons.done, color: Colors.blue, ), onPressed: () { Navigator.of(context).pop(); }) ], ), ); } ``` You can read more about how intrinsic properties are calculated for different views [here](https://docs.flutter.io/flutter/rendering/RenderViewportBase/computeMinIntrinsicWidth.html). Hope that helps! Upvotes: 5 [selected_answer]
2018/03/20
373
1,397
<issue_start>username_0: Sometimes I want to contrast two separate pieces of code in a Stackoverflow post without putting spaces between them. However, Stackoverflow places consecutive code blocks all in the same block, regardless of spaces between them. ``` // first code block // second code block ``` I want them to appear in separate code blocks, somewhat like this. ``` // first code block ``` `// second code block` You'll notice that My first block is indented, whereas the second is surrounded by back tics, which is not ideal, as the second block won't be highlighted by Stackoverflow. ``` // first code block `// second code block` ``` How can I make both blocks appear as separate formatted code blocks using only indentation?<issue_comment>username_1: I just solved it, thanks to a comment (which has since been deleted). To force separate code blocks, place a tag between the code blocks. ``` // first code block ``` ``` // second code block ``` as produced with this formatting. ``` // first code block // second code block ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You could use this invisible char: `⁣⁣` (<http://www.fileformat.info/info/unicode/char/2063/index.htm>) Example: ``` sdf ``` ⁣ ``` sdf ``` EDIT: The solution with makes more sense (also looks better, as the invisible char version's gap is a bit big) Upvotes: 0
2018/03/20
2,306
7,280
<issue_start>username_0: I'm trying to begin developing a skill for alexa using flask-ask and ngrok in python. Following is my code: ``` from flask import Flask from flask_ask import Ask, statement, question, session import json import requests import time import unidecode app = Flask(__name__) ask = Ask(app, "/reddit_reader") def get_headlines(): titles = 'is this working' return titles @app.route('/') def homepage(): return "hi there, how ya doin?" @ask.launch def start_skill(): welcome_message = 'Hello there, would you like the news?' return question(welcome_message) @ask.intent("YesIntent") def share_headlines(): headlines = get_headlines() headline_msg = 'The current world news headlines are {}'.format(headlines) return statement(headline_msg) @ask.intent("NoIntent") def no_intent(): bye_text = 'I am not sure why you asked me to run then, but okay... bye' return statement(bye_text) if __name__ == '__main__': app.run(debug=True) ``` The code runs fine on my machine and returns the correct output if I print it out. But the skill gives a HTTP 500 internal error when I deploy it on amazon using ngrok. I get the same 500 internal error both in the text as well as json simulator in the development console. This is my intent schema: ``` { "intents": [ { "intent": "YesIntent" }, { "intent": "NoIntent" } ] } ``` I get the following error in my python prompt: `AttributeError: module 'lib' has no attribute 'X509V3_EXT_get` The stacktrace is as follows: ``` Traceback (most recent call last): File "C:\Python36\lib\site-packages\flask\app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "C:\Python36\lib\site-packages\flask\app.py", line 1985, in wsgi_app response = self.handle_exception(e) File "C:\Python36\lib\site-packages\flask\app.py", line 1540, in handle_exception reraise(exc_type, exc_value, tb) File "C:\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Python36\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Python36\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Python36\lib\site-packages\flask\app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "C:\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise raise value File "C:\Python36\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "C:\Python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Python36\lib\site-packages\flask_ask\core.py", line 728, in _flask_view_func ask_payload = self._alexa_request(verify=self.ask_verify_requests) File "C:\Python36\lib\site-packages\flask_ask\core.py", line 662, in _alexa_request cert = verifier.load_certificate(cert_url) File "C:\Python36\lib\site-packages\flask_ask\verifier.py", line 21, in load_certificate if not _valid_certificate(cert): File "C:\Python36\lib\site-packages\flask_ask\verifier.py", line 63, in _valid_certificate value = str(extension) File "C:\Python36\lib\site-packages\OpenSSL\crypto.py", line 779, in __str__ return self._subjectAltNameString() File "C:\Python36\lib\site-packages\OpenSSL\crypto.py", line 740, in _subjectAltNameString method = _lib.X509V3_EXT_get(self._extension) AttributeError: module 'lib' has no attribute 'X509V3_EXT_get' ``` Pip freeze output: ``` aniso8601==1.2.0 asn1crypto==0.24.0 certifi==2018.1.18 cffi==1.11.5 chardet==3.0.4 click==6.7 cryptography==2.2 Flask==0.12.1 Flask-Ask==0.9.8 idna==2.6 itsdangerous==0.24 Jinja2==2.10 MarkupSafe==1.0 pycparser==2.18 pyOpenSSL==17.0.0 python-dateutil==2.7.0 PyYAML==3.12 requests==2.18.4 six==1.11.0 Unidecode==1.0.22 urllib3==1.22 Werkzeug==0.14.1 ``` I've tried running it on both python 2.7 and python 3.6. Any help is appreciated<issue_comment>username_1: Ran into the same issue, you can fix it by downgrading cryptography to anything less than 2.2 for me. ``` pip install 'cryptography<2.2' ``` rpg711 gets all the credit (see comments the on original post) Upvotes: 6 [selected_answer]<issue_comment>username_2: I can confirm that this works with cryptography 2.1.4, not with 2.5 or 2.6 on Python 3.7 and Mac OS High Sierra. However on Mac OS there are other issues to get over first. What I found is that installing crypotgraphy 2.1.4 ends with an error (as below). I hit this error at the very start of my flask-ask project and had to do a manual install of requirements before I started coding. When I finally started trying alexa, I got the same 500 error (as above) with cryptography 2.5 or 2.6. So reading that it has to be 2.1.4 I always got this error when trying to install that specific version: ``` #include ^~~~~~~~~~~~~~~~~~~~ 1 error generated. error: command 'clang' failed with exit status 1 ``` Having tried many things I tried the specific recommendation in this post (<https://github.com/pyca/cryptography/issues/3489>). Trying the export CPPFLAGS and LDFLAGS didn't seem to work, however the following did `pip3 install cryptography==2.1.4 --global-option=build_ext --global-option="-L/usr/local/opt/openssl/lib" --global-option="-I/usr/local/opt/openssl/include"` I am afraid I cannot say whether the things I tried before i.e. brew link openssl and setting the CPPFLAGS and LDFLAGS had an impact on the final result. I did not however do an update of openssl as in the post. I hope that helps, but I was not operating from a position of knowledge and was not sure whether I had the skills do a manual install of opsenssl as indicated further in the post. I hope this helps as I had almost given up. BTW: using ngrok's web interface/inspector I found really handy, i.e. being able to replay the amazon request time and time again was very, very handy for me as I made other errors before the cryptography issue. Upvotes: 1 <issue_comment>username_3: Referring to this link helped me solve the problem. <https://github.com/pyca/cryptography/issues/3489> Basically, by linking openssl in mac by `$ brew link openssl`and installing cryptography==2.1.4, the problem was resolved. Upvotes: 0 <issue_comment>username_4: On debian linux, attempting to downgrade the cryptography module with ``` pip install 'cryptography<2.2' ``` led to the errors of not being able to uninstall the old module (I think I had version 2.6.1). I uninstalled it manually by deleting the folders cryptography along with the \*-.egg file within /usr/lib/python3/dist-packages. Then, when I tried to install the older cryptography module, I again ran into an error "unable to build wheel" because I was missing some headers. According to the [cryptography module docs](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux) Once I ran, ``` sudo apt-get install build-essential libssl-dev libffi-dev python3-dev ``` I was then finally able to install cryptography module version 2.1.4, and my alexa skill worked properly. Upvotes: 0
2018/03/20
678
2,218
<issue_start>username_0: ``` import pytest def add(x): return x + 1 def sub(x): return x - 1 testData1 = [1, 2] testData2 = [3] class Test_math(object): @pytest.mark.parametrize('n', testData1) def test_add(self, n): result = add(n) testData2.append(result) <-------- Modify testData here assert result == 5 @pytest.mark.parametrize('n', testData2) def test_sub(self, n): result = sub(n) assert result == 3 if __name__ == '__main__': pytest.main() ``` there are only 3 tests :`Test_math.test_add[1]`,`Test_math.test_add[2]`,`Test_math.test_sub[3]` executed in this scenario. `Test_math.test_sub` only executes with predefined data `[3]` which is not my expectation `[2,3,3]`. How to fix it? > > update [1,2,3]-> [2,3,3] > > ><issue_comment>username_1: Not exactly sure why it didn't work, but doing it like that it's a bad idea since the order of tests is not guaranteed (unless you implement ad-hoc code to order the execution of tests). Besides this and other issues of test design, the way you can somewhat achieve what you want would be by joining `testData1` and `testData2` in the `pytest.mark.parametrize` decorator. ``` @pytest.mark.parametrize('n', testData1 + testData2) def test_sub(self, n): result = sub(n) assert result == 3 ``` Now, keep in mind that with your test definition, this will always fail because the result of `sub(n)` with `testData1 + testData2` will never be `3`. Upvotes: 1 <issue_comment>username_2: ``` import pytest def add(x): return x + 1 def sub(x): return x - 1 testData1 = [1, 2] testData2 = [3] class Test_math(object): @pytest.mark.parametrize('n', testData1) def test_add(self, n): result = add(n) testData2.append(result) assert result == 5, "FAILED" return testData2 def add(): for i in testData1: res = add(i) testData2.append(res) print(testData2) return testData2 @pytest.mark.parametrize('n', add()) def test_sub(self, n): result = sub(n) assert result == 3, "FAILED" if __name__ == '__main__': pytest.main() ``` Upvotes: 0
2018/03/20
463
1,654
<issue_start>username_0: I am trying to pass the selected Id of an account when a user clicks the click zone. ``` ``` However, on my Account component, which this 'to' takes us to: ``` ``` I am getting Undefined. ``` export default class Account extends Component { constructor(props) { super(props); alert(props.id); ``` Is there a way to pass the prop to my component using the Link?<issue_comment>username_1: To pass props down to children you can do this ``` ( )} /> ``` and don't skip the spread operators. Upvotes: 0 <issue_comment>username_2: A clean way for a link to pass information to a route is to use a parameter in the URL: ``` // 1. Link to what would be the URL for a specific account. // would probably replace `1234` for a variable here View Account 1234 // 2. "capture" the ID in the url using a param matcher // We'll receive this param as "props.match.params.id" in the render function // using component={} also works here, and the props will be injected directly into the component instead, // but render={} here looks cleaner to me, and is more flexible if you wanna pass more props } /> ``` [See the docs for more information on how the `render` prop works.](https://reacttraining.com/react-router/web/api/Route/render-func) Upvotes: 0 <issue_comment>username_3: I think the best way would be define your account id as parameter in the route e.g. ``` Go to Accounts ``` and access it with `props.match.params.id`, but if you want to send through props you do this: ``` Go to Accounts ``` and in Account: ``` const { id } = props.location.state ``` Upvotes: 2 [selected_answer]
2018/03/20
681
2,030
<issue_start>username_0: I generated a bugreport in Android through ADB and extracted the large report file. But when I open and read that file, it prints: ``` >>> f = open('bugreport.txt') >>> f.read() Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self.\_buffer\_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 12788794: invalid start byte >>> f = open('bugreport.txt', encoding='ascii') >>> f.read() Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii\_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 5455694: ordinal not in range(128) ``` It seems that neither UTF-8 nor ASCII codec can decode the file. Then I checked the file encoding by two commands: ``` $ enca bugreport.txt 7bit ASCII characters $ file -i bugreport.txt bugreport.txt: text/plain; charset=us-ascii ``` They show me the file is encoded in ascii, while I can't open it by ascii codec. Some other clues: 1. The above python interpreter is python 3.6.3. **I tried python 2.7.14 and it went well.** 2. If the file is opened by adding parameters errors='ignore' and encoding='ascii', it can be read but all Chinese characters are lost. So how can I open that peculiar file in python 3? Can anyone help me?<issue_comment>username_1: In python 3 you can specify encoding with open context. ``` with open(file, encoding='utf-8') as f: data = f.read() ``` Upvotes: 3 <issue_comment>username_2: It's likely that the file is encoded as latin-1 or utf-16 (little-endian). ``` >>> bytes_ = [b'\xc0', b'\xef'] >>> for b in bytes_: ... print(repr(b), b.decode('latin-1')) ... b'\xc0' À b'\xef' ï >>> bytes_ = [b'\xc0\x00', b'\xef\x00'] >>> for b in bytes_: ... print(repr(b), b.decode('utf-16le')) ... b'\xc0\x00' À b'\xef\x00' ï ``` Upvotes: 2
2018/03/20
745
2,682
<issue_start>username_0: I recently installed [Git-LFS](https://git-lfs.github.com/ "Git-LFS") to manage large files. I've quickly reached the 1 Gb storage limit, however, and now when I try to push commits I'm prompted with: > > batch response: This repository is over its data quota. Purchase more > data packs to restore access. > > > and failure to push. So now I can't actually push to the repo. Purchasing more data packs is not an option, however storing large files locally (i.e. not having them version controlled) is. So what I would like to do is: 1. Stop monitoring the files that LFS monitors (currently set to all \*.csv in .gitattributes). 2. Remove those files from git, i.e. so that they don't contribute to any repo size. 3. Still have those files present locally. 4. Uninstall Git-LFS. 5. Disrupt the history as little as possible, ideally so only the removed files are affected. 6. Now that the repo size should be smaller, get back to being able to push/pull as normal. I've found bits and pieces of info around where people have exceeded the limit, but nothing that can do the above points. FWIW I typically use Tortoise Git but of course have Git Shell too.<issue_comment>username_1: > > Is there a way to rewrite history such that it omits the csv files but otherwise is the same? > > > That is what [`git filter-branch`](https://git-scm.com/docs/git-filter-branch) is for. Again, it will rewrite the history, so a `git push --force` will be needed. See also "[Git - Remove All of a Certain Type of File from the Index](https://stackoverflow.com/q/38880436/6309)": [BFG repo cleaner](https://rtyley.github.io/bfg-repo-cleaner/) can be easier/faster to use. Upvotes: 2 <issue_comment>username_2: If you exhuasted GitHub's free quota, but you don't care about using GitHub's LFS storage, then you can still push to GitHub commits with pointers to the LFS blobs (without uploading the blobs themselves) by "uninstalling" git lfs before pushing: ``` $ git push origin master batch response: This repository is over its data quota. Account responsible for LFS bandwidth should purchase more data packs to restore access. $ git lfs uninstall $ git lfs uninstall --local $ git push origin master # Push worked! ``` But, if you get the GH008 error (pre-receive hook declined) when you try to push commits with pointers, then the above trick may or may not help. Sometimes it works sometimes it doesn't, I don't fully understand the pattern: ``` $ git push origin master ... remote: error: GH008: Your push referenced at least 9 unknown Git LFS objects: ... ! [remote rejected] master -> master (pre-receive hook declined) ``` Upvotes: 1
2018/03/20
955
3,432
<issue_start>username_0: I have the following code to clear all filters in every sheet: ``` function clearAllFilter() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var ssId = ss.getId(); var sheetIds = ss.getSheets(); for (var i in sheetIds) { var requests = [{ "clearBasicFilter": { "sheetId": sheetIds[i].getSheetId() } }]; Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId); } } ``` The code is working well, but I'm getting the following error: ![Error Message](https://i.stack.imgur.com/Pp3hi.png) How do I get rid of this error message or better yet, optimize the code to complete its job as quickly as possible?... EDIT: to add more information, my spreadsheet has a 119 sheets.<issue_comment>username_1: You might have hit your current quota limit. Be noted for the [Usage Limits](https://developers.google.com/sheets/api/limits) of the Sheets API. > > This version of the Google Sheets API has a limit of 500 requests per 100 seconds per project, and 100 requests per 100 seconds per user. Limits for reads and writes are tracked separately. There is no daily usage limit. > > > To view or change usage limits for your project, or to request an increase to your quota, do the following: > > > 1. If you don't already have a [billing account](https://support.google.com/cloud/answer/6288653) for your project, then create one. > 2. [Visit the Enabled APIs page of the API library](https://console.developers.google.com/apis/enabled) in the API Console, and select an API from the list. > 3. To view and change quota-related settings, select **Quotas**. To view usage statistics, select **Usage**. > > > Hope this helps! Upvotes: 1 <issue_comment>username_2: @tehhowch comment was all I needed, he gave me a clue and I found a fix to the code. The error lies in the for loop: ``` for (var i in sheetIds) { var requests = [{ "clearBasicFilter": { "sheetId": sheetIds[i].getSheetId() } }]; Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId); } ``` Here I am looping through every sheet in the spreadsheet, obtaining the sheet ID and then calling `.batchUpdate()`. The problem here, is that I'm calling the sheets API for every sheet, meaning I'm calling it 119 times for all my 119 sheets. The above code is inefficient and beyond my quota limit. **FIX:** 1. Place all the sheets IDs into an array. 2. Move the `.batchUpdate()` outside of the for loop 3. Then do `.batchUpdate({'requests': array}` instead of `.batchUpdate({'requests': requests}` So now the code is efficient, instead of calling the sheets API 119 times, now I'm only calling it once, fixing my quota issue and successfully run the script without any error messages. **The complete code:** ``` function clearAllFilter() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var ssId = ss.getId(); var sheetIds = ss.getSheets(); var idArray = []; //loop through all the sheets, get the sheet ID, then push into the array for (var i in sheetIds) { var requests = [{ "clearBasicFilter": { "sheetId": sheetIds[i].getSheetId() } }]; idArray.push(requests); //now the array stores all the sheet IDs //Logger.log(idArray); } Sheets.Spreadsheets.batchUpdate({'requests': idArray}, ssId); //do .batchUpdate only once by passing in the array } ``` Upvotes: 3 [selected_answer]
2018/03/20
798
2,895
<issue_start>username_0: I want to create peerAdmin@\*\*\*.card via node. I only find `exportCard,importCard etc.` api in adminConnection. How can I create a peerAdmin card or other card using composer-admin api?<issue_comment>username_1: You might have hit your current quota limit. Be noted for the [Usage Limits](https://developers.google.com/sheets/api/limits) of the Sheets API. > > This version of the Google Sheets API has a limit of 500 requests per 100 seconds per project, and 100 requests per 100 seconds per user. Limits for reads and writes are tracked separately. There is no daily usage limit. > > > To view or change usage limits for your project, or to request an increase to your quota, do the following: > > > 1. If you don't already have a [billing account](https://support.google.com/cloud/answer/6288653) for your project, then create one. > 2. [Visit the Enabled APIs page of the API library](https://console.developers.google.com/apis/enabled) in the API Console, and select an API from the list. > 3. To view and change quota-related settings, select **Quotas**. To view usage statistics, select **Usage**. > > > Hope this helps! Upvotes: 1 <issue_comment>username_2: @tehhowch comment was all I needed, he gave me a clue and I found a fix to the code. The error lies in the for loop: ``` for (var i in sheetIds) { var requests = [{ "clearBasicFilter": { "sheetId": sheetIds[i].getSheetId() } }]; Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId); } ``` Here I am looping through every sheet in the spreadsheet, obtaining the sheet ID and then calling `.batchUpdate()`. The problem here, is that I'm calling the sheets API for every sheet, meaning I'm calling it 119 times for all my 119 sheets. The above code is inefficient and beyond my quota limit. **FIX:** 1. Place all the sheets IDs into an array. 2. Move the `.batchUpdate()` outside of the for loop 3. Then do `.batchUpdate({'requests': array}` instead of `.batchUpdate({'requests': requests}` So now the code is efficient, instead of calling the sheets API 119 times, now I'm only calling it once, fixing my quota issue and successfully run the script without any error messages. **The complete code:** ``` function clearAllFilter() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var ssId = ss.getId(); var sheetIds = ss.getSheets(); var idArray = []; //loop through all the sheets, get the sheet ID, then push into the array for (var i in sheetIds) { var requests = [{ "clearBasicFilter": { "sheetId": sheetIds[i].getSheetId() } }]; idArray.push(requests); //now the array stores all the sheet IDs //Logger.log(idArray); } Sheets.Spreadsheets.batchUpdate({'requests': idArray}, ssId); //do .batchUpdate only once by passing in the array } ``` Upvotes: 3 [selected_answer]
2018/03/20
551
2,068
<issue_start>username_0: I have developed a plugin for myself and was using it for a little and after decided to go public. But the plugin got declined after submission and code review with the reason ##Calling core loading files directly. I fixed already all issues they mentioned, but only one bothering me now. I have `require_once( ABSPATH.'/wp-admin/includes/upgrade.php' );` in few places to use dbDelta(), but if I will remove `require_once` declaration I won't be able to use dbDelta(). Do you think it will be an issue with second code review? Any developer who already did and released their plugins?<issue_comment>username_1: **Short and simple**: It shouldn't be an issue. **Longer Answer**: [`dbDelta()`](https://developer.wordpress.org/reference/functions/dbdelta/) is a function that's kind of a special case, because the "core file" (upgrade.php) that defines it isn't always going to be loaded when it's needed by your plugin. If it's a simple query, you could probably just use a prepared statement with [`$wpdb`](https://codex.wordpress.org/Class_Reference/wpdb). However if `dbDelta()` is indeed better for your needs (and it sounds like it is), it's *absolutely okay* to use `require_once` with `upgrade.php`, despite it technically being a core file. Take a look at the official [Creating Tables with Plugins](https://codex.wordpress.org/Creating_Tables_with_Plugins#Creating_or_Updating_the_Table) codex page that literally tells you to go ahead and use it in this manner: ``` require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); ``` With the reasoning: > > [...] we'll use the dbDelta function in wp-admin/includes/upgrade.php (we'll have to load this file, as it is not loaded by default) [...] > > > So, `require_once` away my friend! Upvotes: 2 <issue_comment>username_2: Alrighty, great news! Plugin got approved and it's already public :) Thank you, everyone, for the recommendations! You can release your plugin php code with `require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );` Upvotes: 0
2018/03/20
3,550
10,898
<issue_start>username_0: I was looking into StackExchange for a site for discussing just the basic ideas as I'm almost sure I come across it some time ago, but I couldn't find any out of beta, and the lack of developer friends to discuss in depth the issue, makes me come to StackOverflow for help, so here's my question. events ------ As I have not much to do these days, I was looking at apps like Toggle and Clockify and I was wondering about those... As a basic concept, a user can register `types` of events for any gap whatsoever, for example: ``` 2017-12-28 00:00:00 ~ 2018-01-14 23:59:59 // vacation 2018-01-20 00:00:00 ~ 2018-01-20 23:59:59 // devOps event 2018-01-24 00:00:00 ~ 2018-01-24 12:00:00 // haircut ``` detailed info ------------- if I want a detailed info about the events on the month of January, the actual conclusion I want to end up is something as ``` details = { events: [{...}, {...}, {...}], daysUsed: { vacation: 10, // holidays+weekends not counted internal: 1, personal: 0,5 } } ``` problems on paper I faced ------------------------- even if I "saved" the data as is, for example in an RDS table as ``` // evtId | user | from | to | eventType | description 1 | 1 | 2017-12-28 00:00:00 | 2018-01-14 23:59:59 | V | vacation 2 | 1 | 2018-01-20 00:00:00 | 2018-01-20 23:59:59 | I | devOps event 3 | 1 | 2018-01-24 00:00:00 | 2018-01-24 12:00:00 | P | haircut ``` I can't use datetime to actually select the range from Jan 1st to Jan 31st as ``` WHERE userId = 1 and from >= '...' and to <= '...' ``` I would need to spread each event into a **dailyEvent** manner in order to actually calculate anything regarding days, like ``` // eventId | date | evtType | dayType (holiday | weekend | vacation) 1 | 2017-12-28 | V | vacation 1 | 2017-12-29 | V | vacation 1 | 2017-12-30 | V | vacation & weekend 1 | 2017-12-31 | V | vacation & weekend 1 | 2018-01-01 | V | vacation & holiday 1 | 2018-01-02 | V | vacation 1 | 2018-01-03 | V | vacation 1 | 2018-01-04 | V | vacation 1 | 2018-01-05 | V | vacation ... ``` with such data I can then easily use only the database to do some calculations, at least between the dates and then process times in app I got to look at MomentJs library to see if I could, for example, add the raw registrations and somewhat get the results I wanted, but it's only for manipulating and calculate dates, not a range of dates ... a calendar library would make more sense ... didn't found any for javascript that I could see their approach to the problem... two tables instead of one ------------------------- I also thought about holding a secondary table where (dailyEvent) where I get a time gap and fill that table with one entry per day, making it easier to retrieve data from 2 dates... the issue is that is one more table to maintain when the user edits/deletes the main event... and sync-stuff never worked that well :/ * what would be the best way to hold/retrieve data for such task? * is the spreading into daily events the best idea? it would grow a table exponentially no? but nothing like a well designed index table wouldn't care about such, and maybe all events pass 5y old could be "archived" into a special table... what is your take? --- **added** to make the question even simpler, this is what I'm trying to wrap my head into [![](https://i.stack.imgur.com/zZJlb.png)](https://i.stack.imgur.com/zZJlb.png) how would one query this to get: ``` events 1, 2, 4 when query day 3 events 1, 2, 3 when query day 5 events 1, 2, 3 when query from days 4 to 7 events 1, 2 when query from days 10 to 14 ``` here's a test ms-sql to play around: ``` Hostname 3b5a01df-b75c-41f3-9489-a8ad01604961.sqlserver.sequelizer.com Database db3b5a01dfb75c41f39489a8ad01604961 Username czhsclbcolgeznij Password <PASSWORD> ```<issue_comment>username_1: In pseudo-sql, to find the intersection of time periods you can use ``` select * from events where startdate<=[end of day 3] and enddate>=[start of day 3] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Well, the task can't be solved entirely in SQL (from desired output, I guess you are aware of that). Also, I won't give exact solution, as it might be too broad, but I'd be happy to help in case of any questions. I took a look at your account and I saw that you have golden badge in C#, so I will reference this language in case of any suggestions. First, your desired object is quite complex, so let me assume such model: ``` public class Summary { public List events { get; set; } public Dictionary daysUsed { get; set; } = new Dictionary { { 'I', 0 }, { 'V', 0 }, { 'P', 0 } }; } ``` Your first suggestion about storing events was better in my opinion and I've chosen such approach. DDL === ``` declare @table table (evtId int, userId int, startDate datetime, endDate datetime, eventType char(1), [description] varchar(1000)) insert into @table values (1 , 1 , '2017-12-28 00:00:00' , '2018-01-14 23:59:59' , 'V' , 'vacation'), (2 , 1 , '2018-01-20 00:00:00' , '2018-01-20 23:59:59' , 'I' , 'devOps event'), (3 , 1 , '2018-01-24 00:00:00' , '2018-01-24 12:00:00' , 'P' , 'haircut') ``` Now, let's take a look at what you want to do: first, declare period, for which you want the summary - it can be in C# and passed through some SQL methods or some ORM to DB. For simplicity, I used SQL: ``` declare @startDate datetime, @endDate datetime select @startDate = '2018-01-01 00:00:00.000', @endDate = '2018-01-31 23:59:59.999' ``` Which is your example (period from 1st to 31st of Jan). Now let's try to get information we need: first, the most important part is to define CTE, which will perform tasks: 1. Get all events, which started or ended in given period (in January). Note: **events that lie partially in given period would be also included**. 2. We don't want any data from outside given period, so in CTE we will substitute start date, when event started before given period, with 1st of Jan. Also, we will substitute end date, when event ended after given period, with 31st of Jan. The CTE: ``` ;with cte as ( select evtId, userId, case when startDate < @startDate then @startDate else startDate end [startDate], case when endDate > @endDate then @endDate else endDate end [endDate], eventType, [Description] from @table where (startDate between @startDate and @endDate) or (endDate between @startDate and @endDate) ) ``` Now, we have "clean" data from your table. Time to query it: For the first part, i.e. `events: [{...}, {...}, {...}]`, I guess following query will suffice: ``` select [description] from cte ``` Result of this query could be stored in `events` property of `Summary` class. Now, we need to populate `daysUsed` property: ``` select eventType, round(1.0 * sum(datediff(minute, startDate, endDate)) / (60 * 24), 2) [daysUsed] from cte group by eventType ``` Above query will return following data: ``` eventType|daysUsed I |1 P |0.5 V |14 ``` In general, result of above query will always be: ``` eventType|daysUsed I |value P |value V |value ``` This result can be easily used to populate `daysUsed` propertry in `Summary` class. At the end, you can serialize object of `Summary` class to JSON. Then you'd have desired output. **Notes:** 1. C# class is just an example to help me visualise what I want to do at every step. I don't know what technology you are using. 2. I know, that results of second query (to populate `daysUsed`) are little bit different from yours, as I didn't exclude weekends. I didn't exclude weekends and holidays, as that wasn't primary problem and I think you can easily handle that. 3. I usded CTE, which can be queried only once, so to be strict, it should be some temporary table or CTE's inner query can be used as a subquery in other queries (which would be the easiest in my opinion). Upvotes: 0 <issue_comment>username_3: If I understand the question correctly you simply wish to return events that was active with in a specified period. If that is correct then this is a relatively simple problem to solve. We can consider an event active within a period if: 1. Either the starting edge or ending edge of the event is contained within the period or 2. The event spans the entire period in which case the starting edge of the event will be less than the period’s start time and the ending edge of the event will be greater than the period’s end time. Following sample demonstrates: ``` -- ------------------------------------------------------- -- Creat sample table and data -- ------------------------------------------------------- CREATE TABLE [dbo].[EventData]( [ID] [int] IDENTITY(1,1) NOT NULL, [EventStart] [datetime] NOT NULL, [EventEnd] [datetime] NOT NULL, CONSTRAINT [PK_EventData] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET IDENTITY_INSERT [dbo].[EventData] ON GO INSERT [dbo].[EventData] ([ID], [EventStart], [EventEnd]) VALUES (1, CAST(N'2018-01-01T00:00:00.000' AS DateTime), CAST(N'2018-01-13T00:00:00.000' AS DateTime)) GO INSERT [dbo].[EventData] ([ID], [EventStart], [EventEnd]) VALUES (2, CAST(N'2018-01-03T00:00:00.000' AS DateTime), CAST(N'2018-01-15T00:00:00.000' AS DateTime)) GO INSERT [dbo].[EventData] ([ID], [EventStart], [EventEnd]) VALUES (3, CAST(N'2018-01-04T00:00:00.000' AS DateTime), CAST(N'2018-01-06T00:00:00.000' AS DateTime)) GO INSERT [dbo].[EventData] ([ID], [EventStart], [EventEnd]) VALUES (4, CAST(N'2018-01-02T00:00:00.000' AS DateTime), CAST(N'2018-01-04T00:00:00.000' AS DateTime)) GO SET IDENTITY_INSERT [dbo].[EventData] OFF GO -- ------------------------------------------------------- -- Sample Query -- ------------------------------------------------------- DECLARE @periodStart DATETIME = '10 Jan 2018'; -- Selection period start date and time DECLARE @periodEnd DATETIME = '14 Jan 2018'; -- Selection period end date and time SELECT * FROM [EventData] [E] WHERE ( ( -- Check if event start time is contained within period (@periodStart <= [E].[EventStart]) AND (@periodEnd > [E].[EventStart]) ) OR ( -- Check if event end time is contained within period (@periodStart < [E].[EventEnd]) AND (@periodEnd > [E].[EventEnd]) ) OR ( -- Check if the event spans the entire period (@periodStart >= [E].[EventStart]) AND (@periodEnd <= [E].[EventEnd]) ) ) ``` Upvotes: 0
2018/03/20
744
2,785
<issue_start>username_0: This is my controller but so that I can download excel. The locations of the controller and the model are both the same I already checked it but still there's an error and it says that "Class "App\Item" Not Found". ``` namespace Vanguard\Http\Controllers\Web; use Input; use App\Item; use DB; use Excel; use Illuminate\Http\Request; use Vanguard\Http\Controllers\Controller; use Cache; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class MaatwebsiteDemoController extends Controller { public function importExport() { return view('importExport'); } public function downloadExcel() { $data = Item::get()->toArray(); return Excel::create('itsolutionstuff_example', function($excel) use ($data) { $excel->sheet('mySheet', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download($type); } public function importExcel() { if(Input::hasFile('import_file')){ $path = Input::file('import_file')->getRealPath(); $data = Excel::load($path, function($reader){ })->get(); if(!empty($insert)){ foreach ($data as $key => $value) { $insert[] = ['title' => $value->title, 'description' => $value->description]; } if(!empty($insert)){ DB::table('items')->insert($insert); dd('Insert Record succesfully'); } } } return back(); } } ``` Then this is how my Model is. ``` php namespace Vanguard\App; use Illuminate\Database\Eloquent\Model; class Item extends Model { public $fillable = ['title','description']; } </code ```<issue_comment>username_1: Your model's FQCN is `Vanguard\App\Item`, not `App\Item`. Upvotes: 2 <issue_comment>username_2: You are calling `App\Item` class and your class is `Vanguard\Item` **1. use `Vanguard\Item` Model** ``` use Input; // use App\Item; // REMOVE that line use Vanguard\Item; // ADD this line use DB; use Excel; use Illuminate\Http\Request; use Vanguard\Http\Controllers\Controller; use Cache; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class MaatwebsiteDemoController extends Controller { ... } ``` **2. Modify the Model namespace.** ``` namespace Vanguard; use Illuminate\Database\Eloquent\Model; class Item extends Model { public $fillable = ['title','description']; } ``` **3. and run `composer dump-autoload`** Upvotes: 2 <issue_comment>username_3: issue: Error Class 'App\Model\ModelCustomer' not found solved: i solved this issue by adding s to Model become Models. i was using "use App\Models\ModelCustomer" Upvotes: 0
2018/03/20
594
1,936
<issue_start>username_0: my assignment is to reverse a string array in place. I must use a swap function that swaps individual characters and this swap should be in a loop. Pass two character pointers to the swap function to manipulate the locations in memory. So here is what I have so far: ``` #include using namespace std; void swap(char \*a, char \*b){ //swap function that accepts two char pointers char temp = \*a; \*a = \*b; \*b = temp; } int main() { char array[5] = {'H','e','l','l','o'}; //string hello char \*start = array[0]; //pointer for start of string char \*end = array[array.length-1]; //pointer for end of string for (int i = 0, int j = array.length - 1; i < j; i++, j-- ){ swap(start,end); start++; end--; } for(int i = 0; i < 5; i++){ //print reversed array to user cout << array[i]; } } ``` I have little experience with pointers so I may be using them incorrectly. Any help would be appreciated!<issue_comment>username_1: Your model's FQCN is `Vanguard\App\Item`, not `App\Item`. Upvotes: 2 <issue_comment>username_2: You are calling `App\Item` class and your class is `Vanguard\Item` **1. use `Vanguard\Item` Model** ``` use Input; // use App\Item; // REMOVE that line use Vanguard\Item; // ADD this line use DB; use Excel; use Illuminate\Http\Request; use Vanguard\Http\Controllers\Controller; use Cache; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class MaatwebsiteDemoController extends Controller { ... } ``` **2. Modify the Model namespace.** ``` namespace Vanguard; use Illuminate\Database\Eloquent\Model; class Item extends Model { public $fillable = ['title','description']; } ``` **3. and run `composer dump-autoload`** Upvotes: 2 <issue_comment>username_3: issue: Error Class 'App\Model\ModelCustomer' not found solved: i solved this issue by adding s to Model become Models. i was using "use App\Models\ModelCustomer" Upvotes: 0
2018/03/20
974
3,523
<issue_start>username_0: **Update** I've trying to sign in in this website: [Salesforce Trailhead](https://trailhead.salesforce.com/en/home) Unfortunately, I have not been successful. Here's my code: ``` WebDriver driver = new HtmlUnitDriver(); driver.get("https://trailhead.salesforce.com/en/home"); System.out.println(driver.getTitle()); WebElement btnLogin = driver.findElement(By.xpath("//*[@id=\"main-wrapper\"]/header/div[1]/div[2]/span[2]/div/span/button")); System.out.println(btnLogin); driver.quit(); ``` I'm trying to get the Login button from the header but, I cannot find the Element this is the exception message that I'm getting: > > Exception in thread "main" org.openqa.selenium.NoSuchElementException: > Unable to locate a node using > //\*[@id="main-wrapper"]/header/div[1](https://trailhead.salesforce.com/en/home)/div[2]/span[2]/div/span/button > > > I'm trying to test the answer from below but, I've not been successful. I would like to understand better how the WebDriverWait works and the until() method. Thanks.<issue_comment>username_1: The problem is there are more than one login buttons. Your code wait for the **first button** to be visible. Unfortunately, it won't. So Selenium waits until timeout. I recommend creating a method to find the correct button by iterate through all saleforce login buttons and check the property `isDisplayed()`. If it is, use the button. See my example below. ``` private WebElement findLoginButton(WebDriver d, By by) { List elements = d.findElements(by); for (Iterator e = elements.iterator(); e.hasNext();) { WebElement item = e.next(); if(item.isDisplayed()) return item; } return null; } @Test public void testSaleforce() { WebDriver driver = new HtmlUnitDriver(); driver.get("https://trailhead.salesforce.com/en/home"); System.out.println(driver.getTitle()); WebElement btnLogin = driver.findElement(By.xpath("//\*[@data-react-class='auth/LoginModalBtn']")); System.out.println(btnLogin); btnLogin.click(); WebDriverWait wait = new WebDriverWait(driver,10); WebElement btnLoginSalesforce = wait.until((WebDriver d) -> findLoginButton(d,By.cssSelector(".th-modal-btn\_\_salesforce"))); btnLoginSalesforce.click(); ... } ``` Upvotes: 0 <issue_comment>username_2: In this WebPage the developers were so kind to add special (HTML5) attributes to the HTML for test purposes, called 'data-test'. You can use CSS selectors to locate the Webelements in your Selenium code with help of this attributes. So no complicated Xpath selectors are needed and it's not necessary to iterate through the buttons as @username_1 suggested. I tested the following C# code and managed to click on the login button. ``` IWebElement btnLogin = Driver.FindElement(By.CssSelector("button[data-test=header-login]")); btnLogin.Click(); ``` I think you are using Java, then it will be: ``` WebElement btnLogin = driver.findElement(By.cssSelector("button[data-test=header-login]")); btnLogin.click(); ``` For a more stable solution you have to use Explicit wait: ``` WebDriverWait wait = new WebDriverWait(driver, 20); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.css(""button[data-test=header-login]""))); ``` Selenium will try to find the button every 500ms with a maximum of 20 seconds. NoSuchElementExceptions will be ignored till the button is found or till 20 seconds are passed. If the button is not found after 20 seconds a timeout exception will be thrown. Upvotes: 2 [selected_answer]
2018/03/20
922
3,499
<issue_start>username_0: I started to discover the environment of angular I have to install the environment as the video tells me. And I added a first component and the second component.And i added the button **save** and in component I add this code which already contains a deactivated button and after 4 seconds and then it will be active ``` Mes materiels ------------- Test Btn ``` Then in **app.component.ts** file and I added this code in which I define the function of the button to activate after 4 seconds ``` import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { isAuth=false; constructor(){ setTimeout( ()=>{ this.isAuth=true; }, 4000 ); } } ``` I do not know why the button does not activate after 4 seconds? and how can I find fault with angular? despite that I open the panel inspect in google chrome and nothing that shows me Thank you for your helping me :)<issue_comment>username_1: The problem is there are more than one login buttons. Your code wait for the **first button** to be visible. Unfortunately, it won't. So Selenium waits until timeout. I recommend creating a method to find the correct button by iterate through all saleforce login buttons and check the property `isDisplayed()`. If it is, use the button. See my example below. ``` private WebElement findLoginButton(WebDriver d, By by) { List elements = d.findElements(by); for (Iterator e = elements.iterator(); e.hasNext();) { WebElement item = e.next(); if(item.isDisplayed()) return item; } return null; } @Test public void testSaleforce() { WebDriver driver = new HtmlUnitDriver(); driver.get("https://trailhead.salesforce.com/en/home"); System.out.println(driver.getTitle()); WebElement btnLogin = driver.findElement(By.xpath("//\*[@data-react-class='auth/LoginModalBtn']")); System.out.println(btnLogin); btnLogin.click(); WebDriverWait wait = new WebDriverWait(driver,10); WebElement btnLoginSalesforce = wait.until((WebDriver d) -> findLoginButton(d,By.cssSelector(".th-modal-btn\_\_salesforce"))); btnLoginSalesforce.click(); ... } ``` Upvotes: 0 <issue_comment>username_2: In this WebPage the developers were so kind to add special (HTML5) attributes to the HTML for test purposes, called 'data-test'. You can use CSS selectors to locate the Webelements in your Selenium code with help of this attributes. So no complicated Xpath selectors are needed and it's not necessary to iterate through the buttons as @username_1 suggested. I tested the following C# code and managed to click on the login button. ``` IWebElement btnLogin = Driver.FindElement(By.CssSelector("button[data-test=header-login]")); btnLogin.Click(); ``` I think you are using Java, then it will be: ``` WebElement btnLogin = driver.findElement(By.cssSelector("button[data-test=header-login]")); btnLogin.click(); ``` For a more stable solution you have to use Explicit wait: ``` WebDriverWait wait = new WebDriverWait(driver, 20); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.css(""button[data-test=header-login]""))); ``` Selenium will try to find the button every 500ms with a maximum of 20 seconds. NoSuchElementExceptions will be ignored till the button is found or till 20 seconds are passed. If the button is not found after 20 seconds a timeout exception will be thrown. Upvotes: 2 [selected_answer]
2018/03/20
739
2,624
<issue_start>username_0: I am using iTerm on my mac and ZSH and oh my zsh with the theme `dstufft` I wrote this in my `.bash_rc` ``` function goToPythonApp { # no params given if [ -z "$1" ]; then cd ~/Documents/Apps/PythonApps else cd ~/Documents/Apps/PythonApps/$1 fi } ``` so I can type `goToPythonApp abc` Then I will switch to `~/Documents/Apps/PythonApps/abc` But sometimes, I forget the name of the folder in `~/Documents/Apps/PythonApps/` Is there a way to type `goToPythonApp` and then press then press to generate a list of entries in `~/Documents/Apps/PythonApps/`? Similar to how ZSH (or oh-my-zsh) can do autocomplete for half typed commands? Either that or I can type `goToPythonApp ab` then press and the auto complete suggests `abc` which is a valid entry in the folder `~/Documents/Apps/PythonApps/`? **UPDATE** Used the technique suggested in the answer below then I got a `command not found for complete`. Then I added `autoload bashcompinit && bashcompinit` before I source the `.bash_rc file` The `command not found for complete` was gone but the tab still doesn't work<issue_comment>username_1: you can you use bash completion features to handle this add this script to your rc file or your bash\_profile file, then reopen your terminal ``` function goToPythonApp { # no params given if [ -z "$1" ]; then cd ~/Documents/Apps/PythonApps/ else cd ~/Documents/Apps/PythonApps/$1 fi } function _GPA { local cur cur=${COMP_WORDS[COMP_CWORD]} COMPREPLY=( $( compgen -S/ -d ~/Documents/Apps/PythonApps/$cur | cut -b 18- ) ) } complete -o nospace -F _GPA goToPythonApp ``` [Complete Info on how to do this](https://sixohthree.com/867/bash-completion) Upvotes: 2 <issue_comment>username_2: In Zsh, you don't need your function. Add the following to your `.zshrc` file: ``` setopt autocd pyapps=~/Documents/Apps/PythonApps ``` `autocd` lets you change to a directory just by typing the name of the directory, rather than using the `cd` command explicitly. Static named directories (described in `man zshexpn` under FILENAME GENERATION) lets you define ~-prefixed aliases for directories. As long as `pyapps` isn't the name of a user on your system, the contents of the variable replace `~pyapps` anywhere you use it. Combining the two features, * `~pyapps` is equivalent to `cd "$pyapps"` * `~pyapps/Project1` is equivalent to `cd "$pyapps/Project1"` * `~pyapps/` will let you use tab completion on the contents of `$pyapps`. Upvotes: 3 [selected_answer]
2018/03/20
2,778
10,223
<issue_start>username_0: I am developing a **Java Web Application** using **JSF, Primefaces and XHTML**. In which, I am trying to read the **Cell** content from **Excel** using **POI**. In cell, it contains some styling like (bold, color, line-through, underline and etc) along with the value. So now, I need to show the value as well all the styles of the cell in **XHTML** page. Kindly help me to solve this.<issue_comment>username_1: The style is either applied to the whole cell or to parts of the cell content in rich text string content. If applied to the whole cell, the cell style has a [Font](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Font.html) applied from which you can get the style. For getting the styles from rich text string content, you need to get the [RichTextString](https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/RichTextString.html) from the cell. This consists of multiple formatting runs, each having a style having a `Font` applied. So you need looping over all formatting runs to get their styles and their `Font`s. Example: ``` import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; import java.io.FileInputStream; class ReadExcelRichTextCells { static StringBuffer getHTMLFormatted(String textpart, Font font) { StringBuffer htmlstring = new StringBuffer(); boolean wasbold = false; boolean wasitalic = false; boolean wasunderlined = false; boolean wassub = false; boolean wassup = false; if (font != null) { if (font.getBold() ) { htmlstring.append("**"); wasbold = true; } if (font.getItalic()) { htmlstring.append("*"); wasitalic = true; } if (font.getUnderline() == Font.U\_SINGLE) { htmlstring.append(""); wasunderlined = true; } if (font.getTypeOffset() == Font.SS\_SUB) { htmlstring.append(""); wassub = true; } if (font.getTypeOffset() == Font.SS\_SUPER) { htmlstring.append(""); wassup = true; } } htmlstring.append(textpart); if (wassup) { htmlstring.append(""); } if (wassub) { htmlstring.append(""); } if (wasunderlined) { htmlstring.append(""); } if (wasitalic) { htmlstring.append("*"); } if (wasbold) { htmlstring.append("**"); } return htmlstring; } public static void main(String[] args) throws Exception { Workbook wb = WorkbookFactory.create(new FileInputStream("ExcelRichTextCells.xlsx")); Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { switch (cell.getCellTypeEnum()) { case STRING: //CellType String XSSFRichTextString richtextstring = (XSSFRichTextString)cell.getRichStringCellValue(); String textstring = richtextstring.getString(); StringBuffer htmlstring = new StringBuffer(); if (richtextstring.hasFormatting()) { for (int i = 0; i < richtextstring.numFormattingRuns(); i++) { int indexofformattingrun = richtextstring.getIndexOfFormattingRun(i); String textpart = textstring.substring(indexofformattingrun, indexofformattingrun + richtextstring.getLengthOfFormattingRun(i)); Font font = richtextstring.getFontOfFormattingRun(i); // font might be null if no formatting is applied to the specified text run // then font of the cell should be used. if (font == null) font = wb.getFontAt(cell.getCellStyle().getFontIndex()); htmlstring.append(getHTMLFormatted(textpart, font)); } } else { Font font = wb.getFontAt(cell.getCellStyle().getFontIndex()); htmlstring.append(getHTMLFormatted(textstring, font)); } System.out.println(htmlstring); break; //case ... other CellTypes default: System.out.println("default cell"); //should never occur } } } wb.close(); } } ``` --- This code was tested using `apache poi 3.17`. For using this code with `apache poi 4.0.1` do using `CellStyle.getCellType` instead of `getCellTypeEnum`and `CellStyle.getFontIndexAsInt` instead of `getFontIndex`. ``` ... //switch (cell.getCellTypeEnum()) { switch (cell.getCellType()) { ... //Font font = wb.getFontAt(cell.getCellStyle().getFontIndex()); Font font = wb.getFontAt(cell.getCellStyle().getFontIndexAsInt()); ... //if (font == null) font = wb.getFontAt(cell.getCellStyle().getFontIndex()); if (font == null) font = wb.getFontAt(cell.getCellStyle().getFontIndexAsInt()); ... ``` --- The following is a version which supports both, `XSSF` and `HSSF`. It is tested and works using current `apache poi 5.2.1`. The only difference between `XSSF` and `HSSF` is while getting the font of formatting run. `XSSF` gets the font directly while `HSSF` gets the font index in the workbook only. ``` import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; import org.apache.poi.hssf.usermodel.*; import java.io.FileInputStream; class ReadExcelRichTextCells { static StringBuffer getHTMLFormatted(String textpart, Font font) { StringBuffer htmlstring = new StringBuffer(); boolean wasbold = false; boolean wasitalic = false; boolean wasunderlined = false; boolean wassub = false; boolean wassup = false; if (font != null) { if (font.getBold() ) { htmlstring.append("**"); wasbold = true; } if (font.getItalic()) { htmlstring.append("*"); wasitalic = true; } if (font.getUnderline() == Font.U\_SINGLE) { htmlstring.append(""); wasunderlined = true; } if (font.getTypeOffset() == Font.SS\_SUB) { htmlstring.append(""); wassub = true; } if (font.getTypeOffset() == Font.SS\_SUPER) { htmlstring.append(""); wassup = true; } } htmlstring.append(textpart); if (wassup) { htmlstring.append(""); } if (wassub) { htmlstring.append(""); } if (wasunderlined) { htmlstring.append(""); } if (wasitalic) { htmlstring.append("*"); } if (wasbold) { htmlstring.append("**"); } return htmlstring; } public static void main(String[] args) throws Exception { Workbook wb = WorkbookFactory.create(new FileInputStream("./ExcelRichTextCells.xlsx")); //Workbook wb = WorkbookFactory.create(new FileInputStream("./ExcelRichTextCells.xls")); Sheet sheet = wb.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { //switch (cell.getCellTypeEnum()) { switch (cell.getCellType()) { case STRING: //CellType String RichTextString richtextstring = cell.getRichStringCellValue(); String textstring = richtextstring.getString(); StringBuffer htmlstring = new StringBuffer(); if (richtextstring.numFormattingRuns() > 0) { // we have formatted runs if (richtextstring instanceof HSSFRichTextString) { // HSSF does not count first run as formatted run when it does not have formatting if (richtextstring.getIndexOfFormattingRun(0) != 0) { // index of first formatted run is not at start of text String textpart = textstring.substring(0, richtextstring.getIndexOfFormattingRun(0)); // get first run from index 0 to index of first formatted run Font font = wb.getFontAt(cell.getCellStyle().getFontIndex()); // use cell font htmlstring.append(getHTMLFormatted(textpart, font)); } } for (int i = 0; i < richtextstring.numFormattingRuns(); i++) { // loop through all formatted runs // get index of frormatting run and index of next frormatting run int indexofformattingrun = richtextstring.getIndexOfFormattingRun(i); int indexofnextformattingrun = textstring.length(); if ((i+1) < richtextstring.numFormattingRuns()) indexofnextformattingrun = richtextstring.getIndexOfFormattingRun(i+1); // formatted text part is the sub string from index of frormatting run to index of next frormatting run String textpart = textstring.substring(indexofformattingrun, indexofnextformattingrun); // determine used font Font font = null; if (richtextstring instanceof XSSFRichTextString) { font = ((XSSFRichTextString)richtextstring).getFontOfFormattingRun(i); // font might be null if no formatting is applied to the specified text run // then font of the cell should be used. if (font == null) font = wb.getFontAt(cell.getCellStyle().getFontIndex()); } else if (richtextstring instanceof HSSFRichTextString) { short fontIndex = ((HSSFRichTextString)richtextstring).getFontOfFormattingRun(i); // font index might be HSSFRichTextString.NO_FONT if no formatting is applied to the specified text run // then font of the cell should be used. if (fontIndex == HSSFRichTextString.NO_FONT) { font = wb.getFontAt(cell.getCellStyle().getFontIndex()); } else { font = wb.getFontAt(fontIndex); } } htmlstring.append(getHTMLFormatted(textpart, font)); } } else { Font font = wb.getFontAt(cell.getCellStyle().getFontIndex()); htmlstring.append(getHTMLFormatted(textstring, font)); } System.out.println(htmlstring); break; //case ... other CellTypes default: System.out.println("default cell"); //should never occur } } } wb.close(); } } ``` Upvotes: 2 <issue_comment>username_2: Thanks to **@Axel**, as his answer didn't include **color** so I decided to add it. But unfortunately in my case, `font.getColor()` always returned '0'. I went through another way as this: ``` static StringBuffer getHTMLFormatted(String textpart, Font font) { StringBuffer htmlstring = new StringBuffer(); ... boolean hasColor = false; ... if(font.toString().contains("") ; hasColor = true ; } } htmlstring.append(textpart); ... if (hasColor) { htmlstring.append(""); } return htmlstring; } public static String getColor(Font font){ String colorStr ; Pattern pattern = Pattern.compile(""); Matcher matcher = pattern.matcher(font.toString()); if (matcher.find()) { Log.i(TAG , "font color = : " + matcher.group(1)); colorStr = matcher.group(1); colorStr = colorStr.substring(2); }else { colorStr = "616A6B" ; // my defualt color } return colorStr; } ``` Upvotes: 0
2018/03/20
1,747
4,790
<issue_start>username_0: > > Git Bash version is "Git-2.16.2-32-bit". > > > After installing the Git Bash, and set up the env PATH. adb.exe has no response when I execute "adb shell". > > **I can do "adb devices" or "adb push", but adb shell has no response** > > > Please refer below's picture : [![enter image description here](https://i.stack.imgur.com/YImrM.png)](https://i.stack.imgur.com/YImrM.png) > > KimmyYang@KimmyYang-3020 MINGW64 /d/Git $ env > > > ``` HOMEPATH=\Users\kimmyyang MANPATH=/mingw64/share/man:/usr/local/man:/usr/share/man:/usr/man:/share/man: APPDATA=C:\Users\kimmyyang\AppData\Roaming ProgramW6432=C:\Program Files HOSTNAME=KimmyYang-3020 SHELL=/usr/bin/bash TERM=xterm PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 60 Stepping 3, GenuineIntel WINDIR=C:\Windows TMPDIR=/tmp PUBLIC=C:\Users\Public OLDPWD=/d USERDOMAIN=FIHTDC CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files OS=Windows_NT ALLUSERSPROFILE=C:\ProgramData windows_tracing_flags=3 windows_tracing_logfile=C:\BVTBin\Tests\installpackage\csilogfile.log TEMP=/tmp COMMONPROGRAMFILES=C:\Program Files\Common Files USERNAME=KimmyYang PROCESSOR_LEVEL=6 ProgramFiles(x86)=C:\Program Files (x86) PATH=/c/platform-tools:/c/Users/kimmyyang/bin:/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/mingw64/bin:/usr/bin:/c/Users/kimmyyang/bin:/c/Program Files (x86)/Intel/iCLS Client:/c/Program Files/Intel/iCLS Client:/c/Windows/system32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0:/c/Program Files/Intel/Intel(R) Management Engine Components/DAL:/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/DAL:/c/Program Files/Intel/Intel(R) Management Engine Components/IPT:/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/IPT:/c/Program Files/PuTTY:/c/Program Files (x86)/Windows Kits/8.1/Windows Performance Toolkit:/c/Program Files/Microsoft SQL Server/110/Tools/Binn:/c/Python27:/c/Python27/Scripts:/c/Python27/Lib/site-packages:/c/Python27/Lib/site-packages/gensim:/c/Python27/Lib/site-packages/scipy/extra-dll:/c/platform-tools:/usr/bin/vendor_perl:/usr/bin/core_perl EXEPATH=D:\Git PSModulePath=C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ FP_NO_HOST_CHECK=NO PWD=/d/Git SYSTEMDRIVE=C: LANG=zh_TW.UTF-8 VS120COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\ USERPROFILE=C:\Users\kimmyyang PS1=\[\033]0;$MSYSTEM:${PWD//[^[:ascii:]]/?}\007\]\n\[\033[32m\]\u@\h \[\033[35m\]$MSYSTEM \[\033[33m\]\w\[\033[36m\]`__git_ps1`\[\033[0m\]\n$ LOGONSERVER=\\HC-A01 CommonProgramW6432=C:\Program Files\Common Files PROCESSOR_ARCHITECTURE=AMD64 LOCALAPPDATA=C:\Users\kimmyyang\AppData\Local SSH_ASKPASS=/mingw64/libexec/git-core/git-gui--askpass ProgramData=C:\ProgramData SHLVL=1 HOME=/c/Users/kimmyyang USERDNSDOMAIN=FIHTDC.COM PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC PLINK_PROTOCOL=ssh HOMEDRIVE=C: MSYSTEM=MINGW64 COMSPEC=C:\Windows\system32\cmd.exe TMP=/tmp SYSTEMROOT=C:\Windows PRINTER=\\tpe-f01\DingPu-3F PROCESSOR_REVISION=3c03 PKG_CONFIG_PATH=/mingw64/lib/pkgconfig:/mingw64/share/pkgconfig ACLOCAL_PATH=/mingw64/share/aclocal:/usr/share/aclocal INFOPATH=/usr/local/info:/usr/share/info:/usr/info:/share/info: PROGRAMFILES=C:\Program Files DISPLAY=needs-to-be-defined NUMBER_OF_PROCESSORS=4 SESSIONNAME=Console COMPUTERNAME=KIMMYYANG-3020 _=/usr/bin/env ``` Why adb shell has no response on Git Bash? Thank you.<issue_comment>username_1: I only used adb.exe in a CMD session, not a bash session. As [detailed here](https://superuser.com/a/1053657/141), git bash provides mintty, with a better POSIX compatibility. That does not work with some Windows programs. If you use a [simplified PATH](https://stackoverflow.com/a/49248983/6309), you still can access most Linux commands directly from a CMD session (without needing the bash) Upvotes: 1 <issue_comment>username_2: This is an old question, but it's worth pointing out that you are receiving a response while running `adb shell`, but it's just that the terminal prompt is not visible. You'd be able to issue commands and view the responses just fine, as shown below. ![Image showing windows console with ADB shell](https://i.stack.imgur.com/PJPEh.png) ![Image showing git bash console with ADB shell](https://i.stack.imgur.com/xLvWh.png) Upvotes: 2 <issue_comment>username_3: you can try : winpty adb shell.Please refer below's picture : [image](https://i.stack.imgur.com/N8K6R.png) Upvotes: 0 <issue_comment>username_4: Just adding to the knowledge base. Git bash on my windows 10 will work doing an adb shell into my oculus quest 2, but there is no prompt or echo of what you time later. Otoh, vs code says hollywood/ and echoes what you type. Haven't tried winpty yet. Iirc, windows bash works also. Upvotes: 0
2018/03/20
782
2,858
<issue_start>username_0: I use a OpenCV [fisheye model](https://docs.opencv.org/trunk/db/d58/group__calib3d__fisheye.html) function to perform fisheye calibration work. My image is a Circular fisheye ([example](https://i.stack.imgur.com/vzv4x.jpg)), but I'm getting [this result](https://i.stack.imgur.com/DoDos.jpg) from the OpenCV fisheye model function. I have the following problems: 1. I don't know why the result is an oval and not a perfect circle. Is this as expected? 2. Can OpenCV fisheye model be calibrated for a Circular fisheye image? 3. I don't understand why the image is not centered when using the cv::fisheye::calibrate function to get the Cx Cy parameter in K? 4. What tips (picture number, angle and position...) can be used on the checkboard to get the corrent camera matrix and Distortion factor? --- Expected Result --------------- [![Fisheye w/ Distortion](https://i.stack.imgur.com/DszcF.jpg)](https://i.stack.imgur.com/DszcF.jpg) My Result --------- [![Fisheye w/ No Distortion](https://i.stack.imgur.com/lDSLt.jpg)](https://i.stack.imgur.com/lDSLt.jpg)<issue_comment>username_1: 1. I don't know why the result is an oval and not a perfect circle. Is this as expected? -> Tangential parameter of the calibration model can make it look like oval. It could be either your actual lens is tilted or calibration is incorrect. Just try to turn off tangential parameter option. 1. Can OpenCV fisheye model be calibrated for a Circular fisheye image? -> No problem as far as I know. Try ocam as well. 1. I don't understand why the image is not centered when using the cv::fisheye::calibrate function to get the Cx Cy parameter in K? -> It is normal that optical center does not align with the image center. It is a matter of degree, however. Cx, Cy represents the actual optical center. Low-quality fisheye camera manufactures does not control the quality of this parameter. 1. What tips (picture number, angle and position...) can be used on the checkboard to get the corrent camera matrix and Distortion factor? -> clear images only, different distances, different angles, different positions. As many as possible. Upvotes: 0 <issue_comment>username_2: First at all cv::fisheye uses a very simple idea. To remove radial distortion it will move points of fisheye circle in direction from circle center to circle edge. Points near center will be moved a little. Points near edges will be moved on much larger distance. In other words distance of point movement is not a constant. It's a function f(x)= 1+K1\*x3+K2\*x5+K3\*x7=K4\*x9. K1-K4 are coefficients of radial distortion of opencv fisheye undistortion model. In normal case undistorted image is always larger then initial image. As you can see your undistorted image is smaller then initial fisheye image. I think the source of problem is bad calibration. Upvotes: 1
2018/03/20
3,018
11,065
<issue_start>username_0: I'm playing around with keys in android and am trying to generate a public/private cryptographic key-pair. Unfortunately I keep getting a 'KeyStoreException: Invalid key blob'. I'm following the instructions here: <https://developer.android.com/training/articles/keystore.html> Particularly the section entitled 'Generating a New Private Key', which I feel my code copies almost verbatim: ``` try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore"); keyGen.initialize( new KeyGenParameterSpec.Builder( keyName, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY) .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512).build() ); KeyPair pair = keyGen.generateKeyPair(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } ``` The value of `keyName` comes from user input, but I have also tried it with the value `"abc"`. The error I'm getting is: ``` E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.calebg.claimcreator, PID: 17389 java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) at android.view.View.performClick(View.java:6579) at android.view.View.performClickInternal(View.java:6556) at android.view.View.access$3100(View.java:777) at android.view.View$PerformClick.run(View.java:25660) at android.os.Handler.handleCallback(Handler.java:819) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6656) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) at android.view.View.performClick(View.java:6579)  at android.view.View.performClickInternal(View.java:6556)  at android.view.View.access$3100(View.java:777)  at android.view.View$PerformClick.run(View.java:25660)  at android.os.Handler.handleCallback(Handler.java:819)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6656)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)  Caused by: java.security.ProviderException: Failed to load generated key pair from keystore at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:530) at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:478) at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:727) at com.example.calebg.claimcreator.CreateKeyActivity.createKey(CreateKeyActivity.java:76) at java.lang.reflect.Method.invoke(Native Method)  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  at android.view.View.performClick(View.java:6579)  at android.view.View.performClickInternal(View.java:6556)  at android.view.View.access$3100(View.java:777)  at android.view.View$PerformClick.run(View.java:25660)  at android.os.Handler.handleCallback(Handler.java:819)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6656)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)  Caused by: java.security.UnrecoverableKeyException: Failed to obtain X.509 form of public key at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:239) at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:278) at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:289) at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:521) at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:478)  at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:727)  at com.example.calebg.claimcreator.CreateKeyActivity.createKey(CreateKeyActivity.java:76)  at java.lang.reflect.Method.invoke(Native Method)  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  at android.view.View.performClick(View.java:6579)  at android.view.View.performClickInternal(View.java:6556)  at android.view.View.access$3100(View.java:777)  at android.view.View$PerformClick.run(View.java:25660)  at android.os.Handler.handleCallback(Handler.java:819)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6656)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)  Caused by: android.security.KeyStoreException: Invalid key blob at android.security.KeyStore.getKeyStoreException(KeyStore.java:823) at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStorePublicKeyFromKeystore(AndroidKeyStoreProvider.java:241) at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:278)  at android.security.keystore.AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore(AndroidKeyStoreProvider.java:289)  at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.loadKeystoreKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:521)  at android.security.keystore.AndroidKeyStoreKeyPairGeneratorSpi.generateKeyPair(AndroidKeyStoreKeyPairGeneratorSpi.java:478)  at java.security.KeyPairGenerator$Delegate.generateKeyPair(KeyPairGenerator.java:727)  at com.example.calebg.claimcreator.CreateKeyActivity.createKey(CreateKeyActivity.java:76)  at java.lang.reflect.Method.invoke(Native Method)  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  at android.view.View.performClick(View.java:6579)  at android.view.View.performClickInternal(View.java:6556)  at android.view.View.access$3100(View.java:777)  at android.view.View$PerformClick.run(View.java:25660)  at android.os.Handler.handleCallback(Handler.java:819)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6656)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)  ``` I'm using Android Studio 3.0.1, minSdkVersion 23, targetSdkVersion 26, and I'm testing this on a "Nexus 6 API P" virtual device. The only other related stackoverflow question I have found (also the only google result) that looks helpful is: [android.security.KeyStoreException: Invalid key blob](https://stackoverflow.com/questions/36488219/android-security-keystoreexception-invalid-key-blob) However I'm not clear how to apply the answer to my situation and I'm not convinced it is a correct solution in my case (how could the keystore be locked/uninitialised when I only just initialised it? How does catching an exception and trying again solve this problem?). Can anyone identify what I'm doing wrong?<issue_comment>username_1: You may try the following code, it is based on AES-128 encryption algo. ``` public void RandomKey(View view) { int[] Keys = new int[16]; String keyString =""; //reset the secret key into null Secret_Key=""; SecretKey.setText(Secret_Key); try { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); // 128 bit javax.crypto.SecretKey secretKey = keyGen.generateKey(); //generate secret key SKey= secretKey.getEncoded(); // to display for (int i = 0; i < 16; i++) { Keys[i] = SKey[i] & 0x000000FF;//convert byte to integer keyString = Integer.toHexString(Keys[i]); if (keyString.length() < 2) { keyString="0"+keyString; } //Log.d("keys are"," "+i+keyString); Secret_Key = Secret_Key + " " + keyString; } SecretKey.setAllCaps(true); SecretKey.setText(Secret_Key); } ``` for more complete program, you can refer to this: <https://github.com/aliakbarpa/AES-128_for_Android> Upvotes: -1 <issue_comment>username_2: I tried this on a real device and it works. Don't know why, but for some reason the Android emulator is unable to create keys according to the Android documentation. Upvotes: 1 [selected_answer]<issue_comment>username_3: I have the same issue while trying to run my app on Android-P, I think they made some changes on the keystore [See the preview](https://developer.android.com/preview/features/security.html), I was wondering if your physical device was running with Android P? Upvotes: 1
2018/03/20
661
2,046
<issue_start>username_0: Fabric found that the `NSMutableArray` found crash when calling `removeAllObjects`. Most of the crash happened in iOS9. This is my code, crash in `[self.recommentGoodsArray removeAllObjects]`: ``` - (void)clickColorWithIndex:(NSUInteger)index { [self.recommentGoodsArray removeAllObjects]; [self.tableView reloadData]; GoodsInfo *gInfo = [self.goodsInfo.relatedGoodsArray objectAt:index]; self.goods_id = gInfo.goods_id; [self loadGoodsDetail]; } ``` Fabric Latest Session ``` Crashed: com.apple.main-thread 0 libobjc.A.dylib 0x22d2a94e realizeClass(objc_class*) + 25 1 libobjc.A.dylib 0x22d2aa15 realizeClass(objc_class*) + 224 2 libobjc.A.dylib 0x22d2aa15 realizeClass(objc_class*) + 224 3 libobjc.A.dylib 0x22d2d91b lookUpImpOrForward + 158 4 libobjc.A.dylib 0x22d2d873 _class_lookupMethodAndLoadCache3 + 34 5 libobjc.A.dylib 0x22d33cfb _objc_msgSend_uncached + 26 6 CoreFoundation 0x2357e523 -[__NSArrayM removeAllObjects] + 266 7 ZZKKO 0x19f781 -[GoodsDetailVC clickColorWithIndex:] (GoodsDetailVC.m:825) ``` [![enter image description here](https://i.stack.imgur.com/Y12VN.png)](https://i.stack.imgur.com/Y12VN.png)<issue_comment>username_1: You can try if self.recommentGoodsArray has objects before removing it. ``` if ([self.recommentGoodsArray count]){ [self.recommentGoodsArray removeAllObjects]; } ``` Upvotes: -1 <issue_comment>username_2: You have a crash in `_objc_msgSend_uncached`. It's likely that you are addressing deallocated object. It cat either be `recommentGoodsArray`, or `self`. You need to check following: 1. Is recommentGoodsArray declared `strong` or `weak`? It has to be `strong`. 2. Is it possible for this method to be called after VC was destroyed (example: from a timer or in a callback from an UIAlertView). If so, you have to retain self until the moment your function is done working with self. Upvotes: 1
2018/03/20
471
1,643
<issue_start>username_0: I am getting this error when running: terminate called after throwing an instance of 'std::out\_of\_range' what(): basic\_string::substr: I am brand new, any other tips would be appreciated as well. ``` #include #include using namespace std; int main() { string name; int position = 1; string letter; cout << "Enter in your full name seperated by a space: "; getline (cin, name); cout << name.substr(0, 1); while (position <= name.length()) { position++; letter = name.substr(position, 1); if (letter == " ") { cout << name.substr(position + 1, 1) << " "; } } cout << endl; return 0; } ```<issue_comment>username_1: In your loop, `position` will increase to a number equal to the characters entered by the user (i.e. "Abc Def" last loop iteration: position = 8). In this case `name.substr(position, 1);` tries to extract the character after the last character in your string, hence the `std::out_of_range` exception. You may want to change your loop condition to: `while (position <= name.length() - 1)` or `while (position < name.length())` Upvotes: 0 <issue_comment>username_2: You are trying to reach an index after the last index, you need to change your loop condition to : `position < name.length()` and you can solve this problem using for-loop which is more used for such problems, you just need to substitute your while-loop with : ``` for (int position = 0; position < (name.length()-1); position++) { if (name[position] == ' ') { cout << name[position+1]; } } ``` Using this you wouldn't need to use `substr()` method neither `string letter` . Upvotes: 2
2018/03/20
1,967
6,273
<issue_start>username_0: I am trying to use angularJS to repeat div cards in rows of 3. However, it doesn't seem to be working. Rather than showing the cards in their rows, it shows pure html, where the object keywords in {{ }} are showing up plain. Here is all the relevant code. Index.html ``` Client App | InLine [InLine](#) Welcome Back, User Current Conference: Conference ============================== {{line.name}} {{line.description}} * Time: {{line.time}} * Number of People: {{line.numPeople}} * [Card link](#) ``` /src/app.js ``` angular.module('inLineClient', []) .controller('lineController', function($scope) { $scope.linesList = [ { name: 'Lunch', description: 'Lunch time! Come down for some pizza, french fries and drinks!\nPrice: $10 for Pizza, Fries, and a Soft Drink', time: new Date('October 21, 2017 12:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'VR Cave', description: 'Reserve your slot to play in our VR Cave', time: new Date('October 22, 2017 0:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Breakfast', description: 'Good Morning! Bagels and Cream Cheese with Coffee, Tea and Hot Chocolate this morning!', time: new Date('October 22, 2017 8:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Intro to RESTful APIs by RBC', description: 'Learn about how to create REST APIs for your web application, brought to you by RBC', time: new Date('October 21, 2017 17:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Contest Programming', description: 'Get your programming on by competing among different hackers to win a prize!', time: new Date('October 22, 2017 0:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null } ]; }); ``` Any help is appreciated and comment if mroe info is needed. Full repo at <https://github.com/khalid-talakshi/InLine><issue_comment>username_1: You are using **`$scope`** in controller and using **`Controller as syntax`** in the HTML. Follow either one way, In order to use $scope variable, change your HTML as, ``` {{line.name}} {{line.description}} * Time: {{line.time}} * Number of People: {{line.numPeople}} * [Card link](#) ``` **DEMO** ```js // Code goes here angular.module('inLineClient', []) .controller('lineController', function($scope) { $scope.message = "test"; $scope.linesList = [ { name: 'Lunch', description: 'Lunch time! Come down for some pizza, french fries and drinks!\nPrice: $10 for Pizza, Fries, and a Soft Drink', time: new Date('October 21, 2017 12:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'VR Cave', description: 'Reserve your slot to play in our VR Cave', time: new Date('October 22, 2017 0:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Breakfast', description: 'Good Morning! Bagels and Cream Cheese with Coffee, Tea and Hot Chocolate this morning!', time: new Date('October 22, 2017 8:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Intro to RESTful APIs by RBC', description: 'Learn about how to create REST APIs for your web application, brought to you by RBC', time: new Date('October 21, 2017 17:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Contest Programming', description: 'Get your programming on by competing among different hackers to win a prize!', time: new Date('October 22, 2017 0:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null } ]; }); ``` ```html Client App | InLine [InLine](#) Welcome Back, User Current Conference: Conference ============================== {{line.name}} {{line.description}} * Time: {{line.time}} * Number of People: {{line.numPeople}} * [Card link](#) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: When using Controller AS syntax then to access the properties of controller one has to assign 'this' keyword to any other variable(in my case i have assigned this to vm) and then he/she can access the properties via that controller as variable //index.html ``` Client App | InLine [InLine](#) Welcome Back, User Current Conference: Conference ============================== {{lineCtrl.name}} {{line.name}} {{line.description}} * Time: {{line.time}} * Number of People: {{line.numPeople}} * [Card link](#) `enter code here` //app.js angular.module('inLineClient', []) .controller('lineController', function($scope) { vm = this; vm.name = "arvind"; vm.linesList = [ { name: 'Lunch', description: 'Lunch time! Come down for some pizza, french fries and drinks!\nPrice: $10 for Pizza, Fries, and a Soft Drink', time: new Date('October 21, 2017 12:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'VR Cave', description: 'Reserve your slot to play in our VR Cave', time: new Date('October 22, 2017 0:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Breakfast', description: 'Good Morning! Bagels and Cream Cheese with Coffee, Tea and Hot Chocolate this morning!', time: new Date('October 22, 2017 8:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Intro to RESTful APIs by RBC', description: 'Learn about how to create REST APIs for your web application, brought to you by RBC', time: new Date('October 21, 2017 17:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null }, { name: 'Contest Programming', description: 'Get your programming on by competing among different hackers to win a prize!', time: new Date('October 22, 2017 0:30 EST-05:00').toLocaleTimeString('en-US'), numPeople: null } ]; }); ``` [here is plunker](https://plnkr.co/edit/QTdxUFCIiumc2jA1sNXG?p=preview) <https://plnkr.co/edit/QTdxUFCIiumc2jA1sNXG?p=preview> Upvotes: 0
2018/03/20
353
1,263
<issue_start>username_0: Below code was working fine on Production from last few months. Recently it started breaking. Yesterday it was giving HTTP error issue for `file_get_contents` function. Today, On Execution it shows Undefined Offset error. I am not sure what has changed for Finance Google API. ``` public function getJPYtoUSDExchangeRate(){ $from = 'JPY'; $to = 'USD'; $amount = 1; $data = file_get_contents("https://finance.google.com/finance/converter?a=$amount&from=$from&to=$to"); preg_match("/(.\*)<\/span>/",$data, $converted); $converted = preg\_replace("/[^0-9.]/", "", $converted[1][0]); return number\_format(round($converted, 3),2); } ```<issue_comment>username_1: The problem is with the link, google updated the api link recently, and I found success once on checking 10 times to the existing link. Try changing to this link <https://www.google.com/finance/converter> see this <https://www.techbuy.in/google-finance-api-currency-converter-not-working-updated-link-check-currency-converter/> Upvotes: 0 <issue_comment>username_1: Finally I found the solution for this with the updated google URL for currency converter <https://finance.google.com/bctzjpnsun/converter> Thanks Upvotes: 1
2018/03/20
2,441
8,358
<issue_start>username_0: I want to ellaborate a regex that covers the following scenarios: The searched word is "potato". **It matches if the user searches for "potaot" (He typed quickly and the "o" finger was faster than the "t" finger. (done)** **It matches if the user searches for "ptato" (He forgot one letter). (done)** With my knowlege of regex the further I could go was: ``` (?=[potato]{5,6})p?o?t?a?t?o? ``` The problem with this is that it matches reversed words like "otatop", which is a little clever but a little bezarre, and "ooooo", which is totally undesirable. So not I describe what I don't want. **I don't want repeated letters to match "ooooo", "ooopp" and etc. (unable)** By the way I'm using C#.<issue_comment>username_1: The weapon of choice here is a similarity (or distance) matching algorithm. [Compare similarity algorithms](https://stackoverflow.com/questions/9842188/compare-similarity-algorithms) gives a good overview of the most common distance metrics/algorithms. The problem is that there is no single best metric. The choice depends, e.g. on input type, accuracy requirements, speed, resources availability, etc. Nevertheless, [comparing algorithms can be messy](https://www.cs.cmu.edu/~cburch/pgss97/slides/0715-compare.html). Two of the most commonly suggested metrics are the Levenshtein distance and Jaro-Winkler: * Levenshtein distance, which provides a similarity measure between two strings, is arguably less forgiving, and more intuitive to understand than some other metrics. (There are modified versions of the Levenshtein distance like the Damerau-Levenshtein distance, which includes transpositions, that could be even more appropriate to your use case.) * [Some](https://stackoverflow.com/questions/13636848/is-it-possible-to-do-fuzzy-match-merge-with-python-pandas/37505425#37505425) claim the Jaro-Winkler, which provides a similarity measure between two strings allowing for character transpositions to a degree adjusting the weighting for common prefixes, distance is "one of the most performant and accurate approximate string matching algorithms currently available [Cohen, et al.], [Winkler]." However, the choice still depends very much on the use case and one cannot draw general conclusions from specific studies, e.g. name-matching [Cohen, et al. 2003](http://dc-pubs.dbs.uni-leipzig.de/files/Cohen2003Acomparisonofstringdistance.pdf). You can find plenty of packages on NuGet that offer you a variety of similarity algorithms ([a](https://www.nuget.org/packages?q=Levenshtein&prerel=false), [b](https://www.nuget.org/packages?q=jaro-winkler&prerel=false), [c](https://www.nuget.org/packages?q=string%20similarity)), [fuzzy matches](https://www.nuget.org/packages?q=fuzzy%20string), phonetic, etc. to add this feature to your site or app. Fuzzy matching can also be used directly on the database layer. An [implementation of the Levenshtein distance](https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance) can be found for most database systems (e.g. [MySQL](https://stackoverflow.com/questions/4671378/levenshtein-mysql-php), [SQL Server](https://www.izenda.com/blog/integrating-independent-sql-databases-with-levenshtein-distance/)) or is already built-in ([Oracle](https://docs.oracle.com/cd/E18283_01/appdev.112/e16760/u_match.htm), [PostgreSQL](https://www.postgresql.org/docs/8.3/static/fuzzystrmatch.html)). Depending on your exact use case, you could also use a cloud-based solution (i.e. use a microservice based on [AWS](https://aws.amazon.com/blogs/database/creating-a-simple-autocompletion-service-part-one-of-two/), [Azure](https://www.c-sharpcorner.com/article/cognitive-service-bing-autosuggest-api-using-uwp-with-azure-xaml-and-c-sharp/), etc. or [roll-your-own](https://stackoverflow.com/a/6710147/8291949)) to get autosuggest-like fuzzy search/matching. Upvotes: 3 [selected_answer]<issue_comment>username_2: Don't use regular expressions. The best solution is the simple one. There are only eleven possible inexact matches, so just enumerate them: ``` List inexactMatches = new List { "otato", "ptato", "poato", "potto", "potao", "potat", "optato", "ptoato", "poatto", "pottao", "potaot"}; ... bool hasInexactMatch = inexactMatches.Contains(whatever); ``` It took less than a minute to type those out; use the easy specific solution rather than trying to do some crazy regular expression that's going to take you hours to find and debug. If you're going to insist on using a regular expression, here's one that works: ``` otato|ptato|poato|potto|potao|potat|optato|ptoato|poatto|pottao|potaot ``` Again: simpler is better. --- Now, one might suppose that you want to solve this problem for more words than "potato". In that case, you might have said so -- but regardless, we can come up with some easy solutions. First, let's enumerate all the strings that have an omission of one letter from a target string. Strings are `IEnumerable` so let's solve the general problem: ``` static IEnumerable OmitAt(this IEnumerable items, int i) => items.Take(i).Concat(items.Skip(i + 1)); ``` That's a bit gross enumerating the sequence twice but I'm not going to stress about it. Now let's make a specific version for strings: ``` static IEnumerable Omits(this string s) => Enumerable .Range(0, s.Length) .Select(i => new string(s.OmitAt(i).ToArray())); ``` Great. Now we can say `"frob".Omits()` and get back `rob, fob, frb, fro`. Now let's do the swaps. Again, solve the general problem first: ``` static void Swap(ref T x, ref T y) { T t = x; x = y; y = t; } static T[] SwapAt(this IEnumerable items, int i) { T[] newItems = items.ToArray(); Swap(ref newItems[i], ref newItems[i + 1]); return newItems; } ``` And now we can solve it for strings: ``` static IEnumerable Swaps(this string s) => Enumerable .Range(0, s.Length - 1) .Select(i => new string(s.SwapAt(i))); ``` And now we're done: ``` string source = "potato"; string target = whatever; bool match = source.Swaps().Contains(target) || source.Omits().Contains(target); ``` Easy peasy. **Solve general problems using simple, straightforward, correct algorithms that can be composed into larger solutions**. None of my algorithms there was more than three lines long and they can easily be seen to be correct. Upvotes: 3 <issue_comment>username_3: It's easiest to do it this way: ``` static void Main(string[] args) { string correctWord = "Potato"; string incorrectSwappedWord = "potaot"; string incorrectOneLetter = "ptato"; // Returns true bool swapped = SwappedLettersMatch(correctWord, incorrectSwappedWord); // Returns true bool oneLetter = OneLetterOffMatch(correctWord, incorrectOneLetter); } public static bool OneLetterOffMatch(string str, string input) { int ndx = 0; str = str.ToLower(); input = input.ToLower(); if (string.IsNullOrWhiteSpace(str) || string.IsNullOrWhiteSpace(input)) { return false; } while (ndx < str.Length) { string newStr = str.Remove(ndx, 1); if (input == newStr) { return true; } ndx++; } return false; } public static bool SwappedLettersMatch(string str, string input) { if (string.IsNullOrWhiteSpace(str) || string.IsNullOrWhiteSpace(input)) { return false; } if (str.Length != input.Length) { return false; } str = str.ToLower(); input = input.ToLower(); int ndx = 0; while (ndx < str.Length) { if (ndx == str.Length - 1) { return false; } string newStr = str[ndx + 1].ToString() + str[ndx]; if (ndx > 0) { newStr = str.Substring(0, ndx) + newStr; } if (str.Length > ndx + 2) { newStr = newStr + str.Substring(ndx + 2); } if (newStr == input) { return true; } ndx++; } return false; } ``` `OneLetterOffMatch` will return true is there is a match that's off by just one character missing. `SwappedLettersMatch` will return true is there is a match when just two of the letters are swapped. These functions are case-insenstive, but if you want a case-sensitive version, just remove the calls to `.ToLower()`. Upvotes: 0
2018/03/20
457
1,555
<issue_start>username_0: Assume I have the following object: ``` var jsonObj = { "response":{ "result":{ "status":{ "name": "Eric" } } } } ``` And now i'd like to dynamically access a nested property: ``` jsonKey = "response.result.status.name"; console.log("the status is: " + jsonObj.jsonKey); //I cannot call jsonObj.jsonKey here ``` Is there any way to achieve this?<issue_comment>username_1: You cannot access a deeply nested property as simple as you expect. Instead you need to use the `obj[propertyNameAsString]` syntax to dive deeper into the response one by one. This would be one way of getting there: ```js let response = { "response": { "method": "GetStatus", "module": "Module", "data": null, "result": { "status": { "name": "Eric" }, "id": 1 }, "result_code": { "error_code": 0 } } } let keyString = "response.result.status.name" let keyArray = keyString.split('.'); // [ "response", "result", "status", "name" ] var result = response; for (key of keyArray) { result = result[key] } console.log(result) ``` **Please be aware that this is not failsafe against cases where one of those strings in `keyArray` does not exist as a property on the preceding object.** Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` You can do like this something['bar'] ``` > > Where bar is your variable that has been converted to string, in our case: > > > ``` jsonObj[`${jsonKey}`] ``` Upvotes: 0
2018/03/20
1,889
5,185
<issue_start>username_0: I am having a problem trying to solve an equation in programming. Imagine I have this line of code: ``` Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10; ``` Given x = 1000, the result is 320. Now, how can I solve this equation given a result? Imagine given the result 320 I want to get the **minimum** integer value of x that resolves that line of code. ``` /*320 =*/ Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10; ``` I am having some hard time because of the Math.Round. Even thought that expression is a linear equation, the Math.Round makes way more solutions than one for x, so I want the **minimum** integer value for my solution. **Note that x is a integer and if I set x = 999 the result is still 320.** If I keep lowering x I can see that 984 (atleast in Chrome 64.0.3282.186) is the correct answer in this case, because is the lowest value of x equals to 320 in that expression/programming line.<issue_comment>username_1: Solving the equation with the Math.round just introduces boundary conditions. If: ``` Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10 = 320 ``` Then: ``` Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) = 32 ``` By dividing both sides by 10. Now you have: ``` Math.round(expression) = 32 ``` Which can be expressed as an inequality statement: ``` 31.5 < expression < 32.4999.. ``` The expression being equal to 31.5 represents one boundary, and the expression being equal to 32.499.. represents the other boundary.So solving for the boundaries would require solving for: ``` expression = 31.5 and expression = 32.49999... ((x / 5) + Math.pow(x / 25, 1.3))/10 = 31.5 and ((x / 5) + Math.pow(x / 25, 1.3))/10 = 32.4999 ``` Solving these two for x will give you the range of valid values for x. Now that's just algebra which I'm not going to do :) Upvotes: 3 [selected_answer]<issue_comment>username_2: I guess the most reliable way that works (albeit somewhat naive) is to loop through all valid numbers and check the predicate. ``` function getMinimumIntegerSolution(func, expectedResult){ for(let i = 0 /*Or Number.MIN_SAFE_INTEGER for -ves*/; i< Number.MAX_SAFE_INTEGER ; i++ ) { if(func(i) === expectedResult) return i; } } ``` Now ``` getMinimumIntegerSolution((x) => Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10 , 320) ``` This returns what you expect, 984 Upvotes: 1 <issue_comment>username_3: Because the function defined by ``` f(n) = Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10 ``` is monotonous (in this case, increasing), you can do a binary search. Note that I wrote the following code originally in Java, and it is syntactically incorrect in Javascript, but should hopefully be straightforward to translate into the latter. ``` var x0 = 0; var x1 = 1e6; var Y = 320d; var epsilon = 10d; var x = (x1 - x0) / 2d; var y = 0; while (Math.abs(Y - (y = f(x))) > epsilon) { if (y > Y) { x = (x - x0) / 2d; } else { x = (x1 - x) / 2d; } // System.out.println(y + " " + x); } while (f(x) < Y) ++x; // System.out.println(Math.round(x) + " " + f(x)); ``` Running it on my computer leaving the `System.out.println` uncommented: ``` 490250.0 250000.0 208490.0 125000.0 89370.0 62500.0 38640.0 31250.0 16870.0 15625.0 7440.0 7812.5 3310.0 3906.25 1490.0 1953.125 680.0 976.5625 984 320.0 ``` * Note that the last loop incrementing `x` is guaranteed to complete in less than `epsilon` steps. * The values of `x0`, `x1` and `epsilon` can be tweaked to provide better bounds for your problem. * This algorithm will fail if the value of `epsilon` is "too small", because of the rounding happening in `f`. * The complexity of this solution is `O(log2(x1 - x0))`. Upvotes: 0 <issue_comment>username_4: In addition to @username_1 answer. If you rearrange the final equation you get a high-order polynomial (13th degree) which is difficult to solve algebraically. You can use numerical methods as [Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method). For numerical methods in JavaScript you can use [numeric.js](http://www.numericjs.com). You also need to solve only for the lower bound (31.5) in order to find the lowest integer x because the function is monotonic increasing. See also this [post](https://stackoverflow.com/questions/25753546/solving-a-trig-equation-numerically-with-in-browser-js) on numerical equation solving in JavaScript. Here is a solution using Newton's method. It uses 0 as initial guess. It only takes five iterations for getting the minimum integer solution. ```js var result = 320; var d = result - 5; function func(x) { return x / 5 + 0.0152292 * Math.pow(x, 1.3) - d; } function deriv(x) { return 0.2 + 0.019798 * Math.pow(x, 0.3); } var epsilon = 0.001; //termination condition function newton(guess) { var approx = guess - func(guess) / deriv(guess); if (Math.abs(guess - approx) > epsilon) { console.log("Guess: " + guess); return newton(approx); } else { //round solution up for minimum integer return Math.ceil(approx); } } console.log("Minimum integer: " + newton(0)); ``` Upvotes: 0
2018/03/20
2,980
9,045
<issue_start>username_0: Hi im having trouble with this Cash Register program im writing. Specifically the output2 method. Im attempting to to find a way to output the specific dollar amounts the user will receive in change without writing it as: system.out.println("Your change will be "+hundred+" on hundred dollar bills "+fifty+" fifty dollar bills ETC"); But instead include the dollar value if it fits with the change the user will receive. I hope this wasnt too confusing to read. ``` int ranNum, hundred, fifty, twenty, ten, five, one, quarter, dime, nickel, penny; double original, discount, savings, salesprice, tax, total, payment, change, quarterV = .25, dimeV = .10, //V as in value nickelV = .05, pennyV = .01; DecimalFormat percent = new DecimalFormat("0%"); DecimalFormat money = new DecimalFormat("$0.00"); public void input() { System.out.println("Hello, this program will ask you for a price of an item you would like to purchase"); System.out.println("and return a random discount from 5-75 (multiple of 5). Then return the following:"); System.out.println("original price, discount percent, discount amount, sales price, tax and total price with 7% tax.\n"); System.out.println("Please give me the price of an item you would like to purchase"); original = scan.nextDouble(); scan.nextLine(); } public void calculations() { //This will be used to find the random discount given to the user: ranNum = random.nextInt(15)+1; discount = ((ranNum*5)*.10)*.10; //This will be used to find the amount the user will save: savings = (discount*original); //This will be used to find the salesprice of the item being purchased: salesprice = original - savings; //This will be used to find the total price of the item after 7% tax deductions tax = (salesprice*7)/100; //This will be used to find the final total the customer must pay total = salesprice + tax; } public void change() { change = payment - total; hundred = (int) Math.floor(change/100); fifty = (int) Math.floor((change - hundred * 100)/50); twenty = (int) Math.floor((change - hundred * 100 - fifty * 50) / 20); ten = (int) Math.floor((change - hundred * 100 - fifty * 50 - twenty * 20) / 10); five = (int) Math.floor((change - hundred * 100 - fifty * 50 - twenty * 20 - ten * 10) / 5); one = (int) Math.floor((change - hundred * 100 - fifty * 50 - twenty * 20 - ten * 10 - five * 5) / 1); quarter = (int) Math.floor((change - hundred * 100 - fifty * 50 - twenty * 20 - ten * 10 - five * 5 - one * 1) / quarterV); dime = (int) Math.floor((change - hundred * 100 - fifty * 50 - twenty * 20 - ten * 10 - five * 5 - one * 1 - quarter * quarterV) / dimeV); nickel = (int) Math.floor((change - hundred * 100 - fifty * 50 - twenty * 20 - ten * 10 - five * 5 - one * 1 - quarter * quarterV - dime * dimeV) / nickelV); penny = (int) Math.floor((change - hundred * 100 - fifty * 50 - twenty * 20 - ten * 10 - five * 5 - one * 1 - quarter * quarterV - dime * dimeV - nickel * nickelV) / penny); } public void output1() { System.out.println("The original price of your item was "+money.format(original)); System.out.println("You will be granted a " +percent.format(discount)+ " discount on your purchase."); System.out.println("Your discount amount (amount you are saving) is "+money.format(savings)+"."); System.out.println("The sales price of your item is "+money.format(salesprice)); System.out.println("The 7% tax payment will come out to be "+money.format(tax)); System.out.println("Thus your total will be "+money.format(total)+"\n"); System.out.println("How much money are you using to purchase your item?"); payment = scan.nextDouble(); scan.nextLine(); } public void output2() { System.out.println("Your change is"); if (change>=100) { System.out.println(hundred+" one hundred dollar bills"); } else { if (change>=50) { System.out.println(fifty+" fifty dollar bills"); } else { if (change>=20) { System.out.println(twenty+" twenty dollar bills"); } else { if (change>=5) { System.out.println(five+" five dollar bills"); } else { System.out.println(one+" one dollar bills"); } } } } } public void run() { input(); calculations(); output1(); change(); output2(); } public static void main(String[] args) { CashRegister phill = new CashRegister(); phill.run(); } ``` }<issue_comment>username_1: Solving the equation with the Math.round just introduces boundary conditions. If: ``` Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10 = 320 ``` Then: ``` Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) = 32 ``` By dividing both sides by 10. Now you have: ``` Math.round(expression) = 32 ``` Which can be expressed as an inequality statement: ``` 31.5 < expression < 32.4999.. ``` The expression being equal to 31.5 represents one boundary, and the expression being equal to 32.499.. represents the other boundary.So solving for the boundaries would require solving for: ``` expression = 31.5 and expression = 32.49999... ((x / 5) + Math.pow(x / 25, 1.3))/10 = 31.5 and ((x / 5) + Math.pow(x / 25, 1.3))/10 = 32.4999 ``` Solving these two for x will give you the range of valid values for x. Now that's just algebra which I'm not going to do :) Upvotes: 3 [selected_answer]<issue_comment>username_2: I guess the most reliable way that works (albeit somewhat naive) is to loop through all valid numbers and check the predicate. ``` function getMinimumIntegerSolution(func, expectedResult){ for(let i = 0 /*Or Number.MIN_SAFE_INTEGER for -ves*/; i< Number.MAX_SAFE_INTEGER ; i++ ) { if(func(i) === expectedResult) return i; } } ``` Now ``` getMinimumIntegerSolution((x) => Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10 , 320) ``` This returns what you expect, 984 Upvotes: 1 <issue_comment>username_3: Because the function defined by ``` f(n) = Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10 ``` is monotonous (in this case, increasing), you can do a binary search. Note that I wrote the following code originally in Java, and it is syntactically incorrect in Javascript, but should hopefully be straightforward to translate into the latter. ``` var x0 = 0; var x1 = 1e6; var Y = 320d; var epsilon = 10d; var x = (x1 - x0) / 2d; var y = 0; while (Math.abs(Y - (y = f(x))) > epsilon) { if (y > Y) { x = (x - x0) / 2d; } else { x = (x1 - x) / 2d; } // System.out.println(y + " " + x); } while (f(x) < Y) ++x; // System.out.println(Math.round(x) + " " + f(x)); ``` Running it on my computer leaving the `System.out.println` uncommented: ``` 490250.0 250000.0 208490.0 125000.0 89370.0 62500.0 38640.0 31250.0 16870.0 15625.0 7440.0 7812.5 3310.0 3906.25 1490.0 1953.125 680.0 976.5625 984 320.0 ``` * Note that the last loop incrementing `x` is guaranteed to complete in less than `epsilon` steps. * The values of `x0`, `x1` and `epsilon` can be tweaked to provide better bounds for your problem. * This algorithm will fail if the value of `epsilon` is "too small", because of the rounding happening in `f`. * The complexity of this solution is `O(log2(x1 - x0))`. Upvotes: 0 <issue_comment>username_4: In addition to @username_1 answer. If you rearrange the final equation you get a high-order polynomial (13th degree) which is difficult to solve algebraically. You can use numerical methods as [Newton's method](http://en.wikipedia.org/wiki/Newton%27s_method). For numerical methods in JavaScript you can use [numeric.js](http://www.numericjs.com). You also need to solve only for the lower bound (31.5) in order to find the lowest integer x because the function is monotonic increasing. See also this [post](https://stackoverflow.com/questions/25753546/solving-a-trig-equation-numerically-with-in-browser-js) on numerical equation solving in JavaScript. Here is a solution using Newton's method. It uses 0 as initial guess. It only takes five iterations for getting the minimum integer solution. ```js var result = 320; var d = result - 5; function func(x) { return x / 5 + 0.0152292 * Math.pow(x, 1.3) - d; } function deriv(x) { return 0.2 + 0.019798 * Math.pow(x, 0.3); } var epsilon = 0.001; //termination condition function newton(guess) { var approx = guess - func(guess) / deriv(guess); if (Math.abs(guess - approx) > epsilon) { console.log("Guess: " + guess); return newton(approx); } else { //round solution up for minimum integer return Math.ceil(approx); } } console.log("Minimum integer: " + newton(0)); ``` Upvotes: 0
2018/03/20
1,152
4,650
<issue_start>username_0: I have written a function on firebase that downloads an image (base64) from firebase storage and sends that as response to the user: ``` const functions = require('firebase-functions'); import os from 'os'; import path from 'path'; const storage = require('firebase-admin').storage().bucket(); export default functions.https.onRequest((req, res) => { const name = req.query.name; let destination = path.join(os.tmpdir(), 'image-randomNumber'); return storage.file('postPictures/' + name).download({ destination }).then(() => { res.set({ 'Content-Type': 'image/jpeg' }); return res.status(200).sendFile(destination); }); }); ``` My client calls that function multiple times *after* one another (in series) to load a range of images for display, ca. 20, of an average size of 4KB. After 10 or so pictures have been loaded (amount varies), all other pictures fail. The reason is that my function does not respond correctly, and the firebase console shows me that my function threw an error: [![enter image description here](https://i.stack.imgur.com/1Y9Cw.png)](https://i.stack.imgur.com/1Y9Cw.png) The above image shows that 1. A request to the function (called "PostPictureView") suceeds 2. Afterwards, three requests to the controller fail 3. In the end, after executing a new request to the "UserLogin"-function, also that fails. The response given to the client is the default "Error: Could not handle request". After waiting a few seconds, all requests get handled again as they are supposed to be. My best guesses: * The project is on free tier, maybe google is throttling something? (I did not hit any limits afaik) * Is there a limit of messages the google firebase console can handle? * Could the tmpdir from the functions-app run low? I never delete the temporary files so far, but would expect that either google deletes them automatically, or warns me in a different way that the space is running low. Does someone know an alternative way to receive the error messages, or has experienced similar issues? (As Firebase Functions is still in Beta, it could also be an error from google) Btw: Downloading the image from the client (android app, react-native) directly is not possible, because I will use the function to check for access permissions later. The problem is reproducable for me.<issue_comment>username_1: In Cloud Functions, the /tmp directory is [backed by memory](https://cloud.google.com/functions/pricing#local_disk). So, every file you download there is effectively taking up memory on the server instance that ran the function. Cloud Functions may reuses server instances for repeated calls to the same function. This means your function is downloading another file (to that same instance) with each invocation. Since the names of the files are different each time, you are accumulating files in /tmp that each occupy memory. At some point, this server instance is going to run out of memory with all these files in /tmp. This is bad. It's a best practice to [always clean up files after you're done with them](https://cloud.google.com/functions/docs/bestpractices/tips#always_delete_temporary_files). Better yet, if you can stream the file content from Cloud Storage to the client, you'll use even less memory ([and be billed even less for the memory-hours you use](https://cloud.google.com/functions/pricing#compute_time)). Upvotes: 1 <issue_comment>username_2: After some more research, I've found the solution: The Firebase Console seems to not show all error information. For detailed information to your functions, and errors that might be omitted in the Firebase Console, check out the [website from google cloud functions](https://console.cloud.google.com/functions/). [![enter image description here](https://i.stack.imgur.com/oibC4.png)](https://i.stack.imgur.com/oibC4.png) There I saw: The memory (as suggested by <NAME>) usage never ran over 80MB (limit of 256MB) and never shut the server down. Moreover, there is a DNS resolution limit for the free tier, that my application hit. The [documentation](https://cloud.google.com/functions/quotas#rate_limits) points to a limit of `DNS resolutions: 40,000 per 100 seconds`. In my case, this limit was never hit - firebase counts a total executions of roundabout 8000 - but it seems there is a **lower, undocumented limit** for the free tier. After upgrading my account (I started the trial that GCP offers, so actually not paying anything) and linking the project to the billing account, everything works perfectly. Upvotes: 1 [selected_answer]
2018/03/20
701
2,548
<issue_start>username_0: I have a xlsm workbook and with 2 sheets, I call it as workbook 1, sheet 1 is visible, sheet 2 is set as xlsheetveryhidden. And then vbe password setted. Now the situation should be no one can unhide sheet 2 manaually, right? Now I open another workbook, I call it as workbook 2, open vbe at workbook 2, and simply type the following codes and aim to workbook 1, sheet 2 is visble: ```html Sub InvisibleSheet2Fails() Sheets(2).Visible = xlSheetVisible End Sub ``` My question is: How can I unhide my sheet 2 ONLY with workbook 1 vbe password? workbook 2 doesn't know the workbook 1 vbe password but can easily bypass xlsheetveryhidden setting. Thank you very much! Lawrence<issue_comment>username_1: Honestly and sincerely, I have not found an office file that could not be hacked. Besides the tools available for purchase used to do just that, you can also find them for free as well. If you're really serious about protecting these files, you could trying Encrypting them and allowing only those who have the certificates locally, access them. See [Information Rights Management in Office](https://support.office.com/en-us/article/information-rights-management-in-office-c7a70797-6b1e-493f-acf7-92a39b85e30c) > > "If you've gotten a file permission error when trying to view a > document or email, then you have come across Information Rights > Management (IRM). You can use IRM to restrict permission to content in > documents, workbooks, and presentations with Office." > > > Upvotes: 0 <issue_comment>username_2: No security is 100% safe. If your threat model is a power user that knows how to bring up the VBE and you don't want them fiddling around, you can at least protect the workbook structure with a password. ``` ThisWorkbook.Protect "password", Structure:=true ``` Do this from the *immediate pane*, don't put the password anywhere in the code - VBE password protection on the other hand (you seem to be conflating VBA project protection and workbook structure protection), is absolutely [easily defeated](https://stackoverflow.com/a/27508116/1188513), in no time; if you've written the password anywhere in the code, consider it compromised. Use a good, strong password, and if you're using the latest version of Excel and someone manages to unprotect the workbook, they deserve to tweak it. If your threat model is a MI6 agent, if they get to the file in the first place, you already lost: put the file somewhere safe, implement good network security. Upvotes: 3 [selected_answer]
2018/03/20
559
2,009
<issue_start>username_0: How can I restrict access to admin login page based on IP address in LARAVEL? I want to set a permission to the admin login page to a single IP Address.<issue_comment>username_1: you can use `Request::ip();` and check it in middleware.. below is basic poc middleware ``` class AdminAccessCheck { public function handle($request, Closure $next) { $ip = $request->ip(); if ($ip === config('admin.ip')) { return $next($request); } return response()->error(); } } ``` kernel.php ``` protected $routeMiddleware = [ ... 'admin.ip_check' => \App\Http\Middleware\AdminAccessCheck::class, ]; ``` web.php ``` Route::middleware(['admin.ip_check'])->group(function() { // }); ``` If you prefer package, you can checkout this repo .. [Firewall](https://github.com/antonioribeiro/firewall) Upvotes: 3 <issue_comment>username_2: Create a middleware ``` php artisan make:middleware IpMiddleware ``` Code: ``` php namespace App\Http\Middleware; use Closure; class IpMiddleware { public function handle($request, Closure $next) { if ($request-ip() != "192.168.0.155") { // here instead of checking a single ip address we can do collection of ips //address in constant file and check with in_array function return redirect('home'); } return $next($request); } } ``` Register the Middleware in `app/Http/Kernel.php` file ``` protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'ipcheck' => \App\Http\Middleware\IpMiddleware::class, ]; ``` then apply middelware to routes ``` Route::get('/', ['middleware' => ['ipcheck'], function () { // your routes here }]); ``` Upvotes: 1
2018/03/20
1,828
6,201
<issue_start>username_0: I've been having an issue with some code in a project I'm doing at school. I have an array of length 4, where each element of the array is an integer. The values of the integers are determined through multiplying Math.random() by the length of another array. The goal of my code is to find some way of checking whether any of the elements are equal to each other, and if they are then I would want to "reset" (redefine) them until they aren't equal. Here's what I just described, albeit in a very basic form: ``` var originalArray=[a, b, c, d, e, f, g]; var or1=Math.floor(Math.random() * originalArray.length); var or2=Math.floor(Math.random() * originalArray.length); var or3=Math.floor(Math.random() * originalArray.length); var or4=Math.floor(Math.random() * originalArray.length); var numArray=[or1, or2, or3, or4]; function resetData(){ or1=Math.floor(Math.random() * originalArray.length); or2=Math.floor(Math.random() * originalArray.length); or3=Math.floor(Math.random() * originalArray.length); or4=Math.floor(Math.random() * originalArray.length); numArray=[or1, or2, or3, or4]; } ``` I then have another function, at the beginning of which I want to run resetData. However, if any of the elements are equal to each other then I want it to run again until none of them are. ``` function startOperations(){ resetData(); //insert other code here } ``` I'm stuck on what I should do to make it only reset under the previously-mentioned conditions. My initial idea was to do a for-loop, kind of like this: ``` for(i=0; i ``` But I now realize that this won't work, since this only checks if the elements next to each other are equal. So I tried just an if-statement: if(songNumArray[0]==songNumArray[1]||songNumArray[0]==songNumArray[2]||songNumArray[0]==songNumArray[3]){ resetData(); } This doesn't work either, of course, which is why I'm here. Does anyone on here have an idea of what I could do?<issue_comment>username_1: Just use another for loop to iterate again. Something like this: ``` for(i=0; i ``` Upvotes: 0 <issue_comment>username_2: You could use a Set like this to look for duplicates: ``` let dupes; do { let set = new Set(); dupes = false; for (let i = 0; i < songNumArray.length; ++i) { if (set.has(songNumArray[i]) { resetData(); dupes = true; break; } else { set.add(songNumArray[i]); } } } while (dupes); ``` Upvotes: 0 <issue_comment>username_3: I would use nested for-loops. That way, we can cross reference all elements of the array with each other. ``` function newData() { for (var i = 0; i < originalArray.length; i++) { for (var j = 0; j < originalArray.length; j++) { if (i != j && numArray[i] == numArray[j]) { console.log('find'); numArray[i] = Math.floor(Math.random() * originalArray.length); i = 0; } } } } ``` If you look at the if-statement, you can see I first check to make sure it doesn't equal j, since a number will always equal itself, and we don't want to cross reference the same elements in the array. Next, I check if they're the same. If they are, I set i to 0. This acts similar to recursion, it "resets" or "re-runs" the loop. If a number gets set to an already existing number, it will go through the if statement again, modifying it until it meets the criteria. Hope this helps! Upvotes: 0 <issue_comment>username_4: Rather than declaring variables for each element of the array first and putting them into an array later, I'd suggest simply using a array to start with - that way you can use the array methods. You also don't need to reset *all* of the elements in the array and retry until something works - it would be more elegant to try to generate new elements and insert them only if they pass. For example: ```js function createArrayWithoutDuplicates(highestValMinusOne, length) { const highestVal = highestValMinusOne + 1; const arr = []; while (arr.length < length) { let val; do { val = Math.floor(Math.random() * highestVal); } while (arr.includes(val)); arr.push(val); } return arr; } console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); ``` Upvotes: 1 <issue_comment>username_5: You can do it with 2 for loops where first one is from first element to second last element and the second loop always starts with the next element that of the first loop and ends with last element of the array. ``` for(i = 0; i < songNumArray.length - 1; i++){ for(j = i + 1; j < songNumArray.length; j++) { if(songNumArray[i] == songNumArray[j]){ resetData(); } } } ``` Upvotes: 0 <issue_comment>username_6: I've added a `getUniqueNumber` function that generates a unique number if it's a duplicate. Commented code below; ```js var originalArray = [1, 2, 3, 4, 5, 6, 7]; var or1 = Math.floor(Math.random() * originalArray.length); var or2 = Math.floor(Math.random() * originalArray.length); var or3 = Math.floor(Math.random() * originalArray.length); var or4 = Math.floor(Math.random() * originalArray.length); var numArray = [or1, or2, or3, or4]; function getUniqueNumber(index) { var val = numArray[index]; // check if subsequent values are equal to current value. // if not return current value. // no need to check previous values as they are already unique. if (numArray.indexOf(val, index + 1) === -1) return val; // repeat until unique number is generated while (true) { val = Math.floor(Math.random() * originalArray.length); if (numArray.indexOf(val) === -1) return val; } } function resetData() { for (let i = 0; i < 4; i++) { numArray[i] = getUniqueNumber(i); } } function startOperations() { console.log("before: " + numArray); resetData(); console.log("after: " + numArray); //insert other code here } startOperations(); ``` Upvotes: 0
2018/03/20
1,594
5,442
<issue_start>username_0: I really don't know why this is not working. data1 and data2 will be sent to my php form but data3 will not no matter what i set it to be. Can anyone point out what is wrong that I may be simply overlooking. ``` function flap(span) { var id1 = span.getAttribute('data-id1'); var id2 = span.getAttribute('data-id2'); var lop = id2.slice(8, 1000); var lip = id2.slice(0, 8); var str = lop; var n = str.lastIndexOf("/"); var res = str.slice(0, n); var mac = res; var red = mac.lastIndexOf("/"); var rem = red+1; var ret = mac.slice(rem, 1000); var slap = ret; $.ajax({ url:'controlmysite/userfiles.php', type:'POST', data:{ data1: id1, data3: slap, data2: lip + res, }, success: function(filesDirectory1){ $('#filesDirectory').html(filesDirectory1); }});} ``` I changed data3 to many different things; i even set it to id1, lip, res, and ret. I swapped positions with data1 and data2, but for some reason data3 simply will not send. Please someone point out what I am obviously overlooking. Thanks for any help.<issue_comment>username_1: Just use another for loop to iterate again. Something like this: ``` for(i=0; i ``` Upvotes: 0 <issue_comment>username_2: You could use a Set like this to look for duplicates: ``` let dupes; do { let set = new Set(); dupes = false; for (let i = 0; i < songNumArray.length; ++i) { if (set.has(songNumArray[i]) { resetData(); dupes = true; break; } else { set.add(songNumArray[i]); } } } while (dupes); ``` Upvotes: 0 <issue_comment>username_3: I would use nested for-loops. That way, we can cross reference all elements of the array with each other. ``` function newData() { for (var i = 0; i < originalArray.length; i++) { for (var j = 0; j < originalArray.length; j++) { if (i != j && numArray[i] == numArray[j]) { console.log('find'); numArray[i] = Math.floor(Math.random() * originalArray.length); i = 0; } } } } ``` If you look at the if-statement, you can see I first check to make sure it doesn't equal j, since a number will always equal itself, and we don't want to cross reference the same elements in the array. Next, I check if they're the same. If they are, I set i to 0. This acts similar to recursion, it "resets" or "re-runs" the loop. If a number gets set to an already existing number, it will go through the if statement again, modifying it until it meets the criteria. Hope this helps! Upvotes: 0 <issue_comment>username_4: Rather than declaring variables for each element of the array first and putting them into an array later, I'd suggest simply using a array to start with - that way you can use the array methods. You also don't need to reset *all* of the elements in the array and retry until something works - it would be more elegant to try to generate new elements and insert them only if they pass. For example: ```js function createArrayWithoutDuplicates(highestValMinusOne, length) { const highestVal = highestValMinusOne + 1; const arr = []; while (arr.length < length) { let val; do { val = Math.floor(Math.random() * highestVal); } while (arr.includes(val)); arr.push(val); } return arr; } console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); console.log(createArrayWithoutDuplicates(10, 7)); ``` Upvotes: 1 <issue_comment>username_5: You can do it with 2 for loops where first one is from first element to second last element and the second loop always starts with the next element that of the first loop and ends with last element of the array. ``` for(i = 0; i < songNumArray.length - 1; i++){ for(j = i + 1; j < songNumArray.length; j++) { if(songNumArray[i] == songNumArray[j]){ resetData(); } } } ``` Upvotes: 0 <issue_comment>username_6: I've added a `getUniqueNumber` function that generates a unique number if it's a duplicate. Commented code below; ```js var originalArray = [1, 2, 3, 4, 5, 6, 7]; var or1 = Math.floor(Math.random() * originalArray.length); var or2 = Math.floor(Math.random() * originalArray.length); var or3 = Math.floor(Math.random() * originalArray.length); var or4 = Math.floor(Math.random() * originalArray.length); var numArray = [or1, or2, or3, or4]; function getUniqueNumber(index) { var val = numArray[index]; // check if subsequent values are equal to current value. // if not return current value. // no need to check previous values as they are already unique. if (numArray.indexOf(val, index + 1) === -1) return val; // repeat until unique number is generated while (true) { val = Math.floor(Math.random() * originalArray.length); if (numArray.indexOf(val) === -1) return val; } } function resetData() { for (let i = 0; i < 4; i++) { numArray[i] = getUniqueNumber(i); } } function startOperations() { console.log("before: " + numArray); resetData(); console.log("after: " + numArray); //insert other code here } startOperations(); ``` Upvotes: 0
2018/03/20
704
2,323
<issue_start>username_0: I have a dictionary with repeated keys but different values for those keys and i want to pull all values for a specific key. Here is the abbreviated version of what I mean: ``` x_table = {'A':'GCT','A':'GCC','A':'GCA','A':'GCG'} AA_list = [{'A'}] for aa in AA_list: if aa in x_table: print x_table[aa] ``` For some reason it will only pull one of the values from x\_table. Thanks for the help.<issue_comment>username_1: A dictionary cannot have multiple entries for the same key. Think about it - how were you planning on accessing the value? what should `x_table['A']` return? `'GCT'` or maybe `'GCA'`? What you can do, is make a slight change to you data structure and save a list rather than a single values. e.g.: `x_table = {'A':['GCT','GCC','GCA','GCG'], 'B' = ['some', 'other', 'values']}` In your example - you have only 1 key. From the information you have posted I cannot tell if it is a small sample or the general case. If it is the general case, maybe a [list](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) / [set](https://docs.python.org/2/tutorial/datastructures.html#sets) / [tuple](https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences) would serve you better: `('GCT','GCC','GCA','GCG')` If you want to understand better *why* you cannot store multiple entries for the same key, you can read about it [in this link](https://www.laurentluce.com/posts/python-dictionary-implementation/). Upvotes: 1 <issue_comment>username_2: Maybe you need define you dict structure like this: ``` x_table = {'A':['GCT','GCC','GCA','GCG']} ``` Upvotes: -1 <issue_comment>username_3: So, a dictionary is implemented as a set. As such, you ***cannot*** have multiple identical keys like so: ``` dict = {'a': 'blah', 'b': 'foo', 'b': 'bar'}; // ''b would only have the value 'bar' ``` The way dictionaries are designed, they don't allow this. They are basically hashmaps, and so allow quick access to the value via a key, but you can only have one key per value. When you assign the second key, it overwrites the first. You could, however, try implementing a dictionary as your value, like so: ``` x_table = {'A':{'a_1':GCT','a_2':'GCC','a_3':'GCA','a_4':'GCG'},'B':'blah'} ``` `AA_list = ['A']['a_1]` Upvotes: -1
2018/03/20
649
2,180
<issue_start>username_0: After connecting to the database, here is the simplest code that should update my database after clicking the submit button : ``` php if (isset($_POST['update'])){ $sql = "UPDATE accounts SET download='Yes' WHERE id=15 "; } ? ``` I dont know what am i doing wrong.<issue_comment>username_1: A dictionary cannot have multiple entries for the same key. Think about it - how were you planning on accessing the value? what should `x_table['A']` return? `'GCT'` or maybe `'GCA'`? What you can do, is make a slight change to you data structure and save a list rather than a single values. e.g.: `x_table = {'A':['GCT','GCC','GCA','GCG'], 'B' = ['some', 'other', 'values']}` In your example - you have only 1 key. From the information you have posted I cannot tell if it is a small sample or the general case. If it is the general case, maybe a [list](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) / [set](https://docs.python.org/2/tutorial/datastructures.html#sets) / [tuple](https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences) would serve you better: `('GCT','GCC','GCA','GCG')` If you want to understand better *why* you cannot store multiple entries for the same key, you can read about it [in this link](https://www.laurentluce.com/posts/python-dictionary-implementation/). Upvotes: 1 <issue_comment>username_2: Maybe you need define you dict structure like this: ``` x_table = {'A':['GCT','GCC','GCA','GCG']} ``` Upvotes: -1 <issue_comment>username_3: So, a dictionary is implemented as a set. As such, you ***cannot*** have multiple identical keys like so: ``` dict = {'a': 'blah', 'b': 'foo', 'b': 'bar'}; // ''b would only have the value 'bar' ``` The way dictionaries are designed, they don't allow this. They are basically hashmaps, and so allow quick access to the value via a key, but you can only have one key per value. When you assign the second key, it overwrites the first. You could, however, try implementing a dictionary as your value, like so: ``` x_table = {'A':{'a_1':GCT','a_2':'GCC','a_3':'GCA','a_4':'GCG'},'B':'blah'} ``` `AA_list = ['A']['a_1]` Upvotes: -1
2018/03/20
420
1,512
<issue_start>username_0: I am using react with react-router for a project and I need to pass props to the child component from the route. I have this setup: **App.js** ``` } /> ``` **Home.js** ``` import React from 'react' const Home = () => ( Welcome to the Tornadoes Website! ================================= {this.props.num} ) export default Home ``` The problem is that the home component always gives the error 'undefined'. I am unable to understand how to resolve this. If I remove the props from Home.js, the component renders just fine. But when I try accessing the props, it gives error.<issue_comment>username_1: Stateless components don't access props through `this`. They're passed in as an argument to the function. ``` const Home = props => ( Welcome to the Tornadoes Website! ================================= {props.num} ) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` } /> ``` Home ``` import React from 'react' const Home = (props) => ( Welcome to the Tornadoes Website! ================================= {props.someProp} {props.num} ) export default Home ``` Since you named your prop someProp in App.js to acess it you need to do props.someProp, the name has to match the name you passed it down as. The same goes for the num props which holds the "2". example In parent component render Child now in child ``` const Child = (props) => ( {props.prop1} will render hello {props.fun} will render this is a fun prop ) ``` Upvotes: 2
2018/03/20
622
2,173
<issue_start>username_0: I'm starting a new process like this: ``` $p = Start-Process -FilePath $pathToExe -ArgumentList $argumentList -NoNewWindow -PassThru -Wait if ($p.ExitCode -ne 0) { Write-Host = "Failed..." return } ``` And my executable prints a lot to console. Is is possible to not show output from my exe? I tried to add `-RedirectStandardOutput $null` flag but it didn't work because `RedirectStandardOutput` doesn't accept `null`. I also tried to add `| Out-Null` to the `Start-Process` function call - didn't work. Is it possible to hide output of the exe that I call in `Start-Process`?<issue_comment>username_1: You're invoking the executable *synchronously* (`-Wait`) and *in the same window* (`-NoNewWindow`). **You don't need `Start-Process` for this kind of execution at all - simply invoke the executable *directly*, using `&`**, the call operator, which allows you to: * use standard redirection techniques to silence (or capture) output * and to check automatic variable `$LASTEXITCODE` for the exit code ``` & $pathToExe $argumentList *> $null if ($LASTEXITCODE -ne 0) { Write-Warning "Failed..." return } ``` If you still want to use [`Start-Process`](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/start-process), see [username_2's helpful answer](https://stackoverflow.com/a/52623136/45375). Upvotes: 3 <issue_comment>username_2: Using call operator `&` and `| Out-Null` is a more popular option, but it is possible to discard standard output from `Start-Process`. Apparently, [`NUL` in Windows seems to be a virtual path in any folder](https://stackoverflow.com/a/27773642/25450). `-RedirectStandardOutput` requires a non-empty path, so `$null` parameter is not accepted, but `"NUL"` is (or any path that ends with `\NUL`). In this example the output is suppressed and the file is *not* created: ``` > Start-Process -Wait -NoNewWindow ping localhost -RedirectStandardOutput ".\NUL" ; Test-Path ".\NUL" False > Start-Process -Wait -NoNewWindow ping localhost -RedirectStandardOutput ".\stdout.txt" ; Test-Path ".\stdout.txt" True ``` `-RedirectStandardOutput "NUL"` works too. Upvotes: 4
2018/03/20
1,153
3,632
<issue_start>username_0: I'm currently having an issue getting data from my json files in PHP. What I got right now is ``` $jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}', true); echo ($jsondecoded[0]->chat); ``` I'm attempting to get the chat information. But it doesn't echo anything. I've been attempting to figure out why this is but I sadly can't find it.<issue_comment>username_1: Three errors: 1) Missing ] at the end of the json. 2) You are using the "array assoc" option of json\_decode, so it is not returning an object. 3) You cannot echo the chat object. Try this: ``` $jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]'); echo ($jsondecoded[0]->chat->username); ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` $jsondecoded = json_decode('[{"chat": {"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]', true); ``` Also, remember that you've used `true` as second parameter for `json_decode`, it means you're converting the result into a associative array, either remove that `true` or change your access to: ``` var_dump($jsondecoded[0]['chat']); ``` Upvotes: 0 <issue_comment>username_3: Your json is invalid at end add ']' end of json string, and print array in php use print\_r function. '[0]' use for get first element and ['chat'] use for get value of chat key ``` $jsondecoded = json_decode('[{"chat":{"username":"RobloxProtectorKing","message":":slender me","time":"2018-03-20 01:56:12"}}]', true); print_r ($jsondecoded[0]['chat']); ``` output will like ``` Array ( [username] => RobloxProtectorKing [message] => :slender me [time] => 2018-03-20 01:56:12 ) ``` Upvotes: 0 <issue_comment>username_4: Here's an example from a template I have. Hopefully it helps. ``` php /* Status Codes return 0 = Nothing to Update (n/a) return 1 = Successful Insert Query return 2 = Database Connection refused return 3 = MySQL Query Error OR Wrong URL Parameters */ /* Disable Warnings so that we can return ONLY what we want through echo. */ mysqli_report(MYSQLI_REPORT_STRICT); // First get raw POST input $raw_post = file_get_contents('php://input'); // Run through url_decode.. $url_decoded = urldecode($raw_post); // Run through json_decode... // false to allow for reference to oject. eg. $column-name instead of $column["name"] in the foreach. $json_decoded = json_decode($url_decoded, false); $pk_line_item_id = (strlen($json_decoded[0]->value) > 0 ? $json_decoded[0]->value : null); // INCLUDE DB CONNECTION STRING include 'php_pdo_mysql_connect.php'; // SQL INSERT query... $stmt = $link->prepare(" SELECT * FROM tbl_xyz "); //$stmt->bindParam(':pk_line_item_id', $pk_line_item_id, PDO::PARAM_INT); // INT // Execute this SQL statement. $stmt->execute(); // Fetch & Populate the single returned in var $resultSet. $resultSet = $stmt->fetchAll(); // Returns an array indexed by column number as returned in your result set, starting at column 0. // https://www.ibm.com/support/knowledgecenter/en/SSEPGG_9.7.0/com.ibm.swg.im.dbclient.php.doc/doc/t0023505.html // If the search record was found, populate it on the html table. if (($resultSet !== false) && ($stmt->rowCount() > 0)) { // Set JSON headers header('Content-type:application/json;charset=utf-8'); // Encode entire $resultSet array to JSON. $json_encoded = json_encode($resultSet); // Ready to return as JSON to client side JQuery / Java Script... echo $json_encoded; } ?> ``` Upvotes: -1
2018/03/20
1,099
3,024
<issue_start>username_0: I am having a little trouble doing this one SQL homework problem and have tried multiple different attempts but keep getting the same wrong answer. I am not sure what i'm missing, if anyone can please help me out that'd be really nice! :) Question: **Show distinct id's of all professors who taught at least 2 courses in the same semester** Here are the tables given to us: ``` DROP TABLE IF EXISTS PROFESSOR; CREATE TABLE PROFESSOR ( Id VARCHAR (9), Name VARCHAR (32), DepartmentId VARCHAR (3), PRIMARY KEY (Id), FOREIGN KEY (DepartmentId) REFERENCES DEPARTMENT (Id) )ENGINE=INNODB; INSERT INTO PROFESSOR VALUES ('P01', 'Rao', 'CSC'), ('P02', 'Mitra', 'CSC'), ('P03', 'Smith', 'MTH'), ('P04', 'Miller', 'MTH'), ('P05', 'Abwender', 'PSH'), ('P06', 'Speed', 'PSH'); DROP TABLE IF EXISTS TEACHING_ASSIGNMENT; CREATE TABLE TEACHING_ASSIGNMENT ( ProfessorId VARCHAR (9), -- Department Code may be different CourseCode VARCHAR (6), -- This is like CIS422 Semester VARCHAR (16),-- This is like Fall 2016 Section VARCHAR (3), -- This is like 01 PRIMARY KEY (ProfessorId, CourseCode, Semester, Section), FOREIGN KEY (ProfessorId) REFERENCES PROFESSOR (Id), FOREIGN KEY (CourseCode) REFERENCES COURSE (CourseCode) )ENGINE=INNODB; INSERT INTO TEACHING_ASSIGNMENT VALUES ('P01', 'CSC203', 'Fall 2015', '01'), ('P02', 'CIS202', 'Fall 2015', '01'), ('P03', 'MTH201', 'Fall 2015', '01'), ('P04', 'MTH281', 'Fall 2015', '01'), ('P05', 'PSH110', 'Fall 2015', '01'), ('P06', 'PSH201', 'Fall 2015', '01'), ('P01', 'CIS202', 'Fall 2015', '02'), ('P03', 'CSC203', 'Spring 2016', '01'), ('P02', 'CIS202', 'Spring 2016', '01'), ('P03', 'MTH201', 'Spring 2016', '01'), ('P04', 'MTH281', 'Spring 2016', '01'), ('P05', 'PSH110', 'Spring 2016', '01'), ('P06', 'PSH201', 'Spring 2016', '01'), ('P01', 'CIS202', 'Spring 2016', '02'); ``` My SQL: ``` SELECT DISTINCT Id FROM PROFESSOR WHERE Id IN (SELECT ProfessorId FROM TEACHING_ASSIGNMENT GROUP BY Semester HAVING COUNT() >= 2); ``` The answer i get: P01 But the right answer should be P01 AND P03.<issue_comment>username_1: The `GROUP BY` should include `ProfessorId` cause you are counting number of courses taught by a professor in a semester. Try this: ``` SELECT DISTINCT Id FROM PROFESSOR WHERE Id IN (SELECT ProfessorId FROM TEACHING_ASSIGNMENT GROUP BY Semester, ProfessorId HAVING COUNT(*) >= 2); ``` Upvotes: 1 <issue_comment>username_2: No subquery is necessary: ``` SELECT ProfessorId FROM TEACHING_ASSIGNMENT GROUP BY Semester, ProfessorId HAVING COUNT(*) >= 2; ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Below is the query, i checked it after creating a new Table. ``` select Courses.ProfessorId, count(*) from Cou_Pro Courses group by Courses.ProfessorId, Courses.Semester having count(Courses.ProfessorId) > 1 ``` Upvotes: 0
2018/03/20
535
1,834
<issue_start>username_0: I was wondering what the best approach would be to separate multiple items from a string in swift. I'm hoping to separate a unit and an amount from a string and then use those values to create an object of my ingredient class. For example: ``` var string = "4 cups sugar" ``` I would need to grab the 4 (amount) and convert it to an int and then grab the unit (cups) ``` var amount = 4 var unit = "cups" ``` Another example: ``` "3 large eggs" ``` In this case I would want to pull out the 3 (amount) and the unit would be empty. ``` var amount = 3 var unit = "" ``` Then I would create my object using the unit and amount values. I'm still a novice at swift, and more-so with string manipulation so I'm not entirely sure how to approach this, any help in the right direction would be great. I am working with an ingredient class that is structured as: ``` class IngredientModel { var amount = 0 var unit = "" init(amount : Int, unit : String) { self.amount = amount self.unit = unit } ```<issue_comment>username_1: The `GROUP BY` should include `ProfessorId` cause you are counting number of courses taught by a professor in a semester. Try this: ``` SELECT DISTINCT Id FROM PROFESSOR WHERE Id IN (SELECT ProfessorId FROM TEACHING_ASSIGNMENT GROUP BY Semester, ProfessorId HAVING COUNT(*) >= 2); ``` Upvotes: 1 <issue_comment>username_2: No subquery is necessary: ``` SELECT ProfessorId FROM TEACHING_ASSIGNMENT GROUP BY Semester, ProfessorId HAVING COUNT(*) >= 2; ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Below is the query, i checked it after creating a new Table. ``` select Courses.ProfessorId, count(*) from Cou_Pro Courses group by Courses.ProfessorId, Courses.Semester having count(Courses.ProfessorId) > 1 ``` Upvotes: 0
2018/03/20
498
1,915
<issue_start>username_0: Hello I have been digging to find the solution but unfortunately I have not been able to find an answer. My issue is that I have my application that uses crashlytics. When pulling my crashlytics I see the Dsyms missing issue, i tried to add all the missing ones through the organizer but unfortunately i am not able to find all of them. please note my applications are not in the app store and I do not have itunes connect I am using an enterprise account. I noticed when running my application through the simulator and forcing a crash, Fabric will ask me for a new dSYM that I am not able to find. where can i find this dsym? I have verified through my build settings that I have dWARRF with dSYM enabled on both debug and release. If you have any ideas please let me know. Thank you!!<issue_comment>username_1: You can do the following (it works for me): * Archive a binary of your target. Select your Scheme and make sure you have "Generic iOS Device": selected. Then in the Xcode menu, go to Window->Organizer and you will see your build * Select the build. Check the date/time and version(build) numbers to ensure it is the one you want. Right-Click and select "Show in Finder" * Right-click in the .xcarchive file and select "Show Package Contents" * Look for the dSYMs directory. Right-click and compress. * Move the dSYMs.zip file to your Desktop for easy uploading to Crashlytics. Upvotes: 0 <issue_comment>username_2: > > If you’re using Xcode 10 on a new project, Xcode 10 adopts a new build > ordering that is independent of the ordered list in the Build Phases > of Xcode. > > > Put **"$(BUILT\_PRODUCTS\_DIR)/$(INFOPLIST\_PATH)"** into your > Fabric Run Script’s **“Input Files”** section to ensure your > installation of Fabric goes smoothly. > > > Reference to [Crashlytics documentation](https://docs.fabric.io/apple/crashlytics/installation.html). Upvotes: 1