id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23529300
int i = 1; restart: while (i < 6) { Image1.ImageUrl = "~/Images/" + i.ToString() + ".png"; i++; if (i == 5) { restart; } } EDIT: After trying to prepend "GOTO" to the label, I can't get the page to load. Here is the rest of the file: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Clark { public partial class Home : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SetImageURL(); // To ensure image loads on page load } } protected void Timer1_Tick(object sender, EventArgs e) { SetImageURL(); // Refactored from previous logic } private void SetImageURL() { // The random function will choose between 1&5 which // correspond to images 1 through 5 //Random _rand = new Random(); //int i = _rand.Next(1, 5); //Image1.ImageUrl = "~/Images/" + i.ToString() + ".png"; int i = 1; restart: while (i < 6) { Image1.ImageUrl = "~/Images/" + i.ToString() + ".png"; i++; if (i == 5) { restart; } } /* while (true) { int i = 1; do { Image1.ImageUrl = "~/Images/" + i.ToString() + ".png"; i++; } while (i < 6); } */ } } } A: Just use nested loops. do { for (int i = 1; i < 6; i++; { Image1.ImageUrl = "~/Images/" + i.ToString() + ".png"; } } while (/* additional conditions */) I chose the do/while architecture because it maps best to what you already have, but just a plain-ol' while would do the trick too. Although that all said, remember that unless this is just an example, this is a pretty silly thing to do. Your ImageUrl won't be read while you're in this loop, so you could just calculate out what the result will actually be and not have to waste the time and resources to run what could turn into an infinite loop like this. Edit: The question has evolved. Instead of using loops, store an Application variable: object imageIndexObj = Application["imageIndex"]; int imageIndex; if(imageIndexObj == null) imageIndex = 1; else imageIndex = (int)imageIndexObj; Image1.ImageUrl = "~/Images/" + (imageIndex % 5) + ".png"; Application["imageIndex"] = imageIndex + 1; There are some implications here, particularly when dealing with multiple-server farms. But this should suffice for your case. If you hit a user-load wherein multiple servers are required, then using a workflow like this will likely become irrelevant, since the result will be more random anyway. You could also use Session in place of Application here, if you want the five images to cycle for each session, rather than for each request. That's your call. The code's the same other than that, though.
doc_23529301
$data = $_REQUEST; if($data["prop_images"]){ $filename = md5(time()).'.jpg'; $base=$data["prop_images"]; $binary = base64_decode($base); $pathtoupload = JPATH_ADMINISTRATOR . '/components/com_clinchproperties/galupload/'; //header('Content-Type: bitmap; charset=utf-8'); // binary, utf-8 bytes $actual_image_name = time().".jpg"; $image = $filename; $file = fopen($pathtoupload.$filename, 'wb'); fwrite($file, $binary); fclose($file); } I need code to upload n number of images at same time. Can any one help me with it? Thanks in advance. A: This will help you to check your web service <form method="post" enctype="multipart/form-data" action="audioupload.php"> <input type="file" name="file1" multiple> <input type="submit" value="OK"> </form> audio.php <?php move_uploaded_file($_FILES["file1"]["tmp_name"],"audio/".$_FILES["file1"]["name"]); $url = "audio/".$_FILES["file1"]["name"]; ?> likewise developer can call this service n times. A: You have to pass array of files. As you mentioned in comment, you are sending file data in base64 format, try following code for PHP. PHP $data = $_REQUEST; if($data["prop_images"]){ foreach($data["prop_images"] as $img){ //array of images. So loop for every images $filename = md5(time()).'.jpg'; $base=$img; $binary = base64_decode($base); $pathtoupload = JPATH_ADMINISTRATOR . '/components/com_clinchproperties/galupload/'; $actual_image_name = time().".jpg"; $image = $filename; $file = fopen($pathtoupload.$filename, 'wb'); fwrite($file, $binary); fclose($file); } } In android code, make sure to add [] in parameter name while making POST request. That parameter should be prop_images[] as per example I given above. I'm not an Android developer, but I can post code from our Android developer. Android HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://webserver.com/path/to/webservice.php"); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int i = 0; i < number_of_images; i++) { //convert your images to base64 and store in base64ImageData. reqEntity.addPart("prop_images[]", base64ImageData); //adding parameter } //execute request.
doc_23529302
Former string from this report such as Taxes are translated, but I don't know how to translate 'raw strings' associated to custom field I added to the model Invoice... Even some native model field label in the sxw report, such as account.invoice.date_due are not translated anymore. I don't understand why. Thank you for your help Cheers A: Look for the file corresponding to your language in the addons/account/i18n/ folder. I suppose you'll discover that some texts from the existing installation are not translated and obviously your new fields descriptions are also missing. You may want to take a look here too: https://doc.openerp.com/v6.1/contribute/07_improving_translations.html/#translations-code
doc_23529303
header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'} data= requests.get("https://etfdb.com/etfs/inverse/#etfs&sort_name=assets_under_management&sort_order=desc&page=1", headers=header) soup= BeautifulSoup (data.content, 'lxml') table = soup.find_all('tbody',) for i in table: name = i.text print(name) I am only getting SQQQ not the one's below. A: Once you have found the start of your table, you could then find all the table rows by searching for <tr> elements. Then for each row extract all of the <td> elements. For example: from bs4 import BeautifulSoup import requests header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'} data = requests.get("https://etfdb.com/etfs/inverse/#etfs&sort_name=assets_under_management&sort_order=desc&page=1", headers=header) soup = BeautifulSoup(data.content, 'lxml') first_table = soup.find('tbody') for tr in first_table.find_all('tr'): row = [td.text for td in tr.find_all('td')] print(row) This would display output starting: ['SQQQ', 'ProShares UltraPro Short QQQ', 'Equity', '--3x', '$2,768.14', '61.65%', '57,468,328', '$48.01', '7.65%', '24.77%', '14.88%', '-29.55%', '-95.71%', '-98.71%', '', '', '', '', '', '', 'Leveraged Equities', '2010-02-09', '0.95%', 'N/A', '$0.00', '2020-03-25', '$0.06', '0.00%', '0.00', '-2.36', '21', '87.81%', 'View', '40%', '20%', '1099', '$34.58', '$46.07', '$44.62', '$49.79', '64.40', 'View', 'View', 'View', 'View', 'View', 'View', '', 'A', 'C+', '', '', '', '', '5.81', '30.51%', '30.56%', '0.0', '0.00%', '0.00%'] ['SH', 'ProShares Short S&P500', 'Equity', '-False', '$1,927.14', '11.75%', '19,136,312', '$15.22', '1.74%', '5.77%', '3.33%', '-11.92%', '-45.03%', '-54.71%', '', '', '', '', '', '', 'Inverse Equities', '2006-06-19', '0.90%', 'N/A', '$0.00', '2020-03-25', '$0.03', '0.00%', '0.00', '-0.90', '19', '88.02%', 'View', '40%', '20%', '1099', '$13.99', '$15.06', '$14.94', '$15.37', '64.28', 'View', 'View', 'View', 'View', 'View', 'View', '', 'A', 'B+', '', '', '', '', '5.81', '30.51%', '30.56%', '0.0', '0.00%', '0.00%'] ['PSQ', 'ProShares Short QQQ', 'Equity', '-False', '$1,015.79', '18.93%', '20,123,440', '$12.88', '2.47%', '7.87%', '5.57%', '-7.80%', '-57.29%', '-69.16%', '', '', '', '', '', '', 'Inverse Equities', '2006-06-19', '0.95%', 'N/A', '$0.00', '2020-03-25', '$0.04', '0.00%', '0.00', '-0.92', '19', '86.79%', 'View', '40%', '20%', '1099', '$11.52', '$12.68', '$12.56', '$13.05', '64.53', 'View', 'View', 'View', 'View', 'View', 'View', '', 'A-', 'B', '', '', '', '', '5.81', '30.51%', '30.56%', '0.0', '0.00%', '0.00%']
doc_23529304
object start = new Regex(@"(References)\s*:?\s*").Match(wordText).Index; object end = wordText.Length; Word.Range rngRef = doc.Range(start,end); This is how I have selected range, now how do I select list and loop through the items? A: I depend how the ordered list is exactly 'formatted' in Word. If this is just a number of paragraphs one could do (to get the text from the paragraphs): int i = 0; var paragraphs = rngRef.Paragraphs; foreach (Word.Paragraph item in paragraphs) { Console.WriteLine("{0}: {1}", ++i, item.Range.Text); }
doc_23529305
In the case of using <mat-dialog-content>: error NG8001: 'mat-dialog-content' is not a known element: (then stuff about verifying that it is part of the module) While for [(ngInput)] I get: src/app/dialog-test/dialog-content-example-dialog.html:15:17 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'. The full code is at https://github.com/benoleary/mat-dialog-frustration I know that I am importing things correctly to be used anywhere except within the dialog (e.g. in that demo, the main app page has the same input element and it works). I presume that there is something with the imports and exports that is missing but I have not been able to identify it. There seem to be many questions already which are answered with "you forgot to import MatDialogModule in app.module.ts" but I definitely am importing it in app.module.ts. (I did find a question which seems to be the same as mine but I cannot see any answers and honestly I am a little suspicious of "solveforum": https://solveforum.com/forums/threads/solved-angular-material-mat-dialog-content-is-not-a-known-element.34667/#) I have deleted my node_modules and re-run npm install innumerable times. Tried on both Debian 10 with node v18.2.0 and npm 8.9.0 and on Windows Server 2019 also with node node v18.2.0 and npm 8.9.0 app.module.ts: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FormsModule } from '@angular/forms'; import { MatDialogModule } from '@angular/material/dialog'; import { DialogContentExample } from './dialog-test/dialog-test.component'; @NgModule({ declarations: [ AppComponent, DialogContentExample ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FormsModule, MatDialogModule ], exports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, FormsModule, MatDialogModule, DialogContentExample ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } dialog-test.component.ts: import { Component } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { FormsModule } from '@angular/forms'; import { MatDialogModule } from '@angular/material/dialog'; /** * @title Dialog with header, scrollable content and actions */ @Component({ selector: 'dialog-content-example', templateUrl: 'dialog-content-example.html', }) export class DialogContentExample { pageInput = 'initialized'; constructor(public dialog: MatDialog) {} openDialog() { const dialogRef = this.dialog.open(DialogContentExampleDialog); dialogRef.afterClosed().subscribe(result => { console.log(`Dialog result: ${result}`); }); } } @Component({ selector: 'dialog-content-example-dialog', templateUrl: 'dialog-content-example-dialog.html', }) export class DialogContentExampleDialog { dialogInput: string = "blah"; } dialog-content-example-dialog.html: <h2 mat-dialog-title>A Title</h2> <p> A paragraph dialogInput = {{this.dialogInput}} </p> <!-- Uncommenting the mat-dialog-content element below causes the following error: error NG8001: 'mat-dialog-content' is not a known element: while uncommenting the input element causes: error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'. <input matInput [(ngModel)]="dialogInput"> ~~~~~~~~~~~~~~~~~~~~~~~~~ --> <!-- <mat-dialog-content>Some content</mat-dialog-content> --> <!-- <input matInput [(ngModel)]="dialogInput"> --> package.json: { "name": "mat-dialog-test", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "watch": "ng build --watch --configuration development", "test": "ng test" }, "private": true, "dependencies": { "@angular/animations": "~13.3.0", "@angular/cdk": "^13.3.8", "@angular/common": "~13.3.0", "@angular/compiler": "~13.3.0", "@angular/core": "~13.3.0", "@angular/forms": "~13.3.0", "@angular/material": "^13.3.8", "@angular/platform-browser": "~13.3.0", "@angular/platform-browser-dynamic": "~13.3.0", "@angular/router": "~13.3.0", "@material/dialog": "^14.0.0", "rxjs": "~7.5.0", "tslib": "^2.3.0", "zone.js": "~0.11.4" }, "devDependencies": { "@angular-devkit/build-angular": "~13.3.5", "@angular/cli": "~13.3.5", "@angular/compiler-cli": "~13.3.0", "@types/jasmine": "~3.10.0", "@types/node": "^12.11.1", "jasmine-core": "~4.0.0", "karma": "~6.3.0", "karma-chrome-launcher": "~3.1.0", "karma-coverage": "~2.1.0", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "~1.7.0", "typescript": "~4.6.2" } } A: This is not a perfect answer as it does not actually state what the problem was, but at least thanks to Nathaniel Johnson in the comments, I was able to get my dialogs working by doing making my own copy of material.module.ts from https://stackblitz.com/edit/angular-7rp2tf?file=src%2Fapp%2Fdialog-content-example.ts in my src/ folder and importing that in app.module.ts. If anyone can post a more satisfactory answer about what I was doing wrong and why, I will accept that. Until then, at least there is a way forward in case anyone else has the same problem.
doc_23529306
create table telephones( client_id char(9) not null CHECK (cif_cliente SIMILAR TO '[0-9]{8}[A-Z]'), telephone_number char(14) ); I want to restrict the telephone_number field so that I can only enter values such as (123)-45-67-89 or (666)-22-33-55 where there are always 3 numbers in brackets at the beginning followed by a hyphen, 2 numbers with another hyphen, 2 numbers with another hyphen and 2 numbers at the end. I tried this but when I try to insert a correct number I can't: create table telephones( client_id char(9) not null CHECK (cif_cliente SIMILAR TO '[0-9]{8}[A-Z]'), telephone_number char(14) CHECK telephone_number SIMILAR TO '([0-9]{3})-[0-9]{2}-[0-9]{2}-[0-9]{2}'), ); insert into telephones values('12345678K', '(666)-22-33-55'); Any idea of how to fix this? A: As a personal preference I don't use SIMILAR TO defined by the SQL language. I jump from the simplistic LIKE (useful for most cases) to a regexp pattern matching for well-formed patterns. I don't find good uses cases for SIMILAR TO, but that's just me. You can do: create table telephones ( client_id char(9) not null CHECK (client_id ~ '[0-9]{8}[A-Z]'), telephone_number char(14) check (telephone_number ~ '\(\d{3}\)\-\d{2}\-\d{2}\-\d{2}' ) ); insert into telephones (client_id, telephone_number) values ('12345678A', '(122)-45-67-89'); -- succeeds insert into telephones (client_id, telephone_number) values ('12345678A', '122-45-67-89'); -- fails insert into telephones (client_id, telephone_number) values ('12345678A', '(122)-45-6-89'); -- fails See running example at db<>fiddle.
doc_23529307
There's already an existing app which has users subscribed, for the rebuild i'm reusing the current product/subscription IDs in Google Play Console/App Store Connect. I'm using Cognito for login and when a (new) user subscribes I have a webhook setup that listens for events from the respective store and stores the subscription status as a claim against the user. This also works for when a user cancels/modifies their subscription, i'll get an event to the webhook and update the backend accordingly. My problem however, is this I need to migrate any existing users with existing subscriptions across to my new app, to for this to be a success I need: * *A list of users that have an active subscription using the existing subscription/product IDs Once I have this I can create users in Cognito and ensure their subscription status is correct, is there an endpoint/approach for each platform that allows me to get a list of users with an active subscription? Alternatively is there any event I can hook into from the subscriptions/purchases webhook that would allow me to do this? The key is I need to make sure that any existing users that login have their subscription on the new app and for this to happen I need to know their current subscription status so I can store it against them in Cognito. Any help is greatly appreicated
doc_23529308
ogr2ogr -f geoJSON output.json CALGIS.ADM_COMMUNITY_DISTRICT.shp I then trimmed the file down to a single shape to to make sure I have things working. { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "GEODB_OID": 924.0, "NAME0": "Residential", "OBJECTID": 924.0, "CLASS": "Residential", "CLASS_CODE": 1.0, "COMM_CODE": "NEB", "NAME": "NEW BRIGHTON", "SECTOR": "SOUTHEAST", "SRG": "DEVELOPING", "STRUCTURE": "BUILDING OUT", "GLOBALID": "{086267D0-E600-11DE-8601-0014C258E143}", "GUID": null, "SHAPE_AREA": 2864275.556415310129523, "SHAPE_LEN": 6834.047231250339792 }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 2927.794099999591708, 5643887.8214, 0.0 ], [ 2978.190899999812245, 5643875.2194, 0.0 ], [ 3017.59360000025481, 5643861.5459, 0.0 ], [ 3053.779900000430644, 5643845.8617, 0.0 ], [ 3089.161999999545515, 5643826.1559, 0.0 ], [ 3129.111100000329316, 5643798.7318, 0.0 ], [ 3166.111999999731779, 5643767.0104, 0.0 ], [ 3226.018400000408292, 5643707.9734, 0.0 ], [ 3262.138399999588728, 5643679.7766, 0.0 ], [ 3302.66330000013113, 5643652.4609, 0.0 ], [ 3340.545300000347197, 5643633.9568, 0.0 ], [ 3381.070199999958277, 5643617.2149, 0.0 ], [ 3419.833100000396371, 5643605.76, 0.0 ], [ 3464.762900000438094, 5643596.9485, 0.0 ], [ 3557.440000000409782, 5643593.6766, 0.0 ], [ 3743.247600000351667, 5643595.2622, 0.0 ], [ 4549.149299999698997, 5643598.9876, 0.0 ], [ 4557.495199999772012, 5643598.9977, 0.0 ], [ 4558.032899999991059, 5643388.8087, 0.0 ], [ 4556.232300000265241, 5643344.1895, 0.0 ], [ 4557.219800000078976, 5643281.1676, 0.0 ], [ 4568.658999999985099, 5643220.321, 0.0 ], [ 4577.637199999764562, 5643188.2051, 0.0 ], [ 4587.662399999797344, 5643161.1236, 0.0 ], [ 4600.026700000278652, 5643134.0421, 0.0 ], [ 4614.730200000107288, 5643108.298, 0.0 ], [ 4627.428700000047684, 5643088.9062, 0.0 ], [ 4636.785400000400841, 5643077.2044, 0.0 ], [ 4654.315700000151992, 5643055.3688, 0.0 ], [ 4670.024799999780953, 5643037.7422, 0.0 ], [ 4677.24239999987185, 5643028.1856, 0.0 ], [ 4692.314699999988079, 5643007.5858, 0.0 ], [ 4706.75, 5642984.4375, 0.0 ], [ 4721.384600000455976, 5642957.0105, 0.0 ], [ 4728.190799999982119, 5642942.9406, 0.0 ], [ 4733.571000000461936, 5642930.296, 0.0 ], [ 4741.564799999818206, 5642909.5987, 0.0 ], [ 4745.385900000110269, 5642898.9165, 0.0 ], [ 4750.056200000457466, 5642882.7764, 0.0 ], [ 4757.27379999961704, 5642855.5082, 0.0 ], [ 4761.944099999964237, 5642831.0858, 0.0 ], [ 4764.583599999547005, 5642816.8839, 0.0 ], [ 4767.25899999961257, 5642771.221, 0.0 ], [ 4767.212799999862909, 5642753.813, 0.0 ], [ 4767.283999999985099, 5642736.1341, 0.0 ], [ 4767.022300000302494, 5642665.7222, 0.0 ], [ 4766.921799999661744, 5642638.6629, 0.0 ], [ 4766.644999999552965, 5642564.2112, 0.0 ], [ 4764.399000000208616, 5642549.9524, 0.0 ], [ 4763.098699999973178, 5642517.7568, 0.0 ], [ 4759.445700000040233, 5642485.7426, 0.0 ], [ 4753.459599999710917, 5642454.0817, 0.0 ], [ 4745.172600000165403, 5642422.9437, 0.0 ], [ 4734.628999999724329, 5642392.4957, 0.0 ], [ 4721.885400000028312, 5642362.901, 0.0 ], [ 4707.010200000368059, 5642334.3181, 0.0 ], [ 4690.083200000226498, 5642306.9006, 0.0 ], [ 4662.280299999751151, 5642261.2609, 0.0 ], [ 4591.4386, 5642155.4526, 0.0 ], [ 4587.216000000014901, 5642149.4254, 0.0 ], [ 4582.180200000293553, 5642142.5072, 0.0 ], [ 4576.260200000368059, 5642134.7208, 0.0 ], [ 4570.27379999961704, 5642127.1973, 0.0 ], [ 4564.026300000026822, 5642119.6911, 0.0 ], [ 4555.244800000451505, 5642109.6863, 0.0 ], [ 4540.423600000329316, 5642094.0912, 0.0 ], [ 4521.90639999974519, 5642076.5828, 0.0 ], [ 4505.988499999977648, 5642062.9452, 0.0 ], [ 4495.557500000111759, 5642054.8537, 0.0 ], [ 4481.677099999971688, 5642044.7072, 0.0 ], [ 4462.914599999785423, 5642032.251, 0.0 ], [ 4454.125599999912083, 5642026.8774, 0.0 ], [ 4436.629599999636412, 5642016.9938, 0.0 ], [ 4426.443900000303984, 5642011.7128, 0.0 ], [ 4415.223299999721348, 5642006.2772, 0.0 ], [ 4406.224100000225008, 5642002.1967, 0.0 ], [ 4397.961400000378489, 5641998.6618, 0.0 ], [ 4389.166600000113249, 5641995.1156, 0.0 ], [ 4378.450400000438094, 5641991.0886, 0.0 ], [ 4369.899600000120699, 5641988.1007, 0.0 ], [ 4359.190999999642372, 5641984.6342, 0.0 ], [ 4346.230499999597669, 5641980.8381, 0.0 ], [ 4332.145399999804795, 5641977.1961, 0.0 ], [ 4314.272199999541044, 5641973.28, 0.0 ], [ 4294.416500000283122, 5641969.5716, 0.0 ], [ 4271.907200000248849, 5641966.9084, 0.0 ], [ 4251.878700000233948, 5641965.4557, 0.0 ], [ 4234.786999999545515, 5641964.965, 0.0 ], [ 4196.942300000227988, 5641964.8861, 0.0 ], [ 4002.861800000071526, 5641964.5645, 0.0 ], [ 3972.891200000420213, 5641964.5172, 0.0 ], [ 3841.810200000181794, 5641964.3106, 0.0 ], [ 3807.330199999734759, 5641964.2562, 0.0 ], [ 3660.713999999687076, 5641964.025, 0.0 ], [ 3647.798600000329316, 5641963.7829, 0.0 ], [ 3638.501600000075996, 5641963.2293, 0.0 ], [ 3627.036600000225008, 5641962.2457, 0.0 ], [ 3617.656200000084937, 5641961.0928, 0.0 ], [ 3607.657200000248849, 5641959.5778, 0.0 ], [ 3597.110600000247359, 5641957.6351, 0.0 ], [ 3588.339700000360608, 5641955.7766, 0.0 ], [ 3577.879999999888241, 5641953.1515, 0.0 ], [ 3571.110299999825656, 5641951.2793, 0.0 ], [ 3564.783800000324845, 5641949.3857, 0.0 ], [ 3558.644399999640882, 5641947.4041, 0.0 ], [ 3550.486899999901652, 5641944.5771, 0.0 ], [ 3540.044999999925494, 5641940.6467, 0.0 ], [ 3529.676799999549985, 5641936.1998, 0.0 ], [ 3518.299599999561906, 5641930.8311, 0.0 ], [ 3509.474000000394881, 5641926.4049, 0.0 ], [ 3489.843000000342727, 5641915.1433, 0.0 ], [ 3470.775399999693036, 5641902.3484, 0.0 ], [ 3453.804100000299513, 5641889.193, 0.0 ], [ 3439.17960000038147, 5641876.3024, 0.0 ], [ 3426.035000000149012, 5641863.274, 0.0 ], [ 3397.286199999973178, 5641833.1086, 0.0 ], [ 3390.071100000292063, 5641825.5381, 0.0 ], [ 3377.323699999600649, 5641812.1625, 0.0 ], [ 3375.876199999824166, 5641813.5779, 0.0 ], [ 3351.266699999570847, 5641835.3288, 0.0 ], [ 3116.584099999628961, 5642034.1642, 0.0 ], [ 3113.274400000460446, 5642037.411, 0.0 ], [ 3107.191999999806285, 5642043.0764, 0.0 ], [ 3097.167899999767542, 5642052.8479, 0.0 ], [ 3080.6102, 5642070.0978, 0.0 ], [ 3065.090699999593198, 5642087.4722, 0.0 ], [ 3054.615399999544024, 5642099.9023, 0.0 ], [ 3044.664900000207126, 5642112.0562, 0.0 ], [ 3034.105200000107288, 5642126.0083, 0.0 ], [ 3027.029400000348687, 5642135.9554, 0.0 ], [ 3015.540300000458956, 5642152.6979, 0.0 ], [ 3003.560999999754131, 5642170.4954, 0.0 ], [ 2993.930499999783933, 5642185.0394, 0.0 ], [ 2984.89130000025034, 5642200.1754, 0.0 ], [ 2974.038800000213087, 5642220.3783, 0.0 ], [ 2968.171699999831617, 5642232.5815, 0.0 ], [ 2962.849600000306964, 5642244.8424, 0.0 ], [ 2957.70920000039041, 5642257.6546, 0.0 ], [ 2952.978400000371039, 5642270.9303, 0.0 ], [ 2949.268400000408292, 5642282.2314, 0.0 ], [ 2945.973799999803305, 5642293.0548, 0.0 ], [ 2943.189799999818206, 5642303.6028, 0.0 ], [ 2941.162399999797344, 5642312.7351, 0.0 ], [ 2939.726599999703467, 5642319.1378, 0.0 ], [ 2938.206000000238419, 5642329.2002, 0.0 ], [ 2936.854299999773502, 5642338.1634, 0.0 ], [ 2935.807199999690056, 5642347.1374, 0.0 ], [ 2934.383500000461936, 5642426.9538, 0.0 ], [ 2933.103600000031292, 5642495.576, 0.0 ], [ 2931.656700000166893, 5642576.0206, 0.0 ], [ 2931.656700000166893, 5642595.352, 0.0 ], [ 2931.656899999827147, 5642627.5118, 0.0 ], [ 2931.571299999952316, 5642666.984, 0.0 ], [ 2931.658400000073016, 5642675.2527, 0.0 ], [ 2931.575000000186265, 5642696.2072, 0.0 ], [ 2931.488099999725819, 5642734.4552, 0.0 ], [ 2931.402499999850988, 5642768.535, 0.0 ], [ 2931.401999999769032, 5642802.4475, 0.0 ], [ 2931.400899999774992, 5642829.4046, 0.0 ], [ 2931.236399999819696, 5642865.6859, 0.0 ], [ 2931.015800000168383, 5642928.21, 0.0 ], [ 2931.015800000168383, 5642965.0028, 0.0 ], [ 2931.017500000074506, 5643001.0649, 0.0 ], [ 2930.886400000192225, 5643043.3756, 0.0 ], [ 2931.0152000002563, 5643077.3405, 0.0 ], [ 2930.878999999724329, 5643115.9048, 0.0 ], [ 2930.604899999685585, 5643139.8282, 0.0 ], [ 2931.013600000180304, 5643176.6929, 0.0 ], [ 2930.82079999987036, 5643192.4659, 0.0 ], [ 2931.170199999585748, 5643288.041, 0.0 ], [ 2930.92850000038743, 5643307.1494, 0.0 ], [ 2931.049399999901652, 5643329.0395, 0.0 ], [ 2930.808899999596179, 5643345.3237, 0.0 ], [ 2931.051400000229478, 5643363.4409, 0.0 ], [ 2931.171799999661744, 5643384.0848, 0.0 ], [ 2930.93099999986589, 5643404.7221, 0.0 ], [ 2930.93099999986589, 5643421.7746, 0.0 ], [ 2930.932300000451505, 5643444.6002, 0.0 ], [ 2931.41509999986738, 5643467.0487, 0.0 ], [ 2931.899400000460446, 5643490.5762, 0.0 ], [ 2932.503800000064075, 5643512.95, 0.0 ], [ 2933.22829999960959, 5643530.6844, 0.0 ], [ 2934.074500000104308, 5643547.0113, 0.0 ], [ 2934.797799999825656, 5643563.2764, 0.0 ], [ 2935.523199999704957, 5643580.8126, 0.0 ], [ 2936.126000000163913, 5643613.4784, 0.0 ], [ 2936.246899999678135, 5643638.271, 0.0 ], [ 2936.005199999548495, 5643652.421, 0.0 ], [ 2935.643500000238419, 5643675.7237, 0.0 ], [ 2934.556400000117719, 5643701.1971, 0.0 ], [ 2934.193699999712408, 5643714.6214, 0.0 ], [ 2932.745000000111759, 5643742.0091, 0.0 ], [ 2932.140599999576807, 5643758.6988, 0.0 ], [ 2930.814000000245869, 5643786.563, 0.0 ], [ 2930.088700000196695, 5643802.0433, 0.0 ], [ 2929.483300000429153, 5643816.7571, 0.0 ], [ 2928.100499999709427, 5643851.0717, 0.0 ], [ 2927.876600000075996, 5643858.052, 0.0 ], [ 2927.809200000017881, 5643861.4184, 0.0 ], [ 2927.770399999804795, 5643867.8124, 0.0 ], [ 2927.794099999591708, 5643887.8214, 0.0 ] ] ] } } ] } I draw this to the screen using d3.js and the following code which is adapted from http://vallandingham.me/shapefile_to_geojson.html var OpenData; (function (OpenData) { var CalgaryMap = (function () { function CalgaryMap() { } CalgaryMap.prototype.render = function () { var xy = d3.geo.albersUsa(); var path = d3.geo.path().projection(xy); var vis = d3.select("#map").append("svg:svg").attr("width", 900).attr("height", 900); d3.json("data.json", function (json) { vis.append("svg:g").attr("class", "tracts").selectAll("path").data(json.features).enter().append("svg:path").attr("d", path).attr("fill-opacity", 0.5).attr("fill", function (d) { return "black"; }).attr("stroke", "#222"); }); }; return CalgaryMap; })(); OpenData.CalgaryMap = CalgaryMap; })(OpenData || (OpenData = {})); However what I get is a jumbled mess which looks like I loaded the geojson file into QGIS to validate it in case I had messed up. But it looked just fine in QGIS. This made me think it was probably the projection I was using. The geojson file I have doesn't seem to be in anything which looks like a coordinate I know from my GPS. So I changed the projection function to an identity function function (location) { var xCoordinate = location[0]; var yCoordinate = location[1]; return [ xCoordinate, //scale here yCoordinate ]; }; Which generated What do I need to do to get this thing projected correctly? I imagine this is easy but my lack of any knowledge of GIS is certainly hamstringing me. A: Thanks to @Superboggly I changed the command to ogr2ogr and it produced a much more reasonable GeoJSON file. My understanding is that there are a number of different coordinate systems in use in the GIS field. I was attempting to use a file formatted in one system in a system which was expecting a different system. I think we can safely say the results were unintended.
doc_23529309
I'm working through a python tutorial with the following ORM model. from views import db import datetime class Task(db.Model): __tablename__ = "tasks" task_id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) due_date = db.Column(db.Date, nullable=False) priority = db.Column(db.Integer, nullable=False) status = db.Column(db.Integer) def __init__(self, name, due_date, priority, status): self.name = name self.due_date = due_date self.priority = priority self.status = status def __repr__(self): return '<name {0}>'.format(self.name) The config file is defined as follows: import os basedir = os.path.abspath(os.path.dirname(__file__)) DATABASE = 'flasktaskr.db' USERNAME ='admin' PASSWORD = 'admin' CSRF_ENABLED = True # cross site request forgery prevention SECRET_KEY = 'secret' # used in conjunction wth CSR SQLALCHEMY_TRACK_MODIFICATIONS = False DATABASE_PATH = os.path.join(basedir, DATABASE) SQLAlCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH The view initializes the application as follows: app = Flask(__name__) app.config.from_object('_config') db = SQLAlchemy(app) Prior to executing the application the database has to be created using the following. The code runs with out exception, however the database is not created. I have trace the code and verified that the SQLAlCHEMY_DATABASE_URI is set correct. from views import db from models import Task from datetime import date from models import Task db.create_all() db.session.add(Task("Finish this tutorial", date(2019, 6, 22), 10, 1)) db.session.add(Task("Finish Real Python", date(2019, 6, 25), 10, 1)) db.session.commit() Based on this information what would prevent my database from being created on the filesystem? A: Verify if typo are only in this post, or are in code too: SQLAlCHEMY_DATABASE_URI should be SQLALCHEMY_DATABASE_URI (all capital letters
doc_23529310
SOURCE: The area starts from J15 to last row of J column. I'm having trouble with the syntax. DESTINATION: The area where the paste is the same area as in the Sourceworkbook, but K Column (K15 to last row of J column) The problem is the with statement. I keep getting this error: https://pasteboard.co/HsxMzPZ.jpg Picture of the sourcesheet for clarification https://pasteboard.co/Hs8gDsF.jpg Public Sub Subledger_Makro() Dim Subwb As Workbook Dim Subsht As Worksheet Dim Sourcewb As Workbook Dim SourceSht As Worksheet Set Subwb = ActiveWorkbook Set Subsht = Subwb.Sheets("SAPBW_DOWNLOAD") SourceFile = Application.GetOpenFilename(, , "Open yesterdays Subledger Report") Set Sourcewb = Workbooks.Open(SourceFile) Set SourceSht = Sourcewb.Sheets("SAPBW_DOWNLOAD") 'Copies the previous day Subledger (SourceSht) report J-Column to new the Subledgers (DestSht) K-column ' DestSheet is todays Subledger ' SourceSheet is the previous day Subledger With SourceSht .Range(.Cells(15, "J"), .Cells(.Cells(.Rows.Count, "J").End(xlUp).Row, "J")).Copy Destination:=Subwb.Subsht.Range("K15") End With Application.CutCopyMode = False End Sub A: Replace this line .Range(.Cells(15, "J"), .Cells(.Cells(.Rows.Count, "J").End(xlUp).Row, "J")).Copy Destination:=Subwb.Subsht.Range("K15") With .Range(.Cells(15, "J"), .Cells(.Cells(.Rows.Count, "J").End(xlUp).Row, "J")).Copy Subsht.Range("K15").PasteSpecial xlPasteAll
doc_23529311
I was told that if I Dockerize my app and push resulting image to Amazon ECR (Elastic Container Registry), EC2 can easily get app from there. I did that and NOW I have hit another road block. After deploying in EC2 container, the problem is that my app is in ONLY phpfpm container in folder /var/www/html/ but IT IS NOT VISIBLE IN my nginx container. Due to this problem, nginx does not delivery my app. Please note that app is not in the host device EC2, nor it is in nginx, it is only in php-fpm. How to solve this problem? Please advise. Thanks docker-compose.yml version: '2' services: nginx: image: 607167.dkr.ecr.ap-southeast-1.amazonaws.com/nginx:1 cpu_shares: 50 mem_limit: 134217728 ports: - "80:80" links: - phpfpm phpfpm: image: 60547.dkr.ecr.ap-southeast-1.amazonaws.com/phpinfo:latest cpu_shares: 50 mem_limit: 134217728 ports: - "9000:9000" - "3306:3306" I tried add this line to both containers in yml file but then my containers fail to load. volumes: - .:/var/www/html Please help. Thanks A: I would like to post this answer in hope that that it will help someone else. I spent a day trying to figure out how to solve this situation BUT the solution was very simple. Instead of having two separate containers ONE FOR php and ONE FOR nginx, build a single container with PHP, NGINX and your app Consider docker containers just as a single linux vm instance. A single vm can have multiple services running, so can a single docker container. Each service does not have to be in the different container. Answer was easy if concepts are clear. Mine were not unfortunately. Hope it helps.
doc_23529312
But when I try to build the project with $ /path/to/my_new_cordova_project/cordova/debug I get this: In file included from /Users/jakob/Dropbox/Coding/phonegap/ios_project/ios_project/Classes/AppDelegate.m:28: /Users/jakob/Dropbox/Coding/phonegap/ios_project/ios_project/Classes/AppDelegate.h:30:9: fatal error: 'Cordova/CDVViewController.h' file not found #import <Cordova/CDVViewController.h> ^ 1 error generated. ** BUILD FAILED ** The following build commands failed: CompileC build/ios_project.build/Debug-iphonesimulator/ios_project.build/Objects-normal/i386/MainViewController.o ios_project/Classes/MainViewController.m normal i386 objective-c com.apple.compilers.llvm.clang.1_0.compiler CompileC build/ios_project.build/Debug-iphonesimulator/ios_project.build/Objects-normal/i386/AppDelegate.o ios_project/Classes/AppDelegate.m normal i386 objective-c com.apple.compilers.llvm.clang.1_0.compiler (2 failures) When I build the project with Xcode everything works fine but I´d prefer to use the command line tools. I got: Xcode 5.0 PhoneGap 2.9.1 and I have tried in 3.4.0 A: This error appears probably by using the workspace file. Trying with the xcode project directory should resolve the problem.
doc_23529313
After talking to their support I've been told the CSV needs to be ANSI encoded. How do I do that? My code: def to_csv attributes = %w{full_name street_address postal_code city} CSV.generate(headers: true, col_sep: ",") do |csv| csv << attributes orders.all.each do |order| csv << attributes.map{ |attr| order.address.send(attr) } end end end A: By default CSV uses Encoding.default_external as encoding, most likely this is UTF-8. In your case you have to override it, but first you need to know which ANSI encoding you actually need. (What is ANSI format?) Most likely you can use Windows-1252 or ISO-8859-1. Then you can set the external encoding of the CSV string like this: CSV.generate(headers: true, col_sep: ",", encoding: Encoding::ISO_8859_1) CSV.generate(headers: true, col_sep: ",", encoding: Encoding::WINDOWS_1252) Strings work, too: CSV.generate(headers: true, col_sep: ",", encoding: 'ISO-8859-1')
doc_23529314
I know the downstream request is being sent successfully and I'm receiving status code 200 from the response (and of course because the notification is being received on the emulator). When debugging on the devices however, the onMessageReceived in my FCMService class is not being called at all, whether in the foreground or background. It's definitely registered in the manifest and each device is using the same version of the application: <service android:name=".services.FCMService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> If there is any more information required, let me know. Thanks in advance. A: Why was this happening? I realised when I entered the version numbers into the question that it would have to do with Android Oreo. I was searching for issues with FCM and not recent changes the how notifications work. In Android 26+, notification channels have been introduced and are required if your app is targeting 26 and above (which I was). Because I updated the target SDK without thinking, I of course got hit with no notifications. How to fix it The easiest way is to just target API 25 but that's not ideal. What you can do is register notification channels. I've done this where I handle my notifications (so onMessageReceived) as it doesn't register the same channel more than once. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Set the default notification channel settings to be that of alert int importance = NotificationManager.IMPORTANCE_HIGH; String channel_id = ALERT_CHANNEL_ID; CharSequence channel_name = ALERT_CHANNEL_NAME; String channel_desc = ALERT_CHANNEL_DESC; // Logic to change the channel id, name and desc if required // Build and modify channel settings NotificationChannel channel = new NotificationChannel(channel_id, channel_name, importance); channel.setDescription(channel_desc); channel.enableLights(true); channel.enableVibration(true); // Create the notification channel notificationManager.createNotificationChannel(channel); } Then you want to change the notification builder: NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channel_id)
doc_23529315
but all of em have used on class only Enemies ? For example, I have: Enemies skeleton = new Enemies(100, 20); Enemies zombie = new Enemies(90, 30); Enemies warrior = new Enemies(80, 40); Enemies assassin = new Enemies(70, 30); Enemies[] enemy = {skeleton, zombie, warrior, assassin}; I have tried: int randEnemy = random.nextInt(enemy.length); it gives me random number only, but I want to get the name of a object String name = random.nextInt(enemy.length); from here I get error System.out.println(enemy.getClass().getSimpleName()); but it gives me the name of Class "Enemy" A: You could use reflection to obtain the variable names off of the heap or a neater soultion would be to use inherirence class Zombie extends Enemies { } Enemies zombie = new Zombie(90, 30); ... That way the enemy.getClass().getSimpleName() method would return Zombie. A: try String name = enemy.getName()); or System.out.println(enemy.getClass().getName()); Actualy solved here: How do I print the variable name holding an object?
doc_23529316
public class UsersBean { private List<User> allUsers; public UsersBean() { init(); } private void init() { UsersController.doInitialise(allUsers); } // getters, setters } public class UsersController { public static void doInitialise(List<User> users) { users = new ArrayList<User>(); UserDao userDao = new UserDaoImpl(); users = userDao.getAllEnities(); System.out.println(users.toString()); } } public class UserDaoImpl{ @Override public List<User> getAllEnities() { List<User> users= null; Session session = null; Transaction transaction = null; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); org.hibernate.query.Query query = session.createQuery("from User"); users= query.list(); transaction.commit(); } finally { session.close(); } return users; } } A: If you want to modify the content of the original list, don't assign another list object to it, this will have no effect. Instead, just alter the content directly, i.e : public static void doInitialise(List<User> users) { UserDao userDao = new UserDaoImpl(); users.addAll(userDao.getAllEnities()); System.out.println(users.toString()); } A: You are not assigning the value of allUsers into your UsersBean, probably that's why is not working. To have it working, refactor the doInitialise to return a List<User>, then, in the UsersBean, just assign the users. class UsersBean { private List<User> allUsers; public UsersBean() { init(); } private void init() { this.allUsers = UsersController.doInitialise(); } } public class UsersController { public static List<User> doInitialise() { UserDao userDao = new UserDaoImpl(); return userDao.getAllEnities(); } }
doc_23529317
location 1 (location_group_name, owner_id, admin_id) location 1.1 (name, address) location 1.1.1 (name) // DEVICE LIST device 1 (manufacturer_id, model_id, serial, purchase_date, service_date) Battery (manufacturer_id, model_id, purchase_date, service_date) Accesory 1 (manufacturer_id, model_id, purchase_date, service_date) Accesory 2 (...) Accesory n (...) device 2 Battery Accesory 1 Accesory 2 Accesory n device n // STAFF LIST person 1 (name, email) qualification 1 (type, date) qualification 2 (...) qualification n (...) person 2 person n location 1.1.2 location 1.1.n location 1.2 location 1.n location 2 location n I am currently thinking of inserting each device and person as a serialized multi-dimensional array, but I am not sure how well that will work due to the fact that a cron job script will check the service_date field every day and send automated emails to the admins and owners of the location groups if certain criterias are met. To complicate things further, the devices data should be searchable by model as well, in case of a recall, or by serial_number for quick find in case the user has lots of devices added and/or doesn't exactly know its location. If it's not too much to ask, I would also like to see a query example for the proposed data structure (only because I figure it would probably use joins and I am quite unfamiliar with them). Also if there is any extra info you need, please feel free to ask and I will gladly elaborate. Thank you in advance, any input will be more than appreciated ! A: I'm not entirely sure what you're trying to do here, but why all the hierarchy? This is some sort of store/device/employee model, correct? In a relational database, you can separate discrete information into their own sections and relate them on other tables. So if you have stores/devices/employees, you can have a "stores" table, a "devices" table, an "owners" table, an "employees" table, a "stores_employees" table, an "owners_stores" table, a "devices_stores" table (and you could track inventory in that), an "employees_qualifications" table, and so on.. A: Looks like you have a one to many relationship between location1.1.1 and device, and between location1.1.1 and person. I think you'll end up querying in a loop, or you're going to do a few large queries and loop to merge them together. Don't freak out about querying in loops. With prepared statements they don't have to be that slow.
doc_23529318
locations: string[]; builder() { this.locations = [ '01-34-56-75-41', '10-34-22-75-53', '26-34-34-75-63', '00-89-56-75-43', '10-34-56-75-43', '20-33-56-75-43', '00-34-56-75-43', '00-34-56-75-43', '00-34-56-75-43', '00-34-56-75-43', ]; } In my html: <div class="row"> <p id="p" style="font-size: 30px;">Máximo:<input style="margin-left: 10px; font-size: 30px;" type="text"> <div *ngFor="let ubicacion of ubicaciones"><button>{{ ubicacion | slice:0:2 }}</button></div> </div> With the pipe slice I managed to get the first two digits of each location and put them in a button but now I need to remove the duplicates and order them from smallest to largest. Help, please! A: This function will provide you with both sorted and "uniqued" array: const uniqueSort = array => { return array.sort((a, b) => parseInt(a.slice(0,2)) > parseInt(b.slice(0, 2)) ? 1 : -1) .filter((elem, i, arr) => { return !i || elem != arr[i - 1]; }); } Essentially, it first sorts the array based on the first two digits(0 - 2), and then loops through the array to return a new array which contains elements which occur only once. Given an input of: [ '01-34-56-75-41', '10-34-22-75-53', '26-34-34-75-63', '00-89-56-75-43', '10-34-56-75-43', '20-33-56-75-43', '00-34-56-75-43', '00-34-56-75-43', '00-34-56-75-43', '00-34-56-75-43' ] You will get an output of: [ "00-89-56-75-43", "00-34-56-75-43", "01-34-56-75-41", "10-34-22-75-53", "10-34-56-75-43", "20-33-56-75-43", "26-34-34-75-63" ] If you want to get only the elements given the first two numbers are unique, modify the filter function like so: .filter((elem, i, arr) => { return !i || parseInt(elem.slice(0, 2)) != parseInt(arr[i - 1].slice(0, 2)); }); which will result in: [ "00-89-56-75-43", "01-34-56-75-41", "10-34-22-75-53", "20-33-56-75-43", "26-34-34-75-63" ] The difference is that here, the function checks for only the first two digits instead of the element (string) as a whole against its predecessor. A: Finally this worked for me: Ts: ubicaciones = [ '01-34-56-75-41', '10-34-22-75-53', '26-34-34-75-63', '00-89-56-75-43', '10-34-56-75-43', '20-33-56-75-43', '00-34-56-75-43', '00-34-56-75-43', '00-34-56-75-43', '00-34-56-75-43', '21-34-56-75-43', ]; newUbicaciones = Array.from( new Set(this.ubicaciones.map((item) => item.substring(0, 2)).sort()) ); Html: <div *ngFor="let item of newUbicaciones"><button>{{item}}</button></div>
doc_23529319
Does anyone have any tips or suggestions on how to achieve this? A: When the data in column 1 is equal to the data in column 2, what is the harm in updating the row anyways? UPDATE table SET column2 = column1 The data is always set in column 2 but when it was already the same data then column 1 nothing has changed After reading your comment, I suggest the following: Remove column 2 and create a new table called previous_usernames Add 3 columns to that table id, user_id and username Update this table when the username is changed, not afterwards with a cron. That is unneccesary complicated. first run this query INSERT INTO previous_usernames (user_id, username) (SELECT id, username FROM users WHERE id = ?) Then run this query UPDATE users SET username = ? WHERE id = ? When you want to make sure that the old username is stored correctly you can use transactions After reading your new comments I suggest the following You could create a UNIQUE index on the username and GUID column and try to insert every row. When the username and GUID combination exists, the query will fail and the record not be inserted. How do I specify unique constraint for multiple columns in MySQL?
doc_23529320
the log of the program launched with eclipse in this case everything works ffmpeg version git-2019-12-29-e20c6d9 Copyright (c) 2000-2019 the FFmpeg developers built with gcc 9.2.1 (GCC) 20191125 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth --enable-libopenmpt --enable-amf libavutil 56. 38.100 / 56. 38.100 libavcodec 58. 65.100 / 58. 65.100 libavformat 58. 35.101 / 58. 35.101 libavdevice 58. 9.101 / 58. 9.101 libavfilter 7. 70.100 / 7. 70.100 libswscale 5. 6.100 / 5. 6.100 libswresample 3. 6.100 / 3. 6.100 libpostproc 55. 6.100 / 55. 6.100 Input #0, h264, from '.h264': Duration: N/A, bitrate: N/A Stream #0:0: Video: h264 (Main), yuv420p(progressive), 3840x2160 [SAR 1:1 DAR 16:9], 60 fps, 60 tbr, 1200k tbn, 120 tbc Output #0, mp4, to '.mp4': Metadata: encoder : Lavf58.35.101 Stream #0:0: Video: h264 (Main) (avc1 / 0x31637661), yuv420p(progressive), 3840x2160 [SAR 1:1 DAR 16:9], q=2-31, 60 fps, 60 tbr, 15360 tbn, 120 tbc Stream mapping: Stream #0:0 -> #0:0 (copy) Press [q] to stop, [?] for help [mp4 @ 000001cedad59440] Timestamps are unset in a packet for stream 0. This is deprecated and will stop working in the future. Fix your code to set the timestamps properly frame= 9273 fps=0.0 q=-1.0 Lsize= 121326kB time=00:01:17.26 bitrate=12863.3kbits/s speed= 207x video:121287kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.032451% This is where it gets complicated. You can observe the messages that FFMPEG returns to me when I launch my program compile in jar : > [h264 @ 0000017c43e5b700] error while decoding MB 58 6, bytestream -14 > [h264 @ 0000017c43e5b700] concealing 30951 DC, 30951 AC, 30951 MV > errors in I frame [h264 @ 0000017c43e49d80] Stream #0: not enough > frames to estimate rate; consider increasing probesize [h264 @ > 0000017c43e49d80] decoding for stream 0 failed This is the java code which thanks to the ProcessBuilder will launch FFMPEG : String urlVideoMp4 = movie.getPath().replace(".h264", ".mp4"); File videoFinal = new File(urlVideoMp4); //checking if new video exists : if not, creating it with FFMPEG LOG.info("moviePath : " + movie); ProcessBuilder processBuilder = new ProcessBuilder(FFMPEG, "-framerate", "60", "-r", "120", "-i", movie.getPath(),"-c:v", "copy", urlVideoMp4); LOG.debug(processBuilder.command()); processBuilder.inheritIO().start().waitFor(); return videoFinal;
doc_23529321
Here is the anchor tag: <a href="javascript:doMailto()">Sign up</a> And here is the script: var sMailto = "mailto:blah@email.com?body=Dear eyecare professional,%0A%0aTo help us schedule your upcoming webinar, please fill out and return the following information:%0A%0A• Name:%0A%0A• Preferred date of webinar* (any Wednesday at 6 pm EST):%0A%0A• City/State (Optional):%0A%0A• Comments/Questions/Feedback:%0A%0AUpon receipt, we will send you a link to an upcoming GoTo Meeting webinar on Macula Risk implementation in your clinic. These webinars are regularly held on Wednesdays at 6 pm EST.%0A%0A* If you would like to request training on any other date or time - please note this in the Comments section and we will do our best to accommodate your request.%0A%0AKind Regards,%0A%0AGerry Bruckheimer"; function doMailto() { document.location.href= sMailto; } The weird thing is that this works in every other browser except stupid IE 9. UPDATE: If you are experiencing a similar problem to mine, try using window.open(url). I realise its not a perfect solution but it works. A: The URL limit for IE9 is actually quite high at between 5120 and 5150 when following a link. Unfortunately a Javascript hack won't help here - the limit will still be in effect. I doubt that's the issue though. The message you're sending contains some characters that I wouldn't put in a URL, particularly "•". You should URL encode your message before putting it in a link (that last symbol encodes to %e2%80%a2 apparently). You can URL encode it in Javascript or manually encode it with an online tool before pasting it into the <a> tag. Some browsers are more relaxed than others in handling strange characters in URL (or in code in general). Hope that helps
doc_23529322
Also has some issues if i assign it to onload event. The page gets stuck and browser stops responding. A: The Kendo library seem to do an Ok job for me clientside but you do get some rendering issues now and then. You will get the best results from a server side rendering library. You can scrape the HTML from the DOM and send it server side to a rendering engine like ABCPDF and the results are usually pretty good.
doc_23529323
ERROR: no existe el cursor «cur_1» CONTEXT: función PL/pgSQL ganancias(text) en la línea 11 en FETCH SQL state: 34000 CREATE OR REPLACE FUNCTION ganancias(p_jugador text) RETURNS Integer AS $$ DECLARE reg1 RECORD; reg2 RECORD; cur_1 CURSOR FOR SELECT DISTINCT(id_mano) FROM movimientos where nombre_jugador=p_jugador; cur_2 CURSOR FOR SELECT * FROM movimientos where id_mano = reg1.id_mano and linea =(select min(linea) from movimientos where id_mano=reg1.id_mano); v_cont INTEGER =0; v_contAux INTEGER=0; BEGIN OPEN cur_1; LOOP FETCH cur_1 INTO reg1; EXIT WHEN NOT FOUND; OPEN cur_2; LOOP FETCH cur_2 INTO reg2; EXIT WHEN NOT FOUND; v_cont=reg2.stack; v_cont= v_cont - v_contAux; v_contAux=reg2.stack; END LOOP; CLOSE cur_1; END LOOP; CLOSE cur_2; RETURN v_cont; END $$ LANGUAGE 'plpgsql'; A: cur_2 is a cursor variable in PL/pgSQL, and you cannot use it in the SQL command FETCH without knowing the name of the cursor itself. This is confusing, and I cannot explain it better without describing a lot of internal information. Suffice it to say that you do not use FETCH in PL/pgSQL. This is the way to go: DECLARE reg1 record; BEGIN FOR reg1 IN SELECT DISTINCT(id_mano) FROM movimientos WHERE nombre_jugador=p_jugador LOOP /* handle the row */ END LOOP; END; I am sure that what you are trying to do can be expressed more efficiently than with nested cursor loops.
doc_23529324
["2", "Something1", "Something2", "4", "Something3", "Something4", "Something5", "Something6", "2", "Something7", "Something8"] The number indicates how big the chunk should be. const splitInput = (input: string[]) => { const chunks: string[][] = []; input.forEach((element) => { if (element.length === 1) { const chunk = input.splice(input.indexOf(element) + 1, parseInt(element)); console.log(chunk); chunks.push(chunk) } }); The code above works only until there's no same numbers, since indexOf finds the first occurence. How can I either calculate fromIndex of indexOf() properly or remove all the removed elements from the array (including the numbers)? This would be the expected output [ ["Something1", "Something2"], ["Something3","Something4","Something5","Something6"],["Something7", "Something8"] ] Before anyone asks, yes this is a part (not the whole thing, this is just a beginning, I'm going to have to do something with the chunks) of my homework. I have been trying everything for the past 2 hours and couldn't figure it out. A: I don't know how to fix your approach but another approach is to iterate over the chunk sizes and fill another array with the chunks: function splitInput(elements) { const result = []; for (let i = 0, end = elements.length; i < end; i += 1 + +elements[i]) { result.push(elements.slice(i + 1, i + 1 + +elements[i])); } return result; } const elements = ["2", "Something1", "Something2", "4", "Something3", "Something4", "Something5", "Something6", "2", "Something7", "Something8"]; console.log(splitInput(elements));
doc_23529325
bin |-- Coin4d.dll `-- Coin4d.pdb lib |-- Coin4d.lib Which looks fine to me. Then, we are using qmake to build our final executable. In my qmake .pro file I have LIBS += -lCoin4d However, when the final .exe is linked together using the Visual Studio 2015 linker, then I see that it first searches for (and finds) Coin4d.lib: Searching D:/SVN/simcad/trunkd/ThirdParty/Coin/install/lib\Coin4d.lib: However, a bit later, I get the linker error LINK : fatal error LNK1104: cannot open file 'Coin4sd.lib' Mind the extra 's' in the library file name here! I have no idea why the linker is also looking for Coin4sd.lib after it found Coin4d.lib. I would like to systematically find this out, but don't know where to start. So my question is: what tools/commands can I use to systematically find out why my linker is also searching for Coin4sd.lib after it apparently first found Coin4d.lib? Should I investigate the libraries that are used to build the final executable too, and check if any of those somehow refer to Coin4sd.lib? A: I found out that I was using COIN_DLL as define, which apparently caused me to have the Coin4d.* filenames. When I use COIN_NOT_DLL then if I understand things correctly, the static version of the library (which has filename Coin4sd.*) gets built and then my linker no longer complains.
doc_23529326
"Cannot insert an explicit value into a timestamp column. Use INSERT with a column list to exclude the timestamp column, or insert a DEFAULT into the timestamp column." Code: SELECT TOP(0) * INTO #TEMP_TABLE FROM ACTUAL_TABLE; DELETE A FROM ACTUAL_TABLE A INNER JOIN ACTUAL_TABLE_2 B ON A.ID = B.ID AND A.SECOND_ID = B.SECOND_ID I want to delete everything from the actual table but it keeps throwing this error ACTUAL_TABLE_2 only has an ID and Second Id but I don't think that should matter.. but maybe it needs a date? I don't know I'm confused as to why it would be throwing this error. ACTUAL_TABLE does have timestamp columns but I just want to delete them. A: You have to exclude the timestamp field because they can't be inserted into. To do that, you have to pick all of the other columns manually. Syntax: DELETE A OUTPUT DELETED.col1, DELETED.col2, etc INTO #TEMPTABLE (col1, col2, etc) FROM ACTUAL_TABLE A INNER JOIN ACTUAL_TABLE_2 B ON A.ID = B.ID AND A.SECOND_ID = B.SECOND_ID
doc_23529327
He says that import answer has a lot of information and I should get it from my code but when I check imports parameters I just get a structure, there are not tables in rfc answer He says that when RFC is run from SAP GUI It returns a table but when I call it from COM /OLE there are not Does import structure have information? Should rfc return a table with information? Is there something missing in RFC answer? I hope somebody can explain me how a RFC works because I think rfc needs something else to work. A: The OLE object that represents the RFC- function (lets call it rfcFuncObject) has a member tables. e.g.: Object rfcFuncObject = functionCtrl.Add("RFC_CUSTOMER_GET") Object rfcTable = theFunc.tables Object customerItem = rfcTable.Item("CUSTOMER_T") See a complete example at help.sap.com
doc_23529328
SOAP XML Tag <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/"> <soapenv:Header/> <soapenv:Body> <tem:GetForexStocksandIndexesInfo> <tem:request> <tem:IsIPAD>true</tem:IsIPAD> <tem:DeviceID>test</tem:DeviceID> <tem:DeviceType>ipad</tem:DeviceType> <tem:RequestKey>%%UmVxdWVzdElzVmFsaWQxNjowNToyMDEyIDExOjU0%%</tem:RequestKey> <tem:Period>Day</tem:Period> </tem:request> </tem:GetForexStocksandIndexesInfo> </soapenv:Body> </soapenv:Envelope> And my Class to consume data public void CallWebService() { final Date date = new Date(); final String getCurrentDate = new SimpleDateFormat("dd:MM:yyyy HH:mm", Locale.ROOT).format(date); Thread thread = new Thread(new Runnable() { @Override public void run() { key = encryptManager.PushData("RequestIsValid" + getCurrentDate); Log.i("Key: ", key); key2 = sharesandIndexesListManager.PushData2("true","test","ipad",key,"Day"); Log.i("Key2: ", key2); } }); thread.start(); } I see "key" var in log cause I see type of the variable in the web url but I dont see types of the variables, -for instance tem:DeviceType- in the web url. In addition Key2 returns null. Please help me:) Thanks. And the error: org.xmlpull.v1.XmlPullParserException: unexpected type (position:END_DOCUMENT null@1:1 in java.io.InputStreamReader@21da6108) A: I recommend using ksoap2-android library for parsing. If you don't know type of the value simply use getPropertyAsString on SoapObject you'll be getting. Try this: SoapObject messageObject = (SoapObject) response.getProperty("request"); // Fetches last from above oject String lastAsString = messageObject.getPropertyAsString("DeviceID"); Look SoapObject methods here http://kobjects.org/ksoap2/doc/api/ Let me know if it helps. UPD: public class DeviceDetail implements KvmSerializable { public String IsIPAD = null; public String DeviceID= null; //TODO: ADD MORE VALUES YOURSELF! LIKE DeviceType private final String DATA_NAMESPACE = "http://schemas. YOUR SCHEMA HERE"; public DeviceDetail () { } @Override public Object getProperty(int arg0) { switch (arg0) { case 0: return this.IsIPAD; case 1: return this.DeviceID; } return null; } @Override public int getPropertyCount() { //TODO: change to number of items accordingly return 2; } @SuppressWarnings("rawtypes") @Override public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) { arg2.namespace = DATA_NAMESPACE; switch (arg0) { case 0: arg2.type = PropertyInfo.STRING_CLASS; arg2.name = "IsIPAD"; break; case 1: arg2.type = PropertyInfo.STRING_CLASS; arg2.name = "DeviceID"; break; default: break; } } @Override public void setProperty(int arg0, Object arg1) { switch (arg0) { case 0: this.IsIPAD= arg1.toString(); break; case 1: this.DeviceID= arg1.toString(); break; default: break; } } } First create request on server based on your needs: //TODO: change to appropriate values String METHOD_NAME = "MyMethod"; String INTERFACE = "IMyInterface"; String NAMESPACE = "http://tempuri.org/"; String SOAP_ACTION = NAMESPACE + INTERFACE + "/" + METHOD_NAME; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("APIKey", API_KEY); request.addProperty("AuthToken", AuthToken); request.addProperty("UserID", 1); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); Then you can execute call and parse your soap data: HttpTransportSE androidHttpTransport = new HttpTransportSE(SERVER_URL); androidHttpTransport.call(SOAP_ACTION, envelope);// call DeviceDetail responseObject = (DeviceDetail)envelope.bodyIn; //TODO: in responseObject now your data. String ssIPAD = responseObject.IsIPAD ; Here you can find ksoap turorial with some explanation: http://seesharpgears.blogspot.com/2010/10/ksoap-android-web-service-tutorial-with.html
doc_23529329
I'm looking for making a regexp that match the hex color syntax (like #34ffa6) Then I looked at the w3school page: Javascript RegExp Object Then that's my regexp: /^#[0-9a-f]{6}/i It seems to work but, if I want it to match also the "short hex color syntax" form? (like #3fa), it's possible? I've tried using the character | but maybe I'm wrong with the syntax. A: /^#[0-9a-f]{3,6}$/i would match #abc, #abcd, #abcde, #abcdef /^#([0-9a-f]{3}|[0-9a-f]{6})$/i would match #abc and #abcdef but not #abcd /^#([0-9a-f]{3}){1,2}$/i would match #abc and #abcdef but not #abcd /^#(?:[0-9a-f]{3}){1,2}$/i would match #abc and #abcdef but not #abcd Have a look at RegExp - MDN to learn more about regular expressions in javascript. A: Try this : /^#([0-9a-f]{6}|[0-9a-f]{3})$/i [0-9a-f]{6} = 6 characters [0-9a-f]{3} = 3 characters $ = end A: this should work /#[0-9a-f]{6}|#[0-9a-f]{3}/gi and for trying out regular expressions on the fly and learning it you can use this site http://gskinner.com/RegExr/ A: You might want to incorporate 4 and 8 digit hex for #RGBA and #RRGGBBAA. I am doing this in a different setting where I'm using match() and split() to generate arrays. I could not get all the variations posted by @rodneyrehm to work with the g flag and match, but the first (and most verbose) solution works if I list the character count in high to low order: 8, 6, 4, 3. let rx = /(?:#)[0-9a-f]{8}|(?:#)[0-9a-f]{6}|(?:#)[0-9a-f]{4}|(?:#)[0-9a-f]{3}/ig let s = "123 #AA22CC 100% #12F abc #A2Cd #aa11cc44 test 236px"; let arr = s.match(rx); // arr == ["#AA22CC", "#12F", "#A2Cd", "#aa11cc44"] The MDN docs say that (?:#) should forget "#", but it does not, and (?=#) simply fails. What am I misunderstanding? My final goal is to include the other numeric values in the array returned from match(). I'm almost there... A: The possible Hex Colors are - Format Example #RGB #F00 #RGBA #F005 #RRGGBB #FF7C00 #RRGGBBAA #FF7C0016 Regexp to match color without alpha let regex = /^#([A-F0-9]{3}|[A-F0-9]{6})$/i Regexp to match color with alpha let regex = /^#([A-F0-9]{3,4}|[A-F0-9]{6}|[A-F0-9]{8})$/i
doc_23529330
This is how the form looks like class AddExpenses(Form): reason = wtforms.StringField('reason', [validators.Required()]) amount = wtforms.IntegerField('amount', [validators.Required()]) allnames = [] allnames = getSalesman() salesperson = wtforms.SelectField('salesperson', choices=[names for names in allnames]) submitfield = wtforms.SubmitField('Submit') getSalesman() function is used to query the database and get the choices. A: Why not get the choices in the view function that requires the form? For example @app.route('/index') def index(): form = AddExpenses() allnames = getSalesman() form.salesperson.choices = [names for names in allnames] ... You may also want to use some caching on getSalesman() if the database will not change often.
doc_23529331
Does anyone know what may be causing this issue? I have tried setting up a different client id for it but I get the same result, I have tried connecting many different ways including trying the force authentication, but still the same result. A: I ran into this same problem despite specifying the "offline" access_type in my request as per bonkydog's answer. Long story short I found that the solution described here worked for me: https://groups.google.com/forum/#!topic/google-analytics-data-export-api/4uNaJtquxCs In essence, when you add an OAuth2 Client in your Google API's console Google will give you a "Client ID" and an "Email address" (assuming you select "webapp" as your client type). And despite Google's misleading naming conventions, they expect you to send the "Email address" as the value of the client_id parameter when you access their OAuth2 API's. This applies when calling both of these URL's: * *https://accounts.google.com/o/oauth2/auth *https://accounts.google.com/o/oauth2/token Note that the call to the first URL will succeed if you call it with your "Client ID" instead of your "Email address". However using the code returned from that request will not work when attempting to get a bearer token from the second URL. Instead you will get an 'Error 400' and an "invalid_grant" message. A: I encountered the same problem. For me, I fixed this by using Email Address (the string that ends with ...@developer.gserviceaccount.com) instead of Client ID for client_id parameter value. The naming set by Google is confusing here. A: We tried so many things, and in the end the issue was that the client had turned "Less Secure App Access" off in their Google Account settings. To turn this on: * *Go to https://myaccount.google.com/ and manage account *Go to the Security tab *Turn Less secure app access on I hope this saves someone some time! A: I ran into this problem when I didn't explicitly request "offline" access when sending the user to the OAuth "Do you want to give this app permission to touch your stuff?" page. Make sure you specify access_type=offline in your request. Details here: https://developers.google.com/accounts/docs/OAuth2WebServer#offline (Also: I think Google added this restriction in late 2011. If you have old tokens from before then, you'll need to send your users to the permission page to authorize offline use.) A: My issue was that I used this URL: https://accounts.google.com/o/oauth2/token When I should have used this URL: https://www.googleapis.com/oauth2/v4/token This was testing a service account which wanted offline access to the Storage engine. A: This is a silly answer, but the problem for me was that I failed to realize I already had been issued an active oAuth token for my google user which I failed to store. The solution in this case is to go to the api console and reset the client secret. There are numerous other answers on SO to this effect for example Reset Client Secret OAuth2 - Do clients need to re-grant access? A: If you're testing this out in postman / insomnia and are just trying to get it working, hint: the server auth code (code parameter) is only good once. Meaning if you stuff up any of the other parameters in the request and get back a 400, you'll need to use a new server auth code or you'll just get another 400. A: Using a Android clientId (no client_secret) I was getting the following error response: { "error": "invalid_grant", "error_description": "Missing code verifier." } I cannot find any documentation for the field 'code_verifier' but I discovered if you set it to equal values in both the authorization and token requests it will remove this error. I'm not sure what the intended value should be or if it should be secure. It has some minimum length (16? characters) but I found setting to null also works. I am using AppAuth for the authorization request in my Android client which has a setCodeVerifier() function. AuthorizationRequest authRequest = new AuthorizationRequest.Builder( serviceConfiguration, provider.getClientId(), ResponseTypeValues.CODE, provider.getRedirectUri() ) .setScope(provider.getScope()) .setCodeVerifier(null) .build(); Here is an example token request in node: request.post( 'https://www.googleapis.com/oauth2/v4/token', { form: { 'code': '4/xxxxxxxxxxxxxxxxxxxx', 'code_verifier': null, 'client_id': 'xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com', 'client_secret': null, 'redirect_uri': 'com.domain.app:/oauth2redirect', 'grant_type': 'authorization_code' } }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log('Success!'); } else { console.log(response.statusCode + ' ' + error); } console.log(body); } ); I tested and this works with both https://www.googleapis.com/oauth2/v4/token and https://accounts.google.com/o/oauth2/token. If you are using GoogleAuthorizationCodeTokenRequest instead: final GoogleAuthorizationCodeTokenRequest req = new GoogleAuthorizationCodeTokenRequest( TRANSPORT, JSON_FACTORY, getClientId(), getClientSecret(), code, redirectUrl ); req.set("code_verifier", null); GoogleTokenResponse response = req.execute(); A: There are two major reasons for invalid_grant error which you have to take care prior to the POST request for Refresh Token and Access Token. * *Request header must contain "content-type: application/x-www-form-urlencoded" *Your request payload should be url encoded Form Data, don't send as json object. RFC 6749 OAuth 2.0 defined invalid_grant as: The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client. I found another good article, here you will find many other reasons for this error. https://blog.timekit.io/google-oauth-invalid-grant-nightmare-and-how-to-fix-it-9f4efaf1da35 A: Solved by removing all Authorized redirect URIs in Google console for the project. I use server side flow when you use 'postmessage' as redirect URI A: I had the same error message 'invalid_grant' and it was because the authResult['code'] send from client side javascript was not received correctly on the server. Try to output it back from the server to see if it is correct and not an empty string. A: Try change your url for requst to https://www.googleapis.com/oauth2/v4/token A: You might have to remove a stale/invalid OAuth response. Credit: node.js google oauth2 sample stopped working invalid_grant Note: An OAuth response will also become invalid if the password used in the initial authorization has been changed. If in a bash environment, you can use the following to remove the stale response: rm /Users/<username>/.credentials/<authorization.json> A: The code you obtain in the URL after user consent has a very short expiry. Please obtain the code again and attempt to get access token within seconds (you have to hurry) and it should work. I can't find out the expiry period of code but it's literally very short. A: if you are using scribe library, for example to set up the offline mode, like bonkydog suggested. here is the code: OAuthService service = new ServiceBuilder().provider(Google2Api.class).apiKey(clientId).apiSecret(apiSecret) .callback(callbackUrl).scope(SCOPE).offline(true) .build(); https://github.com/codolutions/scribe-java/ A: In my case it was a callback URL that was different from the original request. So, callback URL should be the same for auth request and code exchange. A: I my case I just didn't read the documentation properly because I was trying to do const { tokens } = await oauth2Client.getToken(accessToken); every time to get an authorized client instance but for the subsequent requests you only need to include the refresh_token you store after the first user auth. oauth2Client.setCredentials({ refresh_token: `STORED_REFRESH_TOKEN` }); A: This can happen if your redirect_url is not the same as the one you have when creating the token on Google Gloud. So make sure it's correct A: Although this is an old question, it seems like many still encounter it - we spent days on end tracking this down ourselves. In the OAuth2 spec, "invalid_grant" is sort of a catch-all for all errors related to invalid/expired/revoked tokens (auth grant or refresh token). For us, the problem was two-fold: * *User has actively revoked access to our app Makes sense, but get this: 12 hours after revocation, Google stops sending the error message in their response: “error_description” : “Token has been revoked.” It's rather misleading because you'll assume that the error message is there at all times which is not the case. You can check whether your app still has access at the apps permission page. *User has reset/recovered their Google password In December 2015, Google changed their default behaviour so that password resets for non-Google Apps users would automatically revoke all the user's apps refresh tokens. On revocation, the error message follows the same rule as the case before, so you'll only get the "error_description" in the first 12 hours. There doesn't seem to be any way of knowing whether the user manually revoked access (intentful) or it happened because of a password reset (side-effect). Apart from those, there's a myriad of other potential causes that could trigger the error: *Server clock/time is out of sync *Not authorized for offline access *Throttled by Google *Using expired refresh tokens *User has been inactive for 6 months *Use service worker email instead of client ID *Too many access tokens in short time *Client SDK might be outdated *Incorrect/incomplete refresh token I've written a short article summarizing each item with some debugging guidance to help find the culprit. A: in this site console.developers.google.com this console board select your project input the oath url. the oauth callback url will redirect when the oauth success A: After considering and trying all of the other ways here, here's how I solved the issue in nodejs with the googleapis module in conjunction with the request module, which I used to fetch the tokens instead of the provided getToken() method: const request = require('request'); //SETUP GOOGLE AUTH var google = require('googleapis'); const oAuthConfigs = rootRequire('config/oAuthConfig') const googleOAuthConfigs = oAuthConfigs.google //for google OAuth: https://github.com/google/google-api-nodejs-client var OAuth2 = google.auth.OAuth2; var googleOAuth2Client = new OAuth2( process.env.GOOGLE_OAUTH_CLIENT_ID || googleOAuthConfigs.clientId, process.env.GOOGLE_OAUTH_CLIENT_SECRET || googleOAuthConfigs.clientSecret, process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl); /* generate a url that asks permissions for Google+ and Google Calendar scopes https://developers.google.com/identity/protocols/googlescopes#monitoringv3*/ var googleOAuth2ClientScopes = [ 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email' ]; var googleOAuth2ClientRedirectURL = process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl; var googleOAuth2ClientAuthUrl = googleOAuth2Client.generateAuthUrl({ access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token) scope: googleOAuth2ClientScopes // If you only need one scope you can pass it as string }); //AFTER SETUP, THE FOLLOWING IS FOR OBTAINING TOKENS FROM THE AUTHCODE const ci = process.env.GOOGLE_OAUTH_CLIENT_ID || googleOAuthConfigs.clientId const cs = process.env.GOOGLE_OAUTH_CLIENT_SECRET || googleOAuthConfigs.clientSecret const ru = process.env.GOOGLE_OAUTH_CLIENT_REDIRECT_URL || googleOAuthConfigs.callbackUrl var oauth2Client = new OAuth2(ci, cs, ru); var hostUrl = "https://www.googleapis.com"; hostUrl += '/oauth2/v4/token?code=' + authCode + '&client_id=' + ci + '&client_secret=' + cs + '&redirect_uri=' + ru + '&grant_type=authorization_code', request.post({url: hostUrl}, function optionalCallback(err, httpResponse, data) { // Now tokens contains an access_token and an optional refresh_token. Save them. if(!err) { //SUCCESS! We got the tokens const tokens = JSON.parse(data) oauth2Client.setCredentials(tokens); //AUTHENTICATED PROCEED AS DESIRED. googlePlus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) { // handle err and response if(!err) { res.status(200).json(response); } else { console.error("/google/exchange 1", err.message); handleError(res, err.message, "Failed to retrieve google person"); } }); } else { console.log("/google/exchange 2", err.message); handleError(res, err.message, "Failed to get access tokens", err.code); } }); I simply use request to make the api request via HTTP as described here: https://developers.google.com/identity/protocols/OAuth2WebServer#offline POST /oauth2/v4/token HTTP/1.1 Host: www.googleapis.com Content-Type: application/x-www-form-urlencoded code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7& client_id=8819981768.apps.googleusercontent.com& client_secret={client_secret}& redirect_uri=https://oauth2.example.com/code& grant_type=authorization_code A: For future folks... I read many articles and blogs but had luck with solution below... GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest( new NetHttpTransport(), JacksonFactory.getDefaultInstance(), "https://www.googleapis.com/oauth2/v4/token", clientId, clientSecret, authCode, "") //Redirect Url .setScopes(scopes) .setGrantType("authorization_code") .execute(); This blog depicts different cases in which "invalid_grant" error comes. Enjoy!!! A: for me I had to make sure that the redirect_uri is an exact match to the one in the developer console Authorised redirect URIs, that fixed it for me, I was able to debug and know what exactly was the issue after switching from https://accounts.google.com/o/oauth2/token to https://www.googleapis.com/oauth2/v4/token I got a proper error: {"error": "redirect_uri_mismatch", "error_description": "Bad Request"} A: I had this problem after enabling a new service API on the Google console and trying to use the previously made credentials. To fix the problem, I had to go back to the credential page, clicking on the credential name, and clicking "Save" again. After that, I could authenticate just fine. A: In my case, the issue was in my code. Mistakenly I've tried to initiate client 2 times with the same tokens. If none of the answers above helped make sure you do not generate 2 instances of the client. My code before the fix: def gc_service oauth_client = Signet::OAuth2::Client.new(client_options) oauth_client.code = params[:code] response = oauth_client.fetch_access_token! session[:authorization] = response oauth_client.update!(session[:authorization]) gc_service = Google::Apis::CalendarV3::CalendarService.new gc_service.authorization = oauth_client gc_service end primary_calendar_id = gc_service.list_calendar_lists.items.select(&:primary).first.id gc_service.insert_acl(primary_calendar_id, acl_rule_object, send_notifications: false) as soon as I change it to (use only one instance): @gc_service = gc_service primary_calendar_id = @gc_service.list_calendar_lists.items.select(&:primary).first.id @gc_service.insert_acl(primary_calendar_id, acl_rule_object, send_notifications: false) it fixed my issues with grant type. A: For me the issues was I had multiple clients in my project and I am pretty sure this is perfectly alright, but I deleted all the client for that project and created a new one and all started working for me ( Got this idea fro WP_SMTP plugin help support forum) I am not able to find out that link for reference A: If you are sanitizing user input (For example, $_GET["code"] in php) Make sure you don't accidentally replace something in the code. The regex I am using is now /[^A-Za-z0-9\/-]/ A: Look at this https://dev.to/risafj/beginner-s-guide-to-oauth-understanding-access-tokens-and-authorization-codes-2988 First you need an access_token: $code = $_GET['code']; $clientid = "xxxxxxx.apps.googleusercontent.com"; $clientsecret = "xxxxxxxxxxxxxxxxxxxxx"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v4/token"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "client_id=".urlencode($clientid)."&client_secret=".urlencode($clientsecret)."&code=".urlencode($code)."&grant_type=authorization_code&redirect_uri=". urlencode("https://yourdomain.com")); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch); curl_close ($ch); $server_output = json_decode($server_output); $access_token = $server_output->access_token; $refresh_token = $server_output->refresh_token; $expires_in = $server_output->expires_in; Safe the Access Token and the Refresh Token and the expire_in, in a Database. The Access Token expires after $expires_in seconds. Than you need to grab a new Access Token (and safe it in the Database) with the following Request: $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/oauth2/v4/token"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "client_id=".urlencode($clientid)."&client_secret=".urlencode($clientsecret)."&refresh_token=".urlencode($refresh_token)."&grant_type=refresh_token"); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch); curl_close ($ch); $server_output = json_decode($server_output); $access_token = $server_output->access_token; $expires_in = $server_output->expires_in; Bear in Mind to add the redirect_uri Domain to your Domains in your Google Console: https://console.cloud.google.com/apis/credentials in the Tab "OAuth 2.0-Client-IDs". There you find also your Client-ID and Client-Secret. A: There is a undocumented timeout between when you first redirect the user to the google authentication page (and get back a code), and when you take the returned code and post it to the token url. It works fine for me with the actual google supplied client_id as opposed to an "undocumented email address". I just needed to start the process again. A: For me, this was caused by subsequent getToken calls with the same code. Namely, in NestJS my callback endpoint was decorated with @UseGuards(AuthGuard('google')) and I tried to call getToken in the callback. A: Creation of the new Credentials key under: Was the honey for me. from: to: A: In my case I was trying to use gcloud APIs through a Go program running locally. I recently changed my user's password so I first tried gcloud auth login but it kept outputing the same invalid_grant error. Actually since you are not interacting directly with the api, your code is, you have to use gcloud auth application-default login instead. That fixed it for me. A: For me, I got to remove web cookies before testing Google connect link Api. A: None of the answer worked for me. After calling https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<CALLBACK_URL_YOU_SET_ON_GOOGLE>&prompt=consent&response_type=code&client_id=<YOUR CLIENT ID>&scope=openid%20email%20profile&access_type=offline I was getting response url in return which had code value 4%2F0ARtbsJoGfJYFT6Cy1VpPiONgYV1vIzVhGtTK9MvyQLZfuGv_sAPDRDOzqGkRu07qOIxBfg Instead of decoding the the url received I copied this value and passed to my app API and got the reported error invalid_grant. %2F in the above code should be replaced by /. It should be 4/0ARtbsJoGfJYFT6Cy1VpPiONgYV1vIzVhGtTK9MvyQLZfuGv_sAPDRDOzqGkRu07qOIxBfg Note that this code works only once. Lesson: Always decode the received url! A: Generating refresh and access token: Replace the essential values (code, client_id, client_secret) inside payload. let payload = { grant_type: 'authorization_code', code:'********FDLJli-DFJNLDLfKJ', client_id: '******.googleusercontent.com', client_secret: 'GOCS*******m5Qzg', redirect_uri: 'http://localhost:3000', }; axios .post(`https://oauth2.googleapis.com/token`, payload, { headers: { 'Content-Type': 'application/json;', }, }) .then((res: any) => { return res.data; }) .then((response: any) => { console.log('refresh token: ', response); }) .catch((err) => console.log('err: ', err)); You will get a response like this: { access_token: "********KAjJZmv4xLvbAIHey", expires_in: 3599, id_token: "***************VeM7cfmgbvVIg", refresh_token: "***************VeM7cfmgbvVIg", scope: "https://www.googleapis.com/auth/gmail.readonly openid ..... ..... https://mail.google.com/", token_type: "Bearer", } Save your refresh and access token. Now you can use refresh token to generate new access token! Here is an article on how you can integrate this on your react application. You can check this out for more details. Note: Do not request again and again for refresh token. They provide it only once. I faced some issues while requesting refresh token for more than 1 time.
doc_23529332
For example: mike.newsletter30@gmail.com mike.sfsd4f564s6df45ds@gmail.com mike.newsletter30u@gmail.com etc. I have setup sender access file, so I can block mails from specific servers like this: mike.newsletter30u@gmail.com REJECT But it's not enough. I need to setup more specific rule, for example all senders containing 'mike.' should be blocked in this case. Unfortunatelly, rule like this: mike. REJECT doesn't work. I've searched google and postfix docs I still can't figure out how to do this. Is this even possible? Do you have any ideas? A: 2 Years and no clarification :S Note that it is a regular expression, Using: /^(F|f)rom: *mike*@gmail.com/ won't work because you are thinking of * as a wildcard, regex uses * to match preceding character 0 or more times, the dot (.) is used to match any character, so the regex to match fsdghfsdjmike84329@gmail.com should be something like /^(F|f)rom: .*mike.*@gmail.com/ A: First ensure that you have enabled header checks in your main.cf header_checks = regexp:/etc/postfix/header_checks Then add a matching rule to your checks for example: /^(F|f)rom: mike.*@gmail.com/ REJECT JUNK is not allowed by this server Finally restart/reload postfix to active changes.
doc_23529333
<a th:text="#{login.signup}" href="/registration">Sign Up</a> A: try using thymeleaf's way of defining links, with: th:href="@{/registration}" More here
doc_23529334
$(document).ready(function(){ $("#AddButton").bind('click', function(event){ if(document.getElementById('optionselectthree').value=='drawtab') { divshow(); clone(); event.stopPropagation(); } else if(...) { .. } }); }); divshow() function: function divshow(){ var newImageBoxdiv = $(document.createElement('div')).attr("class",'demo'); newImageBoxdiv.html('<img id="Imagedisplay" style="background-repeat: no-repeat; width:auto; width:100%; height:100%; cursor:move; position:absolute;" />'); newImageBoxdiv.insertAfter("#imagedemo"); $('.demo').show(); } clone() function: function clone(){ var c=document.getElementById("can"); var d=c.toDataURL("image/png"); document.getElementById("Imagedisplay").src=d; } Hi Guys, I am trying to draw an image on canvas and then display the drawn image (clone() function) on div which is called dynamically using divshow() function. Problem is that when i click on #AddButton, it displays the div without the image when the image src is correct. A: I suspect you are setting src before toDataURL is finished. You may need to use a callback to fire once toDataURL is complete, and set src within that. Try logging the value of d right before you set src to check this. Unfortunately I've encountered this problem myself and don't know of a sure fire way to add a callback to toDataURL; toBlob has one but doesn't seem to be implemented properly yet.
doc_23529335
i can use JavaScript to display a message when hover on disabled checkbox , but is there a way to set a message in the below jsp to display a message when the checkbox is disabled. <div class="container sub-process" id="searchResultDiv-${searchList.makeUnique}"> <div align="center" class="form-group col-md-12 col-sm-12 input-group-xs paddingnarrow searchResultsDiv in" id="searchDiv-${modelClass.makeUnique}"> <table data-process-name="processName" class="has-tablesorter-childRow table-xcondensed col-md-12 col-sm-12 nopadding table-bordered tablesorter resultsTable" style="font-size:11px;"> <thead class="ui-widget-header"> <tr> <th id="select_box" class="tablesorter-ignoreColumn filter-false sorter-false">Select</th> </tr> </thead> <tbody> <fmt:setLocale value="en_US"/> <c:forEach var="box" begin="0" end="999" items="${searchList.modelClass}"> <c:choose> <c:when test="${not empty box.obj1 or not empty box.obj2}"> <c:set value="disabled" var="checkBoxDisabled"></c:set> </c:when> <c:otherwise> <c:set value="" var="checkBoxDisabled"></c:set> </c:otherwise> </c:choose> <tr class="table accordion-toggle className noHoverEffect" data-toggle="collapse" data-target="#uniqueId" id="className-uniqueId"> <td class="subClassName tablesorter-ignoreColumn"> <a href="#"> <input style="background-color:inherit; height:16px; min-width:8px; margin-top:1px;" class="form-control checkBox" type="checkbox" ${checkBoxDisabled} name="selectCheckBox"/> </a> </td> </tr> </c:forEach> </tbody> </table> </div>
doc_23529336
Products to be destroyed: «Prabo», «Palox 2000», «Remadon strong» (Rule). The customers «Dilora» and «Apple» has to be notified. I need to match every string within the «» quotes but ONLY in the period starting with the "Products to be destroyed:" pattern or ending with the (Rule) pattern. In other words in this example I do NOT want to match Dilora nor Apple. The regex to get the quoted contents in the capturing group is: «(.+?)» Is it possible to "anchor" it to either a following pattern (such as Rule) or even to a prior pattern (such as "Products to be destroyed:"? This is my saved attempt on regex101 Thank you very much. A: You can match at least a single part between the arrows, and when there is a match, extract all the parts using re.findall for example. The example data seems to be within a dot. In that case you can match at least a single arrow part matching any char except a dot using a negated character class. Regex demo for at least a single match, and another demo to match the separate parts afterwards import re regex = r"\bProducts to be destroyed:[^.]*«[^«»]*»[^.]*\." s = 'Products to be destroyed: «Prabo», «Palox 2000», «Remadon strong» (Rule). The customers «Dilora» and «Apple» has to be notified.' result = re.search(regex, s) if result: print(re.findall(r"«([^«»]*)»", result.group())) Output ['Prabo', 'Palox 2000', 'Remadon strong']
doc_23529337
The script runs perfectly fine if the database exists. If it doesn't exist, it fails with the message "the database doesn't exist", which makes perfect sense. Now, I don't it to fail so I added a check to select if the DB exists on sys.databases (which I will represent here with a IF 1=2 check for the sake of simplicity), so, if the DB exists (1=1), then run the "use" statement. To my surprise, the script kept failing. So I tried to add a TRY CATCH block. Same result. It seems that the use statement is evaluated prior to anything else, which id quite annoying because now my script may break. So my question is: how can I have an use statement on a script to a database that may not exist? BEGIN TRY IF (1=1) BEGIN --if DB exists USE DB_THAT_MAY_NOT_EXIST END END TRY BEGIN CATCH END CATCH A: I don't believe you can do what you want to do. The documentation specifies that use is executed at both compile time and execution time. As such, use on a database that does not exist is going to create a compile time error. I am not aware of a way to bypass compile time errors. As another answer suggests, use the database qualifier in all your names. You can also check if a database exists, without switching to it. Here is one way: begin try exec('use dum'); print 'database exists' end try begin catch print 'database does not exist' end catch A: How about this? May be you could check in this way. if db_id('dbname') is not null -- do stuff or try this: if not exists(select * from sys.databases where name = 'dbname') -- do stuff So for table: if object_id('objectname', 'somename') is not null or sp_msforeachdb ‘select * from ?.sys.tables’ Reference A: Off the top of my head, you could fully qualify all your references to avoid the USE statement. I hope someone comes up with a solution that requires less PT. After doing your check to see if the DB exists, instead of SELECT Moo FROM MyTable use SELECT Moo FROM MyDB.MySchema.MyTable
doc_23529338
NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown , handler: { (mouseEvent:NSEvent?) in .... A: For me, using the globalMonitor along with NSEvent's locationInWindow property seemed to output coordinates of the click, even when not on the window of the app. Here's my implementation: NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDown) { event in print(event.locationInWindow) } * *As a side note, the click coordinates go from (0,0) in the bottom left of my screen to (width,height) of my screen at the top right
doc_23529339
http://Domain.com/admin/sitecategory/add/ Although all other admin pages are working fine. I checked django logs, no errors. I ran the django test server and that specific page is working fine as well. nginx logs: 2013/06/15 13:37:01 [error] 1906#0: *4431 upstream prematurely closed connection while reading response header from upstream, client: 46.185.176.26, server: staging.myapp.com, request: "GET /admin/sitecategory/add/ HTTP/1.1", upstream: "uwsgi://unix:///tmp/myapp-staging.socket:", host: "staging.myapp.com", referrer: "http://staging.myapp.com/admin/sitecategory/" uwsgi logs: *** HARAKIRI ON WORKER 1 (pid: 1942, try: 1) *** *** backtrace of 1942 *** uwsgi(uwsgi_backtrace+0x25) [0x43ed95] uwsgi(what_i_am_doing+0x17) [0x43eeb7] /lib64/libc.so.6(+0x32920) [0x7fec48662920] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x2ee6) [0x7fec48cd64a6] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x50ad) [0x7fec48cd866d] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(+0x6ecbb) [0x7fec48c68cbb] /usr/lib64/libpython2.6.so.1.0(PyObject_Call+0x53) [0x7fec48c41243] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x2a1b) [0x7fec48cd5fdb] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x50ad) [0x7fec48cd866d] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x54ef) [0x7fec48cd8aaf] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x50ad) [0x7fec48cd866d] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x50ad) [0x7fec48cd866d] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(+0x6ecbb) [0x7fec48c68cbb] /usr/lib64/libpython2.6.so.1.0(PyObject_Call+0x53) [0x7fec48c41243] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x2a1b) [0x7fec48cd5fdb] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x50ad) [0x7fec48cd866d] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x50ad) [0x7fec48cd866d] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(+0x6ebc7) [0x7fec48c68bc7] /usr/lib64/libpython2.6.so.1.0(PyObject_Call+0x53) [0x7fec48c41243] /usr/lib64/libpython2.6.so.1.0(PyObject_CallFunctionObjArgs+0xb0) [0x7fec48c41bb0] /usr/lib64/libpython2.6.so.1.0(PyObject_Unicode+0x6a) [0x7fec48c7dc6a] /usr/lib64/libpython2.6.so.1.0(+0xb4c6a) [0x7fec48caec6a] /usr/lib64/libpython2.6.so.1.0(+0x9e633) [0x7fec48c98633] /usr/lib64/libpython2.6.so.1.0(PyObject_Call+0x53) [0x7fec48c41243] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x39ab) [0x7fec48cd6f6b] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalCodeEx+0x8de) [0x7fec48cd9c7e] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x50ad) [0x7fec48cd866d] /usr/lib64/libpython2.6.so.1.0(PyEval_EvalFrameEx+0x54ef) [0x7fec48cd8aaf] *** end of backtrace *** HARAKIRI: --- uWSGI worker 1 (pid: 1942) WAS managing request /admin/sitecategory/add/ since Sat Jun 15 16:36:49 2013 --- [pid: 1818|app: 0|req: 5/5] 46.185.176.26 () {38 vars in 694 bytes} [Sat Jun 15 16:37:01 2013] GET /favicon.ico => generated 5939 bytes in 113 msecs (HTTP/1.1 404) 1 headers in 51 bytes (1 switches on core 0) *** HARAKIRI ON WORKER 1 (pid: 1942, try: 2) *** DAMN ! worker 1 (pid: 1942) died, killed by signal 9 :( trying respawn ... I run uwsgi using upstart: exec uwsgi -b 25000 --chdir=/www/python/apps/myapp-staging/ --module=wsgi:application --env DJANGO_SETTINGS_MODULE=settings --socket=/tmp/myapp-staging.socket --processes=3 --harakiri=10 --max-requests=5000 --vacuum --master --pidfile=/tmp/myapp-staging-master.pid --uid=220 --gid=499 --daemonize=/www/uwsgi/myapp-staging.log and my nginx configs are as follows: server { server_name staging.myapp.com; root /www/python/apps/myapp-staging/; access_log /www/nginx/staging.myapp.com.access.log; error_log /www/nginx/staging.myapp.com.error.log; location /static/ { alias /www/python/apps/myapp-staging/static/; expires 30d; } location /media/ { alias /www/python/apps/myapp-staging/media/; expires 30d; } location / { uwsgi_pass unix:///tmp/myapp-staging.socket; include uwsgi_params; proxy_read_timeout 360; } } Anything wrong am doing here? Thanks A: Find one error in your nginx config file proxy_read_timeout 360; should read uwsgi_read_timeout 360; HttpUwsgiModule module has its own timeout directives. http://wiki.nginx.org/HttpUwsgiModule#uwsgi_read_timeout A: You set 10 seconds harakiri for a heavy view that very probably will require more time. Just remove it, measure how much time that view needs and reset it accordingly
doc_23529340
I have in Java an object of type Person which I serialized it and saved it as a BLOB in my Oracle database. I want in Pl/SQL to define type Person like CREATE OR REPLACE TYPE Person AS OBJECT with the same attributes and methods as in java and then read my Java serialized object from the database Into my PL/SQL Person Object. Java: Person java_person -------> serialization ------> write it to the database PL/SQL: plsql_person Person -----> read from the database the java_person into plsql_person
doc_23529341
I have a struct, within a class, which is in a namespace. In the class, there is a vector of my_struct's. namespace my_namespace { class my_class { public: struct my_struct { int a; int b; } std::vector<my_struct> my_vector; } } There is also a function (in example.h) that returns my_vector. The code above is #included in example.h. I'm trying to wrap this using SWIG so that I can access my_vector in Python. My SWIG file looks like this at the moment. I'm trying to use the nested workaround method. %module Example %{ #include "example.h" %} // Redefine struct class in global scope in order for SWIG to generate proxy class // Only SWIG parses this definition struct my_struct { int a; int b; }; %nestedworkaround my_namespace::my_class::my_struct; // We fooled SWIG into thinking that DtProgramMapping is a global struct // Now we need to trick the C++ compiler into understanding this apparent global type %{ typedef my_namespace::my_class::my_struct my_struct; %} %include "std_vector.i" %template(MyStructVector) std::vector<my_namespace::my_class::my_struct>; %include "example.h" If I define my_struct in example.h (without the namespace and class) everything works fine. But unfortunately in my application I'm not able to remove those. With this current code I get back a list of Swig objects that look like: <Swig Object of type 'std::vector< my_namespace::my_class::my_struct >::value_type *' at 0x7f82...> I want to be getting back a list of 'proxy of Swig Object...', as I'm able to access the members in that: <Example.my_struct; proxy of <Swig Object of type 'std::vector< my_struct >::value_type *' at 0x7f82...> >
doc_23529342
library(Genenet) data(arth800) subset = c(60, 141, 260, 333, 365, 424, 441, 512, 521, 578, 789, 799) arth12 = arth.expr[, subset] I would like the simulated data to look like the one shown below > str(arth12) num [1:22, 1:12] 6.59 6.33 7.12 6.9 7.22 ... - attr(*, "dimnames")=List of 2 ..$ : chr [1:22] "0-1" "0-2" "1-1" "1-2" ... ..$ : chr [1:12] "265768_at" "263426_at" "260676_at" "258736_at" > arth12[1:8,1:8] 265768_at 263426_at 260676_at 258736_at 257710_at 255764_at 255070_at 253425_at 0-1 6.589464 8.708049 6.802193 2.560715 5.958843 8.695228 8.556889 6.137504 0-2 6.329124 9.084011 6.923625 4.145677 5.632268 8.421644 9.479982 6.228819 1-1 7.116864 8.865733 7.795066 4.832890 5.289097 8.994071 8.355792 6.705978 1-2 6.898450 8.792790 7.941341 5.061776 5.741467 8.657854 9.210915 6.982994 2-1 7.224002 8.910793 7.991522 5.053111 5.402586 8.757223 8.178914 6.556123 2-2 6.993221 8.978710 8.093286 5.026800 5.812498 8.868823 8.981567 6.852998 4-1 7.266787 9.261390 8.396177 5.251719 6.133399 9.241745 7.596935 7.074677 4-2 7.483816 9.300124 8.137504 5.551516 5.794416 9.110092 7.914684 6.904484
doc_23529343
class Person(): def __init__(self, name): self.aname = name def __add__(self,other): x = self.person1 y = self.person2 print(x + y) return(Couple(x,y)) class Couple(Person): def __init__(self,person1,person2): self.person1 = person1 self.person2 = person2 What am i doing wrong? The error i get: Traceback (most recent call last): File "<pyshell#81>", line 1, in <module> acouple = p1 + p2 File "/Users/Desktop/NameP.py", line 7, in __add__ x = self.person1 AttributeError: 'Person' object has no attribute 'person1' A: A Person object only has aname so you should pass the currect object self and the added object: def __add__(self, other): return Couple(self, other) A: # This is what worked for me class Person(): def __init__(self, name): self.aname = name def __add__(self,other): x = self.aname y = self.aname print(self.aname + " " + other.aname) return(Couple(x,y)) class Couple(Person): def __init__(self,person1,person2): self.person1 = person1 self.person2 = person2 enter code here
doc_23529344
Hi Team, I have website. I need to click on more button ( 3 dots in screenshot) and then once popup click on "Export to Excel" //*[@id="OverflowButton_button0_account$button"] This is xpath retrieved from website. Once you click on this button a form opens which has Export to Excel button. for Export to Excel button doesnt has any inspect source. it doesnt has any id or name That 3 dots named "more.." Regards A: You can try this : driver=Webdriver.<>() driver.find_element_by_xpath('//*[@id="OverflowButton_button0_account$button"]')click() # You may need some delay here. driver.find_element_by_xpath("//*[contains(text(), 'Export to Excel')]").click()
doc_23529345
Tomcat description here ((int) The minimum number of established connections that should be kept in the pool at all times. The connection pool can shrink below this number if validation queries fail. Default value is derived from initialSize:10 (also see testWhileIdle) ) Spring support does not share any information about this attribute 29.1.2 Connection to a production database. I dont know if Spring Boot managers automatically the number of connections or the attribute appears with other name. A: You should be able to configure any of these properties in your application.properties with this prefix : spring.datasource.tomcat.min-idle=20 Note that kebabcase is used instead of camelcase: minIdle -> min-idle maxActive -> max-active
doc_23529346
C code= #include "stm32f10x.h" void TIM2_IRQHandler() { TIM2->SR =0x00; GPIOA->ODR ^=0x0008;//toggle pa3 } int main(void) { RCC->APB2ENR = 0x04; /// port a GPIOA->CRL = 0x00003000; __disable_irq(); RCC->APB1ENR =0x1;// timer2 TIM2->ARR = 0xffff; TIM2->PSC = 0x36; // 10hz TIM2->DIER = 0x1;// (OVERFLOW) TIM2->CR1 = 0x1; // TIMx_CR1.CEN NVIC_EnableIRQ(TIM2_IRQn); __enable_irq(); while(1) { } } Assembly code= EXPORT Program GPIOA_IDR EQU 0x40010808 GPIOA_CRL EQU 0x40010800 GPIOB_IDR EQU 0x40010C08 GPIOA_ODR EQU 0x4001080C RCC_APB2ENR EQU 0x40021000 RCC_APB1ENR EQU 0x40021000 TIM2_ARR EQU 0x4000002C TIM2_PSC EQU 0x40000028 TIM2_DIER EQU 0x4000000C TIM2_CR1 EQU 0x40000000 TIM2_SR EQU 0x40000010 AREA start, CODE, READONLY timer_ MOVS r0,#0x00 MOV r1,#0x40000000 STRH r0,[r1,#0x10] LDR r0,=GPIOA_ODR LDR r0,[r0,#0x00] EOR r0,r0,#0x08 LDR r1,=GPIOA_ODR STR r0,[r1,#0x00] ADDS R7,R7,#1 ;counter for debugging BX LR Program MOVS r0,#0x04 LDR r1,=RCC_APB2ENR STR r0,[r1,#0x18] ; pa3 out MOV r0,#0x3000 LDR r1,=GPIOA_CRL STR r0,[r1,#0x00] ADDS R11,R11,#1 CPSID I MOVS r0,#0x01 LDR r1,=RCC_APB1ENR STR r0,[r1,#0x1C] ; TIM2->ARR = 0xffff; MOVW r0,#0xFFFF LSLS r1,r1,#18 STRH r0,[r1,#0x2C] ; TIM2->PSC = 54; MOVS r0,#0x36 STRH r0,[r1,#0x28] ; TIM2->DIER = 0x1; MOVS r0,#0x01 STRH r0,[r1,#0x0C] ; TIM2->CR1 = 0x1; STRH r0,[r1,#0x00] MOVS r0,#0x1C BL timer_ CMP r0,#0x00 BLT interrupt ; NOP NOP AND r2,r0,#0x1F MOVS r1,#0x01 LSLS r1,r1,r2 LSRS r2,r0,#5 LSLS r2,r2,#2 ADD r2,r2,#0xE000E000 STR r1,[r2,#0x100] ADDS R8,R8,#1 ;counter for debugging NOP interrupt NOP ADDS R5,R5,#1 ;counter for debugging MOVS R6,#0x3 ;control CPSIE I NOP while B while MOVS R6,#0x7 ALIGN END
doc_23529347
public class Dependency{ Dependency(int number1, int number2, int number3, DependencyListener listener){} } each dependent class needs to path different arguments in order to instantiate a dependency. How should i define the module and the component that other classes could initiate it properly while transferring different values and passing 'this' as the listener? Also, How should i use the @Inject method in this case? Edit 1 @jeff-bowman I was thinking of using the following method: @Module public class DependencyModule { int first; int second; int third; DependencyListener listener; public DependencyModule(int first, int second, int third, DependencyListener listener) { this.first = first; this.second = second; this.third = third; this.listener = listener } @Provides Dependency provideDependency(int first, int second, int third, DependencyListener listener) { return new Dependency(first, second, third, listener) } } @Component(modules = { DependencyModule.class }) public interface DependencyComponent { void inject(DependentClass1 target); void inject(DependentClass2 target); void inject(DependentClass3 target); } and in each DependentClass i would do: public class DependentClass{ @Inject Dependency; public DependentClass{ DaggerDependencyComponent.builder().dependencyModule(new DependencyModule(first, second, third, this)).build().inject(); } } Is it a good practice? A: Conceptually, what you want is a Factory: /** Inject this wherever you want an instance of Dependency. */ public interface DependencyFactory { Dependency create( int number1, int number2, int number3, DependencyListener listener); } public class DependencyFactoryImpl implements DependencyFactory { @Inject Provider<SomeDaggerDepIfNeeded> someDaggerDepProvider; @Override public void create( int number1, int number2, int number3, DependencyListener listener) { return new Dependency(number1, number2, number3, listener, someDaggerDepProvider.get() /* if necessary */); } } However, because this is so easy to generate automatically, there are often built-in tools to do so. Guice calls this Assisted Injection, and supplies FactoryModuleBuilder (via an optional extension JAR) that reflectively generates factories at runtime. Dagger 2 doesn't have a built-in equivalent, mostly because Google has already released an open-source JSR-330 factory generator called AutoFactory that generates a factory for any JSR-330 implementation including Dagger, Guice, and Spring. @AutoFactory public class Dependency{ Dependency( int number1, int number2, int number3, DependencyListener listener, @Provided SomeDaggerDepIfNeeded somedaggerDep){} } See the AutoFactory documentation for details on its calls, particularly if you're interested in having the generated factory implement an interface. Using an interface you define explicitly can make it easier to work with generated code in IDEs. (If you don't have any need for dependencies from Dagger, or for substituting other implementations of this class to classes that depend on it, you can leave the class exactly as it is and treat the call to new as a factory.)
doc_23529348
<a href="${parentLink}#${menuItem.name}" class="${menuItem.classes[anchorClasses]}"> and there is a .js that makes my accordion opened on the new page $(document).ready(function () { if (location.hash != null && location.hash != "") { $('.collapse').removeClass('in'); $(location.hash + '.collapse').collapse('show'); } }); I think that you guys will need more info, so ask me anything that could help you. I'm new in this and I don't even know which code should I post here to help you guys realize what the problem is... Thank you (: A: One common way is to add an invisible pseudo element to the original target element of the link via CSS, like this: #your_anchor_id::before { display: block; content: " "; margin-top: -80px; height: 80px; visibility: hidden; pointer-events: none; } This will "extend" the element with that ID in a way which causes the anchor to be 80px above the main element, without causing any other visible changes. A: Another idea is to use smooth scrolling with an offset. (View the example "Full Page" by clicking that link at top right of the snippet window) $("nav ul li a").on('click', function(event) { if (this.hash !== "") { var myOffset = $('#myOff').val(); //get value from input (offset value) if (myOffset==='') $('input').addClass('alert'); event.preventDefault(); // Prevent default anchor click behavior var hash = this.hash; // Store hash // jQuery animate() method for smooth page scroll // 900 is the number of ms to scroll to the specified area $('html, body').animate({ scrollTop: $(hash).offset().top - myOffset }, 900); } // End if }); //$('div:contains(Section)').css('font-weight','bold'); html,body{margin:0;padding:0;font-family:Calibri;} body{height:2500px;} ul,li{margin:0;padding:0;} *{box-sizing:border-box;} section{ display: grid; place-items: center; width: 100%; height: 500px; } nav{position:fixed;width:80vw;background:white;border:1px solid red;} ::placeholder{color:#ccc;} nav ul li{ display: inline-block; padding:0; border: 1px solid rgba(200,200,200,0.3); } nav ul li:hover{background: #ddd;} a{text-decoration:none;padding:10px 25px;display:inline-block;} #one{background:palegreen; padding:50px;} #two{background:palegoldenrod;} #twa{background:lightblue;} #fer{height:1500px;} .alert{border:1px solid red;background:#ffc0cb99;} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav> <ul> <li>NAV / HEADER:</li> <li><a href="#one">One</a></li> <li><a href="#two">Two</a></li> <li><a href="#twa">Three</a></li> <li><input id="myOff" type="text" placeholder="Offset (e.g. 75):" /></li> </ul> </nav> <section id="one"> <div> <div style="text-align:center">Section One</div> <div>Directions:<br>(a) View as Full Page (link at top right)<br>(b) Enter offset number (for how many pixels the smooth-scroll will stop short)<br>(c) Click nav "Two" or "Three" and observe<br>(4) Repeat using a different offset value<br>Note: The fixed header is deliberately not full width in order to show the top of the next section scrolling UNDER the header (undesireable) The offset prevents that, and is what you are asking about.</div> </div> </section> <section id="two"> Section Two </section> <section id="twa"> Section Three </section> <section id="fer"> Section Four </section> Example code ripped off from: w3schools Company Theme example
doc_23529349
Q: How to get my converted value from the input of the textbox entered by the user into the second textbox? I am not sure how to fix the logic error which I am making. I am just converting the input into the new weight and put that value into the second textbox. Here is the code I have so far. namespace Your_weight_on_Saturn { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void label1_Click(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { var earthWeight = float.Parse(earthBox.Text); // holds the formula to calculate and find the value. var solve = (earthWeight / 9.81) * 10.44; MessageBox.Show("Your weight on saturn is" + solve); this.convertButton.Click += new EventHandler(button1_Click); } private void saturnBox_TextChanged(object sender, EventArgs e) { } } } A: Where you are initializing solve, just set the text of the other TextBox to Solve. Like this: solve = (earthWeight / 9.81) * 10.44; SecondTextBox.Text=solve.ToString(); // It will set text of Second TextBox to the value of solve A: simply convert it to float solve = (float) ((earthWeight / 9.81) * 10.44);
doc_23529350
import java.util.Scanner; public class Calculate{ public static void main(String args[]) { int age=0; String name=""; Scanner scan=new Scanner(System.in); System.out.println("Please Enter value of your age : "); age=scan.nextInt(); System.out.println("Please Enter value of your name : "); name=scan.nextLine(); System.out.println("Age : "+age+", Name : "+name); } } Now, Here the issue is taking String value from the user. I can take two INTEGER values from user one by one after pressing [ENTER]. But, In case of taking STRING value from the user Second time, It just let me out after I enter value for Age variable. If I first take the input for String and then INTERGER than it working fine as below : (First name and then age) : System.out.println("Please Enter value of your name : "); name=scan.nextLine(); System.out.println("Please Enter value of your age : "); age=scan.nextInt(); What might be the issue ? A: The problem occurs as you hit the enter key, which is a newline \n character. to add an additional scan.nextLine() after you read the int System.out.println("Please Enter value of your age : "); age=scan.nextInt(); scan.nextLine();// additional line A: The problem is with the scan.nextInt() method. It only reads the int value. So when you continue reading with scan.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine() Try this: import java.util.Scanner; public class Main{ public static void main(String args[]) { int age=0; String name=""; Scanner scan=new Scanner(System.in); System.out.println("Please Enter value of your age : "); age=scan.nextInt(); scan.nextLine(); // This line you have to add (It consumes the \n character) System.out.println("Please Enter value of your name : "); name=scan.nextLine(); System.out.println("Age : "+age+", Name : "+name); } } Output Please Enter value of your age : 20 Please Enter value of your name : ABC Age : 20, Name : ABC
doc_23529351
I am trying to find a way to use 2 shipping charges: If a customer order is less than n amount then shipping is standard x amount If a customer order is more than n amount then shipping is reduced to x amount I also need to hide the standard if the order qualifies for reduced shipping. Currently woocommerce displays both shipping charges if the order qualifies for reduced shipping Any ideas how i can resolve this please? Thanks A: Here is a custom function hooked in woocommerce_package_rates action hook that will show only one shipping rate based on the cart amount limit: add_filter( 'woocommerce_package_rates', 'hide_sshipping_rate_based_on_cart_amount', 100 ); function hide_sshipping_rate_based_on_cart_amount( $rates ) { // HERE define the limit amount to switch of shipping rate (integer) $amout_limit = 600; // Cart total amount (integer) $cart_total = WC()->cart->cart_contents_total; // Set below your 2 Rate ID slugs if( $cart_total >= $amout_limit ) unset( $rates['flat_rate:12'] ); // Removes the LOWER Rate else unset( $rates['flat_rate:8'] ); // Removes the HIGHER Rate return $rates; } Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
doc_23529352
This is source controller code public ModelAndView forwardRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception { //String urlToForward=httpServletRequest.getParameter("urlToForward"); httpServletRequest.getRequestDispatcher("postQuery.htm?actionCode=answerQuery%26queryListStatus=ANS%26strKey=90302140000326").forward(httpServletRequest, httpServletResponse); LoginForm loginForm = new LoginForm(); return new ModelAndView("homePage", "loginForm", loginForm); } error I got is 03/02/2014 20:34:07 ERROR PortalExceptionResolver:43] Exception ID (MESSAGE_KEY) : 1391439847740 : Request processing failed; nested exception is org.apache.tiles.definition.NoSuchDefinitionException: postQuery org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.apache.tiles.definition.NoSuchDefinitionException: postQuery at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:583) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329) at sun.reflect.GeneratedMethodAccessor289.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at net.bull.javamelody.JspWrapper.invoke(JspWrapper.java:151) at net.bull.javamelody.JdbcWrapper$DelegatingInvocationHandler.invoke(JdbcWrapper.java:282) at $Proxy34.forward(Unknown Source) at com.tcs.kra.tps.portal.controller.common.MainController.forwardRequest(MainController.java:1255) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.springframework.web.servlet.mvc.multiaction.MultiActionController.invokeNamedMethod(MultiActionController.java:473) at org.springframework.web.servlet.mvc.multiaction.MultiActionController.handleRequestInternal(MultiActionController.java:410) at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153) at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:203) at net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:181) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) Caused by: org.apache.tiles.definition.NoSuchDefinitionException: postQuery at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:578) at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) at org.springframework.web.servlet.view.tiles2.TilesView.renderMergedOutputModel(TilesView.java:75) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:257) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1183) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:902) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571) A: postQuery.htm See Caused by error is Tiles definition not declared in your Tiles.xml (apache tiles configuration file ) Ref: struts 2 tiles NoSuchDefinitionException i think you have to check your tiles definition
doc_23529353
let myArray : [Int] = [1, 1, 1] 3 numbers are an example. In the reality, it will be different each time. And I have variables of minimum and maximum let valueMin = 1 let valueMax = 500 I need to generate a FinalArray that will contain all the possible values ​​between min and max of each number of my initial array. Here is an example: for the beginning we have the first possibility and it's possibility001: [1, 1, 1] I add this value to my FinalArray var finalArray : [[Int]] = [] finalArray.append(possibility001) The second value: possibility002: [1, 1, 2] finalArray.append(possibility002) possibility003: [1, 1, 3] at one point, we will have possibility 14.944.020: [230, 182, 357] etc until possibilityFinal: [500, 500, 500] finalArray.append(possibilityFinal) How could I make multi dimensional loop to create it? A: You can probably do that using a recursive logic in a function: func possibleSums(min: Int, max: Int, length: Int) -> [Int] { guard length > 0 else { return [] } var sums = [Int]() for i in min...max { if length == 1 { sums.append(i) } else { let subSums = possibleSums(min: min, max: max, length: length - 1).map { $0 + i } sums.append(contentsOf: subSums) } } return sums } This will return an array with all possible sums including duplicate ones. But it will need to run like forever in your case: let sums = possibleSums(min: 1, max: 500, length: myArray.count) If you want to ditch the duplicate sum values, you can do something like this: func possibleSums(min: Int, max: Int, length: Int) -> [Int] { guard length > 0 else { return [] } var sums = [Int]() for i in min...max { if length == 1 { sums.append(i) } else { let subSums = possibleSums(min: i, max: max, length: length - 1).map { $0 + i } sums.append(contentsOf: subSums) } } return sums } This will also take a long time to finish. Update: To create a function that returns all the possible arrays without summing the numbers in each one, you can do something like this: func possibleArrays(min: Int, max: Int, length: Int) -> [[Int]] { guard length > 0 else { return [] } var arrays = [[Int]]() for i in min...max { if length == 1 { arrays.append([i]) } else { let subArrays: [[Int]] = possibleArrays(min: min, max: max, length: length - 1).map { var array = $0 array.insert(i, at: 0) return array } arrays.append(contentsOf: subArrays) } } return arrays }
doc_23529354
A: There is an implied unique index on the _id field of every collection which makes it impossible for two objects with the same _id to exist in the same collection. When two objects with the same _id value are stored with collection.save, one document will replace the other. When they are stored with collection.insert, one of the inserts will fail with a duplicate key error. But note that MongoDB ObjectIDs include a 24bit machine-ID. This makes it impossible for two clients to generate the same ID, unless they have the same machine-ID. And even then it's unlikely. That, of course, only applies when you let the MongoDB driver (or shell) auto-generate ObjectIDs. MongoDB allows to use any value of any type as a value for the _id field when you set it manually. When you do this (you shouldn't), it's your responsibility to ensure uniqueness.
doc_23529355
Nowadays we are using Eclipse to create the War( File -> Export -> War),but I did an Ant script that create a War but it's not compatible with Jboss. <zip destfile="${docflow4-web-home}/deploy/${nome}.war"> <zipfileset dir="${docflow4-web-home}/web" /> </zip> A: Replace "zip" with "war" and supply a web.xml for your war: <war destfile="${docflow4-web-home}/deploy/${nome}.war" webxml="path/to/web.xml"> <zipfileset dir="${docflow4-web-home}/web"/> </war> For more details, check out the documentation at http://ant.apache.org/manual/index.html A: Use the war tag instead of zip. (You can also create the WAR structure then just use the jar tag to create a WAR file.)
doc_23529356
After that error bottom navigation bar stop changing the current page's of pageview. PageController pageController; class MainController extends StatefulWidget { @override _MainControllerState createState() => _MainControllerState(); } class _MainControllerState extends State<MainController> with TickerProviderStateMixin { @override void initState() { // TODO: implement initState super.initState(); pageController = PageController(initialPage: 0, keepPage: true); } @override void dispose() { // TODO: implement dispose super.dispose(); pageController.dispose(); } PagesList() { return BlocBuilder<BottomnavbarcubitCubit, BottomnavbarcubitState>( builder: (context, state) { return Scaffold( body: PageView( allowImplicitScrolling: true, controller: pageController, onPageChanged: (int index) => state.currentIndex = index, children: [ NotificationsScreen(), NotificationsScreen(), NotificationsScreen(), NotificationsScreen(), ], ), bottomNavigationBar: NormalNavBar(), ); }, ); } } Bottomnavbar's onTap func that creates error try { if (pageController.hasClients) await pageController.animateToPage(state.currentIndex, duration: Duration(milliseconds: 500), curve: Curves.elasticOut); } catch (err) { print(err); } E/flutter (30081): #18 GestureBinding._handlePointerEvent package:flutter/…/gestures/binding.dart:295 E/flutter (30081): #19 GestureBinding._flushPointerEventQueue package:flutter/…/gestures/binding.dart:240 E/flutter (30081): #20 GestureBinding._handlePointerDataPacket package:flutter/…/gestures/binding.dart:213 E/flutter (30081): #21 _rootRunUnary (dart:async/zone.dart:1206:13) E/flutter (30081): #22 _CustomZone.runUnary (dart:async/zone.dart:1100:19) E/flutter (30081): #23 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7) E/flutter (30081): #24 _invoke1 (dart:ui/hooks.dart:265:10) E/flutter (30081): #25 _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5) A: It occurs when the data fetching from firestore is cancelled. Then bottom navigation bar not work until restart app.
doc_23529357
axUnityWebPlayer1.SendMessage( "Sphere", "Down", null );//called in winform Just use the code snippet above then we can send message from winform to its embeded unitywebplayer module. axUnityWebPlayer1_OnExternalCall_1(object sender,AxUnityWebPlayerAXLib._DUnityWebPlayerAXEvents_OnExternalCallEvent e) And by using the snippet above we can receive message from unitywebplayer in winform. I'm curious about the mechanism behind the api.Does it treat the file "*.unity3d" exported from unity3d as something like .dll,which makes the communication become function calling,and load it in runtime?
doc_23529358
template< typename T> struct A { A() : action_( [&]( const T& t) { }) {} private: boost::function< void( const T& )> action_; }; When compiling with Visual C++ 2010, it gives me a syntax error at construction of action_: 1>test.cpp(16): error C2059: syntax error : ')' 1> test.cpp(23) : see reference to class template instantiation A<T>' being compiled What is strange is that the same example, with no template parameter, compiles just fine: struct A { A() : action_( [&]( const int& t) { }) {} private: boost::function< void( const int& )> action_; }; I know that one workaround to the problem is to move the action_ initialization in the constructor body, instead of initialization list, like in the code below: template< typename T> struct A { A() { action_ = [&]( const T& t) { }; } private: boost::function< void( const T& )> action_; }; ... but I want to avoid such workaround. Did anybody encountered such situation? Is any explanation/solution to this so called syntax error? A: Broken implementation of lambdas in Visual C++ 2010? That's my best guess for an explanation. Although, I'm intrigued what capturing scope variables by reference does in this situtation... Nothing?
doc_23529359
@IBAction func pinchGestureActivated(_ sender: UIPinchGestureRecognizer) { imageView.transform = CGAffineTransform(scaleX: sender.scale, y: sender.scale) } A: This is what is happening: * *Your imageView is 100 x 100. *You pinch it, it goes down to 20 x 20. *Pinch ends. // Your imageView size hasn't changed. It has just been transformed. None of the changes reflect on it. *You pinch again. // The imageView is still 100 x 100. So the transformation takes place again from 100 x 100. When the transform property of any UIView subclass is not set to the identity, the frame won't actually be changed, and that is probably the reason you're observing this. We can work with that: @IBAction func pinchGestureActivated(_ sender: UIPinchGestureRecognizer) { imageView.transform = imageView.transform.scaledBy(x: sender.scale, y: sender.scale) } This should do the job :)
doc_23529360
var entity = landingPages.Select(x = new MyClass { name = x.name, age = x.age }); The only problem is that age is actually a coolection so I thought I would do this... var entity = landingPages.Select(x = new MyClass { name = x.name, age.add(x.age) }); But it dont work. Is this possible? A: var entity = landingPages.Select(x => new MyClass { //this is an initialization block. Only Property Assignment is allowed. name = x.name, age.add(x.age) //arbitrary statements are not allowed in initialization blocks. }); You didn't say which age was a collection (LandingPage's age or MyClass' age). If it's the LandingPage's age, then: convert the single value into a collection. IEnumerable<MyClass> query = landingPages.Select(x => new MyClass { name = x.name, age = new List<int>() { x.age } //this is a collection initializer }); If it's MyClass' age, then: convert the collection to a single value. IEnumerable<MyClass> query = landingPages.Select(x => new MyClass { name = x.name, age = x.age.Sum() });
doc_23529361
I want to know, how I can run my .m file (Matlab function files ) in Eclipse using Java? A: You should run your code by command line. So use a command line like this in a java command executor. "C:\<matlab path>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<program path>\mfile.m');exit;"
doc_23529362
<Window x:Class="TestDatabinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <TextBox Grid.Row="0" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="10,10,10,10"/> <Button Grid.Row="1" Content="Click me" Margin="10,10,10,10" Click="Button_Click"></Button> <Button Grid.Row="2" x:Name="a1" Content="ShowText" Margin="10,10,10,10" Click="a1_Click" ></Button> </Grid> Now the cs-file for this MainWindow looks like: using System.Windows; namespace TestDatabinding { public partial class MainWindow : Window { MainWindowViewModel mwvm; public MainWindow() { InitializeComponent(); mwvm = new MainWindowViewModel(); this.DataContext = mwvm; } private void Button_Click(object sender, RoutedEventArgs e) { mwvm.ChangeText(); this.DataContext = mwvm; } private void a1_Click(object sender, RoutedEventArgs e) { mwvm.showText(); } } } And last but not least the ViewModel Class: using System.ComponentModel; using System.Windows; namespace TestDatabinding { class MainWindowViewModel { public event PropertyChangedEventHandler PropertyChanged; private string text; public string Text { get { return this.text; } set { this.text = value; OnPropertyChanged("Text"); } } protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } public void ChangeText() { this.Text = "Hey paadddyy"; } public void showText() { MessageBox.Show(Text); } } } I didn´t implement ICommands, because this is a simple test. Now the Button's work correctly but the Textbox Text didn´t get updated. Any suggestions what i can do? I only want to display "Hey paadddyy" when I click the first Button. After I press the second Button and then the first the MessageBox shows "Hey paadddyy" but the Textbox text didn´t get updated :( Thank you for every hint ;) A: Your MainWindowViewModel does not implement INotifyPropertyChanged. It needs to look like that: class MainWindowViewModel: INotifyPropertyChanged you define the event but does not implement the interface A: It need to implement INotifyPropertyChanged I suggested that if you want to do something with Notify Property. Another easy way is to apply Caliburn.Micro Framework to your project. Follow this link.
doc_23529363
A little back story: I'm writing an app to display the waveform of an ongoing audio recording. I'm taking the bytes directly from an AudioRecord and calculating the amplitude every 1000ish samples and pushing them to a list that is then observed in a composable. The usage within the composable looks something like this: @Composable fun HomeScreen(vm: HomeViewModel = hiltViewModel()) { val data: SnapshotStateList<Int> = GlobalState.waveformBuffer Canvas( modifier = Modifier.fillMaxWidth().height(250.dp) ) { val canvasHeight = this.size.height data.forEachIndexed { i, value -> val spikeHeight = if (value > 0) value / 30f else 9f val spikeSize = Size(12f, spikeHeight) val spikeOffset = Offset( (i * (spikeSize.width + 6f)), canvasHeight / 2f - spikeSize.height / 2f ) val spikeColor = Color(0xFFFF0000) drawRoundRect( size = spikeSize, topLeft = spikeOffset, color = spikeColor, cornerRadius = CornerRadius(2f, 2f) ) } } } I am now trying to animate each line as it's being drawn to the canvas for the first time. The Google Recorder is a good example of this where each of the audio spikes "grows" to its designated height. Here's the Google Recorder example. I am basically trying to understand how I would animate the spikes just like they did. I've tried storing a whole lot of Animatables and using those but the state updates way too fast for it to be an efficient solution and the app just ended up crashing every time. A: I don't know anything about Compose, but it looks like you already know how to use it to draw bars to a Canvas? It might help to think of that video as a fixed set of positions - after a certain point horizontally, the bars are drawn at their full height. Before that, each position is drawn at a fraction of its full height - say 0%, 20%, 40%, 60%, 80%, 100%, 100%, 100%... As it "scrolls" and each spike is drawn further to the right, it's drawn closer to its actual height, until it's being drawn normally. Something like this: data.forEachIndexed { i, value -> val spikeHeight = if (value > 0) value / 30f else 9f val drawnHeight = (spikeHeight * (i / 5f)).coerceAtMost(1f) or you could use an interpolator to get smoother curves in the changes (so it doesn't just ramp from 0 to 100% although that might look fine!)
doc_23529364
A: Microsoft Speech Platform SDK 10.2 is the server version of SAPI. The server engines support lower quality audio, but don't support dictation. Also, the server versions of SAPI (I believe) have license restrictions that the desktop versions do not. The desktop engines are typically bundled with Windows, so if you have Vista or Windows 7, the desktop engine is built in; for XP, the desktop engine is free to use.
doc_23529365
long size; printf("Enter the size of the array to be sorted: "); scanf("%ld",&size); Can anybody tell me why? as based on my information, the range of long is much greater than 200,000 TIA Edit: the prev piece of code is followed by those declarations. int arrMerge[size]; int arrQuick[size]; int arrSelect[size]; int arrInsert[size]; When I've commented the whole program except those lines (and the ones above) it has crashed. The following terminating message was given: Process returned -1073741571 (0xC00000FD) execution time : 2.419 s Press any key to continue. A: According to this Microsoft documentation, the status code 0xC00000FD stands for STATUS_STACK_OVERFLOW. Your program is failing due to a stack overflow. By default, a Windows program has a maximum stack size of about 1 megabyte. If you enter the number 200000, then your variable-length arrays will exceed this limit, causing the stack overflow. You may want to consider allocating the memory for the arrays on the heap instead of the stack, for example using the function malloc. The heap does not have the limitation of only being able to allocate up to a single megabyte. It is able to store much larger amounts of data. A: After size is set to 200,000, these definitions: int arrMerge[size]; int arrQuick[size]; int arrSelect[size]; int arrInsert[size]; create arrays with automatic storage duration and size 800,000 bytes each, assuming int is four bytes, which is common today. That is a total of 3.2 MB. Automatic storage duration is typically implemented using a stack (except for effects of optimization), and default stack sizes are 8 MiB on macOS, 2 MiB on Linux, and 1 MiB on Microsoft Windows.1 Thus, the arrays overrun the space set for the stack, and the program crashes. Footnote 1 “MB” stands for megabyte, 1,000,000 bytes. “MiB” stands for Mebibyte, 220 bytes = 1,048,576 bytes.
doc_23529366
I tried to explain it all in the picture. A: Is it what you are looking for ? repro on Stackblitz Here is the code if you can't access stackblitz: import React, { Component } from "react"; import { render } from "react-dom"; import Hello from "./Hello"; import "./style.css"; const App = () => { // Hide/show main blocks const commonAction = () => { document.getElementById("container").classList.toggle("flex-col"); Array.from(document.getElementsByClassName("block")).forEach(el => { el.classList.toggle("hidden"); }); }; // On click on the main block const enlarge = e => { commonAction(); // Just show the one we clicked e.target.classList.remove("hidden"); // Enlarge it e.target.classList.add("enlarge"); // show/hide its details e.target.childNodes[1].classList.toggle("hidden"); }; // On click on the details const hide = e => { // Hide it e.target.classList.add("hidden"); // reset main blocks to their original state commonAction(); //reset main clicked block to its normal state const parent = e.target.closest(".block"); parent.classList.remove("hidden"); parent.classList.remove("enlarge"); e.stopPropagation(); }; return ( <> <div id="container"> <div className="block" onClick={enlarge}> Content 1 <div className="block-content hidden" onClick={hide}> Content details 1 </div> </div> <div className="block" onClick={enlarge}> Content 2 <div className="block-content hidden" onClick={hide}> Content details 2 </div> </div> <div className="block" onClick={enlarge}> Content 3 <div className="block-content hidden" onClick={hide}> Content details 1 </div> </div> </div> </> ); }; render(<App />, document.getElementById("root")); css : #container { display: flex; justify-content: space-between; height: 200px; } .flex-col{ flex-direction: column; } #container > * { position: relative; min-width: 25%; background-color: #6dd4fd; } .block-content { position: absolute; background-color: #ffb35c; top:0; bottom:0; left:0; right:0; } .hidden{ visibility: hidden; height:0px !important; } .enlarge{ width: 100% !important; height: 100% !important; display: block; }
doc_23529367
any user visits our site on desktop to see this video. But open this page on the mobile view to change video. in mobile view different video play. **Both Screen video autoplay ** Place help me how to possibly this. **this is my code..** <html> <head> <title>video</title> </head> <body> <video width="100%" height="100%"> <source src="https://www.w3schools.com/howto/rain.mp4" type="video/mp4"> <source src="https://www.w3schools.com/howtorain.ogg" type="video/ogg"> Your browser does not support the video tag. </video> </body> </html> open mobile view and desktop view plays different video and both autoplay. A: To play the video in mobile and desktop by giving a separate class Like.. <video class="desktop" controls autoplay> <source src="Fumefx colored smoke.mp4" type="video/mp4"> Your browser does not support the video tag. </video> <video class="mobile" controls autoplay> <source src="mobile.mp4" type="video/mp4"> Your browser does not support the video tag. </video> To us css to hide ad shoe... .desktop{ width:100%; height:100vh; display:block; } .mobile{ display:none; } @media only screen and (max-width: 600px) { .desktop{ display:none; } .mobile{ width:100%; height:100vh; display:block; } } A: For auto play video add an "autoplay" attribute on video tag. To use different video in desktop and mobile. Use different video TAG with different source file and use media query or java script to hide and show <html> <head> <title>video</title> </head> <body> <video width="100%" height="100%" autoplay> <source src="https://www.w3schools.com/howto/rain.mp4" type="video/mp4"> <source src="https://www.w3schools.com/howtorain.ogg" type="video/ogg"> Your browser does not support the video tag. </video> </body> </html>
doc_23529368
... content_type :json adam.to_json end #--> #<Human:0x10aa540 @x=68, @y=24, @name="Adam", @age=50> js with jquery: ... $("#player").html(data); ... resulting in div being populated with just "#" character. console.log(data) shows: #<Human:0x10aa540 @x=68, @y=24, @name="Adam", @age=50> So I'm guessing that happens because "<" and other characters are interpreted to html. How can I avoid it and show the object in a web page as it appears on debug console ? Thanks A: In case it helps : data.replace(/\</gi,"&lt;"); jsfiddle A: You can ask the browser to escape the HTML for you, by adding it to a temporary block and them retrieving the escaped content. This way, you ensure that all the HTML markup is escaped, not only the > and < : var temp_div = document.createElement('div'); // Create temporary div temp_div.appendChild(document.createTextNode(data)); // Insert data as Text data = temp_div.innerHTML; // Get Text escaped jsFiddle
doc_23529369
In frontend, I get Json from this url timezone json, and append each element into <option></option>, and I set if select box onchange: $(#fullcalendar).fullCalendar('option', 'timezone', this.value || false); * *What need to do in backend? *Should I set default timezone:"local" in init generate fullcalendar?
doc_23529370
android:id="@+id/topRight Thanks. A: When you define an ID in your layout, it simply modifies the auto-created R file with a new field. The name you specified will be the name of the variable (R.id.topRight). I guess you might be able to access the name of the variable via some reflection magic, but I feel like you're going about this in a wrong way. IDs are used to reference the view from the layout and create instances during runtime. If you want to have some string stored in the layout elements which you can use to determine what view you'd like to use, I would probably go with the "Tag" property rather than ID. Hope this helps. A: Look at this, I have a textView with editTextUserName as an id so I get its value like the one I posted. Try it, I hope it works for you. EditText editTextUserName = (EditText) findViewById(R.id.editTextUserName); <EditText android:id="@+id/editTextUserName" android:hint="User Name" android:layout_width="match_parent" android:layout_height="wrap_content">
doc_23529371
This is my IntelliJ project structure: A: I have found a way to build such projects which are not in default structure which eclipse supports. Import project then Move to Properties > java build path > source tab....remove path to src....add path to java folder in the source code using add folder button... then build your project as usual
doc_23529372
Postman post Example // Email model private String module; private String notificationGroupType; private String notificationGroupCode; private String notificationType; private String inLineRecipients; private String eventCode; private HashMap<String, Object> metaData; public EmailModel() { this.module = "tset"; this.notificationGroupType ="test"; this.notificationGroupCode =test"tset"; this.notificationType = "EMAIL"; this.inLineRecipients ="[test]"; this.eventCode = "DEFAULT"; this.metaData = metaData; } //Controller code private EmailModel em; @RequestMapping(value = "test", method = RequestMethod.GET) public void post() throws Exception { String uri= ""; EmailModel em = new EmailModel(); EmailModel data =em; HttpClient client = HttpClient.newBuilder().build(); HttpRequest request = HttpRequest.newBuilder() .headers("Content-Type", "application/json") .uri(URI.create(uri)) .POST(HttpRequest.BodyPublishers.ofString(String.valueOf(data))) .build(); HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding()); System.out.println(em); System.out.println(response.statusCode()); }
doc_23529373
I'm having some trouble getting the logs to work correctly though. What am I missing here? No error's are being thrown or logged and the app run smoothly, but nothing is being logged apart from the start-up logs: [2018-10-16 09:41:18 +0000] [1] [INFO] Starting gunicorn 19.9.0 [2018-10-16 09:41:18 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2018-10-16 09:41:18 +0000] [1] [INFO] Using worker: aiohttp.worker.GunicornWebWorker [2018-10-16 09:41:18 +0000] [16] [INFO] Booting worker with pid: 16 [2018-10-16 09:41:18 +0000] [17] [INFO] Booting worker with pid: 17 [2018-10-16 09:41:18 +0000] [18] [INFO] Booting worker with pid: 18 [2018-10-16 09:41:18 +0000] [19] [INFO] Booting worker with pid: 19 [2018-10-16 09:41:18 +0000] [20] [INFO] Booting worker with pid: 20 [2018-10-16 09:41:18 +0000] [21] [INFO] Booting worker with pid: 21 [2018-10-16 09:41:18 +0000] [22] [INFO] Booting worker with pid: 22 [2018-10-16 09:41:18 +0000] [23] [INFO] Booting worker with pid: 23 My app/init.py file is as such: import logging import os from logging import handlers from aiohttp.web import Application from app.routes import routes from utils.logging import CloggerFormatter def create_app(app_config): app = Application() logger = logging.getLogger('aiohttp.web') log_level = logging.DEBUG if os.environ.get('LOG_LEVEL'): log_level = os.environ['LOG_LEVEL'] app.router.add_routes(routes) logger.setLevel(log_level) logger.addHandler(CloggerFormatter) app['config'] = app_config return app And then in my app/routes.py file I access the logger with request.app.logger from within the rout definition like: from aiohttp.web import Response, RouteTableDef routes = RouteTableDef() @routes.post('/background-checks') async def api_background_check(request): request_identifier = request.headers.get('X-Request-ID') if not request_identifier: request_identifier = uuid.uuid4() request.app.logger.info('Checking background for request: %s', request_identifier) This is my utils/handlers/logging.py file: from time import strftime, gmtime from logging import Formatter class CloggerFormatter(Formatter): """ Logging module formatter in accordance with the yoti clogger manual guidelines. """ converter = gmtime def __init__(self, datefmt=None): fmt = ('level:%(levelname)s' '\ttime:%(asctime)s' '\tmessage:%(message)s') Formatter.__init__(self, fmt=fmt, datefmt=datefmt) def formatTime(self, record, datefmt=None): """ Return the creation time of the LogRecord using the RFC 3339 format if datefmt is not specified. """ ct = self.converter(record.created) if datefmt: s = strftime(datefmt, ct) else: t = strftime('%Y-%m-%dT%H:%M:%S', ct) s = '%s.%03dZ' % (t, record.msecs) return s A: Please use the root aiohttp logger: logger = logging.getLogger('aiohttp'). Particularly access logger uses 'aiohttp.access' name but maybe you want to see other log messages like errors and warnings as well.
doc_23529374
df_writer.saveAsTable('hive_table', format='parquet', mode='overwrite') I am getting following error: Caused by: org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: hdfs://hostname:8020/apps/hive/warehouse/testdb.db/hive_table at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:287) at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:229) I have the path till 'hdfs://hostname:8020/apps/hive/warehouse/testdb.db/' Please provide your inputs A: Try using DataFrameWriter as df.write.mode(SaveMode.Append).insertInto(s"${dbName}.${t.table}")
doc_23529375
"Array to string conversion" I am using codeigniter, i am getting post value in second array(listingdata) with method $this->input->post(); , but my first array getting some dynamic key and value then this two array diff give me output but some time getting error. Please Help me Any solution always welcome. if(isset($_POST)){ foreach($_POST as $key => $value) { $arr[$key] = $value; // making array } } $result = array_diff($arr,$listingdata); print_r($result); print_r($arr); print_r($listingdata); My $arr array Array ( [itemTitle] => fdafdas [subtitle] => fadsfdas [quantity] => 12 [itemDescription] => fdas [hide_ebay_id] => 89 [ebay_user] => Array ( [0] => ) [ebay_category] => 2984 [e_sub_cat] => 20433 [e_second_child_sub_cat] => 117027 [e_third_child_sub_cat] => [ebay_upc] => 31231241341 [Brand] => Unbranded [MPN] => Does_Not_Apply [Model] => fsdf [Country/Region_of_Manufacture] => Unknown [listingType] => FixedPriceItem [listingduration] => Days_5 [buy_it_now_price] => 20.00 [shippingtype] => Flat [fshippingservice] => USPSPriorityFlatRateBox [shippingservicecost] => 2.0 [shippingsac] => 3.0 [internationalhc] => [paypalemailaddress] => sam@jaff.in [dispatchtimemax] => 3 [location] => CA [ebaycountry] => [ebay_paypalemail] => [ReturnsAccepted] => ReturnsAccepted [returnswithin] => Days_14 [refundoption] => MoneyBack [shippingcostpaidbyoption] => Seller [policydescription] => wqdewvfdgbfdggrbf ) This is my another Array Array ( [itemTitle] => fdafdas [subTitle] => fadsfdas [categoryId] => 117027 [itemDescription] => fdas [listingType] => FixedPriceItem [listingDuration] => Days_5 [startPrice] => [buyItNowPrice] => 20.00 [quantity] => 12 [upc] => 31231241341 [paypalEmailAddress] => sam@jaff.in [returnWithin] => Days_14 [RefundOption] => MoneyBack [ShippingCostPaidByOption] => Seller [returnsAccepted] => ReturnsAccepted [shippingType] => Flat [cshippingService] => [fshippingService] => USPSPriorityFlatRateBox [dcPostalcode] => [ShippingServiceCost] => 2.0 [dshippingPackage] => [shippingHandlingcost] => [shippingServiceAdditionalCost] => 3.0 [currency] => USD [country] => [location] => CA [dispatchTimeMax] => 3 [pictureUrl] => Array ( [0] => http://jaftech.in/ashprey/uploads/69.jpg ) [policyDescription] => wqdewvfdgbfdggrbf [internationalShipping] => [internationalShippingType] => [internationalShippingServiceCost] => [internationalshippingServiceAdditionalCost] => [cinternationalshippingService] => [finternationalshippingService] => [internationalShipToLocation] => [internationaloriginatingPostalCode] => [internationalshippingHandlingcost] => [ishippingPackage] => PackageThickEnvelope [pid] => 89 ) A: This is because array_diff compares values after typecasting both compared values to string (see documentation notes). Both of your arrays contain another array (ebay_user and second pictureUrl). See this answer for recursive array_diff, which should work in your case.
doc_23529376
I've tried the following answers to no avail: * *How do I link to an external stylesheet in Ruby on Rails? - but the link given in the answer is not working. *How do I use CSS with a ruby on rails application? - which says to add stylesheet in public/stylesheets, but I do not have folder named public/stylesheets. I do have a public folder, but I have stylesheets folder under /vendor/assets. *css @import external style sheet - but it's unclear. A: I'm just going to assume you're already using something like this in your layout: stylesheet_link_tag 'application' If you want to refer to an external stylesheet then all you need to do is pass in the url. stylesheet_link_tag 'application', 'http://yui.yahooapis.com/2.8.1/build/reset/reset-min.css' If you want to include the actual files in your codebase: app/assets/stylesheets is where you should place your main css files. vendor/assets/stylesheets is where you should place the css files for any plugins that you might have. It's the same for js files. For example your application.js would go in app/assets/javascripts and a jquery plugin like timeago.js would go in vendor/assets/javascripts. A: After looking for a solution to this problem for a while, I found this step by step tutorial which explain how to implement a bootstrap theme to a rails app => http://www.notch8.com/implementing-a-bootstrap-theme/ You can apply this to other CSS and JS templates than a Bootstrap one. Hope this help (sorry if I make english mistakes)
doc_23529377
When rendering in HTML, content shown to user : select a, b, c from table; When user searches for select a in search field, this data is not shown as it does not match the underlying data. Similarly, the content has extra spaces which are all removed when showing in UI automatically by HTML, but search fails because of that. What is a solution that can enable user to search?
doc_23529378
@IBAction button_n_Action(_ sender:Any?) { if self.mode == server { // Server code } else { // Client code } } Only problem is n varies from 1 to 100, which to me sounds ugly, complex, repetitive code. Is there a cleaner, better, or clever way in Swift/XCode that I can easily separate client & server code?
doc_23529379
import requests from bs4 import BeautifulSoup url = 'https://digitalcoinprice.com' source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text, "html.parser") for link in soup.find_all('a', {'class': 'coin_currency_name'}): title = link.string print(title) my ultimate goal is to create a web crawler that will log the information of the top 100 cryptocurrencies every 5 minutes. I'd like to work this problem out but am struggling with this hurdle. when I run python wcrawl.py all it does is moves to where I can type a new command.... Sorry I'm not knowledgeable enough on the topic to give any more detail, I have been using python a whole 12 hours now. just some more info: Windows 10 inside Anaconda CMD Prompt Python 3.7.2 A: You should to find 'span' tag instead 'a' tag. import requests from bs4 import BeautifulSoup url = 'https://digitalcoinprice.com' source_code = requests.get(url) plain_text = source_code.text soup = BeautifulSoup(plain_text, "html.parser") for link in soup.find_all('span', {'class': 'coin_currency_name'}): title = link.string print(title) A: You can use pandas and read_html for this import pandas as pd tables = pd.read_html('https://digitalcoinprice.com/') print(tables[0]) If doing a lot consider also using an API method
doc_23529380
Thanks My code - String CHANNEL_ID = "my_channel_01"; String name = "notification"; int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance); NotificationManager mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification.Builder(this,CHANNEL_ID) .setContentTitle("New Message") .setContentText("You've received new messages.") .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark) .setChannelId(CHANNEL_ID) .build(); A: I think you are missing mManager.createNotificationChannel(mChannel);
doc_23529381
public void example() { Pattern p = Pattern.compile("\\d*"); Matcher m = p.matcher("ab34ef"); boolean b = false; while (b = m.find()) { System.out.println(m.start() + " " + m.group()); } } If I ran this I would end up with the following output.. 0 1 2 34 4 5 6 I understand how this works apart from how it ends up at 6, I thought it would finish on 5 could someone please explain this to me? Thanks! A: In your string, "ab34ef", there are 7 "empty characters" with a value of "". They are located between each of the normal characters. It attempts to find a match starting on each empty character, not each normal character; i.e. the location of each | in the following: "|a|b|3|4|e|f|".
doc_23529382
* *The client hello is sent from IIS *Then SoapUi responds with the server hello and continues with the certificate and a certificate request *Then IIS terminats the connection with a TCP [FIN, ACK] *And finally SoapUi sends the Alert(Level: Fatal, Description: Handshake Failure) *In my application log I can see the error Could not establish secure channel for SSL/TLS with authority 'localhost:8443'. From the logs in my app I can see that my app is apparently loading the certificate as expected. The certificate is loaded from the LocalMachine certificate store and the CA certificate is located in the Trusted Root Certification Authorities. In SoapUi I've added .pfx files for the SoapUi certificate/private key and for the CA certificate/private key. Both the IIS certificate and the SoapUi certificate is signed by the same CA. Is there anything special I need to configure in IIS to allow an app to connect with mutual certificate authentication. A: IIS does not necessarily have access to the private keys in the local machine certificate store. If you have installed the certificate with e.g. an administrator account you will have to give the app pool that runs your application access to the private key of the certificate.
doc_23529383
Here is my code: const unirest = require("unirest") const getData = async() => { let url = "https://trends.google.com/trends/api/explore?tz=420&req=%7B%22comparisonItem%22%3A%5B%7B%22keyword%22%3A%22audi%22%2C%22geo%22%3A%22%22%2C%22time%22%3A%22today+12-m%22%7D%2C%7B%22keyword%22%3A%22mercedes%22%2C%22geo%22%3A%22%22%2C%22time%22%3A%22today+12-m%22%7D%2C%7B%22keyword%22%3A%22bmw%22%2C%22geo%22%3A%22%22%2C%22time%22%3A%22today+12-m%22%7D%5D%2C%22category%22%3A0%2C%22property%22%3A%22%22%7D" const response = await unirest .get(url) .headers({ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36", }) console.log(response.body) } getData(); A: Google is a very hard platform to scrape. Apart from its bot preventing systems, it uses A/B testing quite regularly, which changes the layout and requires additional adjustments to a web scraper. As an engineer at WebScrapingAPI, I can recommend you our Google Trends Scraper. Here is how it would work: const axios=require('axios'); const API_KEY = '<YOUR_API_KEY>' const QUERY = 'test' const SCRAPER = `https://api.searchdata.io/v1?engine=google_trends&api_key=${API_KEY}&q=${encodeURI(QUERY)}` const scrape = async () => { try { let response = await axios.get(SCRAPER) console.log(response.data) } catch (e) { console.log(e) } } scrape() Alternatively, you can render the page using Puppeteer, but you'd probably get blocked. Here is a script: const puppeteer = require("puppeteer") const cheerio=require('cheerio'); const main = async () => { const browser = await puppeteer.launch({ headless: false, defaultViewport: null, acceptInsecureCerts: true, }) const page = await browser.newPage() await page.goto('https://trends.google.com/trends/api/explore?tz=420&req=%7B%22comparisonItem%22%3A%5B%7B%22keyword%22%3A%22audi%22%2C%22geo%22%3A%22%22%2C%22time%22%3A%22today+12-m%22%7D%2C%7B%22keyword%22%3A%22mercedes%22%2C%22geo%22%3A%22%22%2C%22time%22%3A%22today+12-m%22%7D%2C%7B%22keyword%22%3A%22bmw%22%2C%22geo%22%3A%22%22%2C%22time%22%3A%22today+12-m%22%7D%5D%2C%22category%22%3A0%2C%22property%22%3A%22%22%7D') const html = await page.content(); console.log(html); } main()
doc_23529384
Below is the code snippet that i have used aItDriver.switchTo().window("[TITLE:Choose File to Upload]"); aItDriver.getKeyboard().sendKeys(new String[]{"I:\Downloads\fileName.txt" + Keys.ENTER}); in here we used autoit (aItDriver) driver to enter the file path for file upload screen, expected output for the file upload screen was : I:\Downloads\fileName.txt But we see the below text entered to the upload window text box in rare cases. I:|Downloads\fileName.txt Could someone give an explanation to this sporadic issue, and if there is a correct way to enter the given text or fix for this issue? A: @Marlan depending on the language that you use, there is few solutions to fix the absolute path. In java you can try: public static void main(String[] args) throws IOException { Path path = Paths.get("myFile.txt"); Path absolutePath = path.toAbsolutePath(); System.out.println(absolutePath.toString()); } After that you can just used element.sendKeys(absolutePath.toString()); to upload file Using JavaScript: const path = require('path'); let absoluteFilePath = path.resolve('myFile.txt'); element(by.id('something').sendKeys(absoluteFilePath);
doc_23529385
.fa-facebook{content:url("")} The images work on Chrome but not FF or IE. What's going on/Is there a workaround? Jsfiddle A: According to W3school: Definition and Usage The content property is used with the :before and :after pseudo-elements, to insert generated content. So instead of .fa-facebook{content:url("")} use .fa-facebook:before{content:url("")} Jsfiddle A: According to the official rules, the content property only works for ::before and ::after pseudo-elements. So in this case, Chrome breaks the rules! Solution: add ::before to the selectors for the icons, then it will work in all browsers. .fa-facebook::before { content: url("https://lh3.googleusercontent.com/-VPr8buUo47w/VjMsRPIzr-I/AAAAAAAAAL4/AYBtvlNCQiw/s64-Ic42/clouds_social_media_icons_set_64x64_0000_facebook.png"); } .fa-twitter::before { content: url("https://lh3.googleusercontent.com/-yDH1FuHcQ5s/VjMsQ2lXvxI/AAAAAAAAAMg/i8JHsTh6aU8/s64-Ic42/clouds_social_media_icons_set_64x64_0002_twitter.png"); } .fa-instagram::before { content: url("https://lh3.googleusercontent.com/-VIveL13ocQc/VjMw7JU6dGI/AAAAAAAAAOo/AGxBey6rtC0/s64-Ic42/clouds_social_media_icons_set_64x64_0001_instagram.png") } .fa-pinterest::before { content: url("https://lh3.googleusercontent.com/-Or5qfrW2PFI/VjMsQziUH5I/AAAAAAAAAL8/bOIkRNtMSbo/s64-Ic42/clouds_social_media_icons_set_64x64_0001_pinterest.png"); } .fa-google-plus::before { content: url("https://lh3.googleusercontent.com/-xIroPQ5PdBk/VjMsRhd-1VI/AAAAAAAAAMM/rcruNIarpPU/s64-Ic42/clouds_social_media_icons_set_64x64_0003_google%25252B.png"); } .fa-heart::before { content: url("https://lh3.googleusercontent.com/-ymc-N9bHkpo/VjNAMkaZnpI/AAAAAAAAAPY/Yv1qLXXuG7E/s64-Ic42/clouds_social_media_icons_set_64x64_0001_bloglovin.png"); } <ul class="site-social-networks secondary-2-primary style-default show-title"> <li><a href="#" class="facebook" target="_blank" title="Facebook"><i class="fa fa-facebook"></i>Facebook</a> </li> <li><a href="#" class="twitter" target="_blank" title="Twitter"><i class="fa fa-twitter"></i>Twitter</a> </li> <li><a href="#" class="instagram" target="_blank" title="Instagram"><i class="fa fa-instagram"></i>Instagram</a> </li> <li><a href="#" class="pinterest" target="_blank" title="Pinterest"><i class="fa fa-pinterest"></i>Pinterest</a> </li> <li><a href="#" class="bloglovin" target="_blank" title="Bloglovin"><i class="fa fa-heart"></i>Bloglovin</a> </li> <li><a href="#" class="googleplus" target="_blank" title="Google Plus"><i class="fa fa-google-plus"></i>Google Plus</a> </li> </ul> A: Use image in background instead of content for e.g .fa-facebook{ content: ''; background:url("https://lh3.googleusercontent.com/-VPr8buUo47w/VjMsRPIzr-I/AAAAAAAAAL4/AYBtvlNCQiw/s64-Ic42/clouds_social_media_icons_set_64x64_0000_facebook.png"); width:64px; height:64px; display:inline-block; } A: I want to replace this line and show a custom image. <i class="fa-solid fa-graduation-cap fa-lg">
doc_23529386
VALUES ('OUOUOuouOUO', 'OU', 'OUO', 'IU', 'OI', 'OI', 'HJO', '') Where have I gone wrong in this SQL query? Everything seems to be in order! If it is some thing to do with the choice of quotes i.e. ' vs. ` vs. " could you explain the usage and choice between them? A: SO's syntax highlighting hints at the problem in this query. You need to write the word Index in quotes — it is a reserved word, and by using it in this context without quoting I'm guessing your SQL server is getting confused. INSERT INTO `assets` (SKU, Quantity, Description, Value, Location, Owner, Notes, `Index`) VALUES ('OUOUOuouOUO', 'OU', 'OUO', 'IU', 'OI', 'OI', 'HJO', '') For more information: * *MySQL reserved words *PostgreSQL reserved words *SQL Server reserved words *SQLite reserved words *even more.. A: Is Index a primary key/auto increment value as the name suggests? If it is, what you're doing is assigning it 0 as a value everytime you do an insert - which obviously you can't, since no two primary key values can be the same. Solution: * *Assign the index column the auto_increment attribute; *Don't specify the value of Index when doing inserts. A: The name of the table is also is written in ` this is wrong. please write it without any quotes. INSERT INTO assets (SKU, Quantity, Description, Value, Location, Owner, Notes, Index) VALUES ('OUOUOuouOUO', 'OU', 'OUO', 'IU', 'OI', 'OI', 'HJO', '')
doc_23529387
Ext.apply(this, { xtype: 'grid', selModel: { mode: 'MULTI' }, columnLines: true, store: Ext.create('TheGrid.store.GridDetail'), columns: [ {text: 'FirstName', dataIndex: 'first_name', cellWrap: true, width: 75}, {text: 'LastName', dataIndex: 'last_name', cellWrap: true, width: 100}, {text: 'Comment', dataIndex: 'comment', cellWrap: true, flex:1, minWidth: 200}, ], I've tried to get the cell value by doing so: var grid_results = function(header_name, row) { var grid = Ext.ComponentQuery.query('grid=itemId=gridID]')[0]; return grid.getStore().data.items[0].raw['FirstName']; }; A: you can use the get method to obtain the value of a specified field in the model ie: grid.getStore().data.items[0].get('first_name') Here is a fiddle demonstrating
doc_23529388
''' Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserRegistrationSerializer.create() method to handle this correctly. ''' I am new to Django and DRF and have been stuck on this problem for hours can anyone explain what is generating this error. I have been following tutorial and same code works for him. serializers. py from rest_framework import serializers from account.models import User class UserRegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type':'password'},write_only=True) class Meta: model = User fields = ['email','name','password','password2','tc'] extra_kwargs = { 'password':{'write_only':True} } # validating Password and confirm password while Registration def validate(self,attrs): password = attrs.get('password') password2 = attrs.get('password2') if password != password2: raise serializers.ValidationError("Password and confirm password doesn't match") return attrs def create(self,validate_data): print(validate_data); return User.objects.create_user(**validate_data); Models .py from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser # Custom User Manager class UserManager(BaseUserManager): def create_user(self, email, name,tc, password=None,password2=None): """ Creates and saves a User with the given email, name, tc and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), name = name, tc = tc, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,tc, password=None): """ Creates and saves a superuser with the given email, name, tc and password. """ user = self.create_user( email, password=password, name=name, tc=tc, ) user.is_admin = True user.save(using=self._db) return user # Custom user model class User(AbstractBaseUser): email = models.EmailField( verbose_name='Email', max_length=255, unique=True, ) name = models.CharField(max_length=200) tc = models.BooleanField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name','tc'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return self.is_admin def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin views.py from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from account.serializers import UserRegistrationSerializer class UserRegistrationView(APIView): def post(self,request,format=None): serializer = UserRegistrationSerializer( data = request.data); print("******************************************") print(request.data); if serializer.is_valid(raise_exception=True): user = serializer.save() return Response({'msg':'Registration Sucssess'},status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) A: You have forgotten to add password and password2 in the models. In models.py, class User(AbstractBaseUser): password = models.Charfield(max_length=255) password2 = models.Charfield(max_length=255) A: remove semicolon from the create method in serializer and try again. def create(self,validate_data): print(validate_data); return User.objects.create_user(**validate_data); <----------
doc_23529389
The subject line and any content shows the Unicode correctly. And looking at the MSDN, the property should be "urn:schemas:httpmail:from". Anyone solved this issue? Dim AC_EMAIL : AC_EMAIL = "test@test.com" Dim AC_EMAIL_FROM : AC_EMAIL_FROM = "测试 <test@test.com>" Dim strSubject : strSubject = """测试"" testing testing" set oMessage = WScript.CreateObject("CDO.Message") With oMessage .BodyPart.charset = "utf-8" 'unicode-1-1-utf-8 .Fields("urn:schemas:httpmail:from") = AC_EMAIL_FROM .Fields("urn:schemas:httpmail:to") = AC_EMAIL .Fields("urn:schemas:httpmail:subject") = strSubject .Fields.Update .Send End With Set oMessage = Nothing A: Found a work around. Not the prettiest, but it works. Basically I converted the string to Quoted-Printable. .Fields("urn:schemas:httpmail:from") = "=?utf-8?Q?=E6=8F?= <test@test.com>"
doc_23529390
_function: push ebp ;store the old base pointer mov ebp, esp ;make the base pointer point to the current ;stack location – at the top of the stack is the ;old ebp, followed by the return address and then ;the parameters. sub esp, x ;x is the size, in bytes, of all ;"automatic variables" in the function at the top of the stack is the old ebp, followed by the return address and then the parameters. The old ebp is there because push ebp, but why are the return address and the parameters there too? UPDATE Standard Exit Sequence mov esp, ebp ;reset the stack to "clean" away the local variables pop ebp ;restore the original base pointer ret ;return from the function What does ret actually do?I think the esp should have already reached the return address at the line pop ebp A: In x86 standard call convention, before a function is called, the parameter are pushed to the stack first. And the call op means "push the next address to the stack, then jump to the function", so the return address is on the stack too. That means, before the push ebp, the stack looks like: ... param2 param1 param0 return_address <- esp After calling push ebp it becomes ... param2 param1 param0 return_address ebp <- esp Finally, mov ebp, esp stores this esp into ebp, so you can refer to the return address and all input parameters relative to ebp, and free the stack for local use. A: It's all part of the ABI. By convention the caller creates a stack frame which contains parameters, etc, then calls the function (during which process the return address is also pushed onto the stack). The called function will allocate additional space on the stack for local variables and can reference parameters and local variables all via one common pointer and offset.
doc_23529391
data Foo = A Int | B Int | C Int myList :: [Foo] myList = [A 1, B 2, C 3] I want a function that gets the value of a specific constructor, if existing: -- returns value of the first A constructor, if exists: getA :: [Foo] -> Maybe Int -- returns value of the first B constructor, if exists: getB :: [Foo] -> Maybe Int Any elegant solution? And what about a getX function, capable of getting the value of any specified constructor in the list? A: This will work getA theList = listToMaybe [x | A x <- theList] getB theList = listToMaybe [x | B x <- theList] You will need to import Data.Maybe. Generalizing this would be possible, but tricky.... What type would you even want this function to have? ([a]->somethingToRepresentAConstructor->Int). A: And what about a getX function, capable of getting the value of any specified constructor in the list? Regarding the generalization, the somethingToRepresentAConstructor could be a String? You can generalize a bit more and get firstJust :: (a -> Maybe b) -> [a] -> Maybe b firstJust f xs = case filter isJust (map f xs) of x : _ -> x [] -> Nothing getA = firstJust f where f (A x) = Just x f _ = Nothing getB = firstJust f where f (B x) = Just x f _ = Nothing
doc_23529392
So, I can save and next restore the chart model in Integrated chart mode (data table with chart). Can I restore the same chart model in Standalone charts (ag-Charts)?
doc_23529393
my two models class Team < ActiveRecord::Base has_many :fixtures, :finder_sql => 'SELECT * FROM fixtures where (home_team = #{id} or away_team = #{id})' has_many :home_fixtures, :class_name => "Fixtures", :foreign_key => :home_team has_many :away_fixtures, :class_name => "Fixtures", :foreign_key => :away_team has_many :teamalias end class Fixture < ActiveRecord::Base belongs_to :league belongs_to :selection has_many :selection named_scope :for_team_id, lambda{|team_id| {:conditions => ['(home_team = ? or away_team = ?)', team_id, team_id]} } belongs_to :home_team, :class_name => "Team", :foreign_key => :home_team belongs_to :away_team, :class_name => "Team", :foreign_key => :away_team def fix_list [home_team.title, "Draw", away_team.title] end end taken from Multi level associations in rails but I'm stumped again- i'm trying to save a fixture based on the last solution in the first answer above and I am getting a typemismatch of. Team(#38391330) expected, got String(#1242130) no idea what to do here please help. edit- db migrations Here is the migrations class CreateFixtures < ActiveRecord::Migration def self.up create_table :fixtures do |t| t.integer :home_team t.integer :away_team t.datetime :when t.integer :league_id t.timestamps end end def self.down drop_table :fixtures end end class CreateTeams < ActiveRecord::Migration def self.up create_table :teams do |t| t.string :title t.timestamps end end def self.down drop_table :teams end end class AddResultToFixture < ActiveRecord::Migration def self.up add_column :fixtures, :result, :integer end def self.down remove_column :fixtures, :result end end A: your form probably has fixture[home_team] which is a select which passes the team.id so when you do @fixture = Fixture.new(params[:fixture]) @fixture.save you are calling home_team= team.id team.id is a string but home_team should be a Team object
doc_23529394
Here is the toy data frame structure(list(Dates = c("2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31", "2021-12-31"), Firm = c("BRYAT", "ZRGYO", "KONTR", "TRGYO", "DAPGM", "INVES", "ECZYT", "GWIND", "KMPUR", "SNGYO", "BERA", "ISGYO", "ALKA", "YGGYO", "SRVGY"), Sector = c("FINANCIAL AND INSURANCE ACTIVITIES", "FINANCIAL AND INSURANCE ACTIVITIES", "INFORMATION AND COMMUNICATION", "REAL ESTATE ACTIVITIES", "REAL ESTATE ACTIVITIES", "FINANCIAL AND INSURANCE ACTIVITIES", "FINANCIAL AND INSURANCE ACTIVITIES", "MANUFACTURING", "MANUFACTURING", "REAL ESTATE ACTIVITIES", "MANUFACTURING", "REAL ESTATE ACTIVITIES", "MANUFACTURING", "FINANCIAL AND INSURANCE ACTIVITIES", "FINANCIAL AND INSURANCE ACTIVITIES" ), `Number of Employees` = c(9, 32, 226, 144, 138, 6, 3, 50, 219, 194, 33, 69, 208, 138, 11), EBITDA = c(23.8137, 1113.5212, 113.9684, 6517.373, 387.6152, 1624.0192, -7.8884, 420.6019, 280.8024, 4648.4098, 752.1899, 153.6431, 138.7504, 194.0958, 144.2635), `Profit Margin` = c(574.7712, 706.7635, 21.3576, 357.6667, 34.2274, 537.1883, 372.8143, 31.6373, 14.5637, 150.702, 17.7025, 48.8762, 26.2978, 252.0494, 162.3127), Sales = c(47.7833, 186.8011, 611.8077, 1483.729, 912.4001, 312.5418, 0, 540.2263, 2172.6885, 2123.4395, 4217.1842, 545.2598, 700.9869, 277.6963, 414.2354), `Market Cap` = c(10681.875, 11405.4966, 2474.0625, 3920, NA, NA, 5407.5, 3123.1821, NA, 3728.536, 3320.352, 2435.225, 859.425, 3386.88, 4695.6), `Personnel Expense (Millions)` = c(3.4716, 8.4842, 7.7846, 11.869, 14.3014, 1.1789, 0.4507, 17.2696, 55.9705, 25.5093, 308.7577, 20.0843, 33.358, 10.5289, 14.3268 ), `Personnel Expense Per Employee` = c(385733.5556, 265130.0938, 34445.1726, 82423.6111, 103633.6739, 196478.3333, 150236.6667, 345392.94, 255573.0411, 131491.1082, 9356294.7879, 291076.971, 160374.9663, 76296.7319, 1302436.6364), `Price/Earnings` = c(38.8935, 7.8922, 18.934, 0.7387, NA, NA, 12.5925, 18.2735, NA, 1.1651, 4.4476, 9.1377, 4.6621, 4.6933, 6.9838)), row.names = c(NA, -15L), class = c("tbl_df", "tbl", "data.frame")) I tried to make legend text font size smaller but this time the legend becomes unreadable. I am pretty sure that I can wrap the text but I really couldn't find the code. ggplot(dataset%>% filter(Dates %in% "2021-12-31" & `Number of Employees` < 250))+ geom_point(aes(x = `Number of Employees`, y = `Profit Margin`, color = Sector),show.legend = T)+ lims(y = c(-100,200))+ theme(legend.text = element_text(size = 6,hjust = 0.5,lineheight = 121)) A: I suggest you move the legend to the bottom (or top) and set the number of rows: dataset %>% filter(Dates %in% "2021-12-31", `Number of Employees` < 250) %>% ggplot(aes(x = `Number of Employees`, y = `Profit Margin`)) + geom_point(aes(color = Sector)) + lims(y = c(-100,200)) + theme( legend.text = element_text(size = 6,hjust = 0.5, lineheight = 121), legend.position = "bottom") + guides(color = guide_legend(nrow = 2)) A: I looked at Hadley Wickham's GitHub and found legend.key.size() and legend.key.width() options. dataset %>% filter(Dates %in% "2021-12-31", `Number of Employees` < 250) %>% ggplot(aes(x = `Number of Employees`, y = `Profit Margin`)) + geom_point(aes(color = Sector)) + lims(y = c(-50,200)) + theme( legend.text = element_text(size = 5,vjust = 0.1), legend.position = "bottom", legend.key.width = unit(0.05, "cm"), legend.key.size = unit(0.1, "cm"))+ guides(color = guide_legend(ncol = 3, nrow = 5)) A: The scales package provides label_wrap() to wrap long strings at natural breakpoints after a specified number of characters. In combination with r2evans' suggestions about legend positioning and formatting, you should be able to achieve readable text for many labels. dataset %>% filter(Dates %in% "2021-12-31" & `Number of Employees` < 250) %>% ggplot(aes(x = `Number of Employees`, y = `Profit Margin`, color = Sector)) + geom_point(size = 3) + scale_colour_viridis_d( option = "turbo", end = 0.8, labels = scales::label_wrap(20), guide = guide_legend(nrow = 2) ) + theme_bw() + theme( legend.text = element_text(size = 7, hjust = 0.5), legend.key.height = unit(10, "mm"), # increase this to space out the wrapped labels legend.position = "bottom" # might be more space down here, depends on plot dimensions ) 14 distinct colours will be tricky, my suggestion for that is to use/abuse the turbo palette, as above, or consider using both shapes and colour to distinguish your categories.
doc_23529395
It is a checkbox which allow user to select one of more options. The issue I am having is that the model does not work properly when more than one option is selected. My hunch is that the issue is what is being passed via the viewModel If one value is selected fiddler shows me that beds=1 is passed whereas when multiple values of checkbox are selected then beds[]=1&beds[]=2 is passed. Is it because of the brackets [] that the controller is not able to bind it. More details below The view is as follows: <div> <input type="checkbox" name="beds" id="beds_1" value="1" /><label for="beds_1">1</label> <input type="checkbox" name="beds" id="beds_2" value="2" /><label for="beds_2">2</label> <input type="checkbox" name="beds" id="beds_3" value="3" /><label for="beds_3">3</label> <input type="checkbox" name="beds" id="beds_4" value="4" /><label for="beds_4">4</label> <input type="checkbox" name="beds" id="beds_5" value="5" /><label for="beds_5">5+</label> </div> This is part of a viewModel which is as follows: public class SearchFormViewModel { ... public int[] beds { get; set; } } When the user hits submit - it goes to the search controller via ajax private IEnumerable<Property> ProcessPropertySearch(SearchFormViewModel viewModelInp, int? page = null, int? ps = null) { var searchQuery = new SearchParameters { ... BedroomsCounts = viewModelInp.beds ?? new int[0], ... }; Now, I have tried to debug this. If I don't choose any filter for bed then viewModelInp.beds = null & BedroomCounts is set to int[0]. If I choose one value then viewModelInp.beds = choosen-value & BedroomCounts is set to int[choosen-value] If I choose multiple value then for some reason viewModelInp.beds is flowing in the controller as null. I have checked using fiddler as well. For the case, when I choosse multiple values the fiddler webform view shows the following: ... beds[]=1 beds[]=2 ... I am not sure why viewModelInp.beds = null when multiple values are choosen. I have used jquery bbq to help bookmark my url. if I directly write the url for a multiple selection case, i.e. www.domain.com/search#beds[]=1&beds[]=2 (or,www.domain.com/search#beds=1&beds=2) - then the right checkboxes are shown as 'checked'. However, the search still ignores it. Any help would be grateful! Thanks --- UPDATE AS ASKED I am using Jquery BBQ. and the ajax is $.post('/search/getproperties', $.param(model), function (response) { // show properties returned } The $.param(model) in the above case is equal to beds[]=1&beds[]=2 A: I don't think the model binder likes the format it's receiving the data in. You said: The $.param(model) in the above case is equal to beds[]=1&beds[]=2 The request body should actually be: beds=1&beds=2 less the [] A: As expected, the issue was due to [] being used in the post values due to the way $.param in Jquery BBQ plugin works. I am not sure if there is a better way to do it but I basically removed the [] from the $.param(model) before posting the values and it worked so, var postValues = $.param(model).replace(/\%5B\%5D/g,'') $.post('/search/getproperties', postValues, function (response) { // show properties returned } Please let me know if you guys feel there is a better way. Thank you! --- UPDATE AS PER ED's Comments $.post('/search/getproperties', $.param(model, true), function (response) { // show properties returned }
doc_23529396
its also can be done with c library that i will add to my project. A: There are two methods for changing the perceived tempo of audio. One method is to simply alter the playback speed. This is easy to do with PCM audio, but will require you to decode the MP3. It might be possible to alter the sample rate (effectively the same thing) in the compressed domain (i.e. in the MP3 file itself), but I don't know how to do that. The big drawback with this approach is all the pitches in the audio change, too. This can make vocals sound unnatural, for instance. Another approach is to apply a pitch-invariant speed change. This is a far more complex operation, and there are many proprietary algorithms and research papers addressing it. The pitch-synchronous overlap add (PSOLA) technique is one that works well. You can also look at what Audacity (an open-source audio editor) does. Since you are on iOS, Apple's audio framework might also provide some support for this. Look for AUPitch in the iOS documentation.
doc_23529397
Ex. A user wants to search for a character whose name starts with "S", that is a "Vampire" and also is a "Female". React code below: //This is a function to filter an object function objectFilter(mainObject, filterFunction){ return Object.fromEntries(Object.entries(mainObject).filter(objKey => filterFunction(mainObject[objKey[0]]))) }; const filters = objectFilter(this.props.filters, el => el !== null); filters.lenght > 0 ? this.props.data .filter(el => { if (el.name.toLowerCase().includes(this.props.name.toLowerCase())){ if(filters.age){ if(el.age === filters.age){ return true } } if(filters.gender){ if(el.gender === filters.gender){ return true } } if(filters.status){ if(el.status === filters.status){ return true } } if(filters.race){ if(el.race === filters.race){ return true } } } return false }) .map(el => <Character img={el.img} name={el.name} race={el.race} age={el.age} status={el.status} gender={el.gender} key={el.id} /> ) : this.props.data .filter(el => el.name.toLowerCase().includes(this.props.name.toLowerCase())) .map(el => <Character img={el.img} name={el.name} race={el.race} age={el.age} status={el.status} gender={el.gender} key={el.id} /> ) this.props.data is an array of objects [{}, {}, {}...], each array contains the character info (id, name, race, gender, status, img, etc...).
doc_23529398
foreach (var shopItem in Instance.Configuration.ItemsToSellToPlayers.Select(x => (ShopItem)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(x), typeof(ShopItem)))) Here's the ShopItem class: public class ShopItem { public int Amount; public double Price; public string ShortName; public ulong SkinId; public ShopItem() { } public ShopItem(int amount, double price, string shortName, ulong skinId = 0) { Amount = amount; Price = price; ShortName = shortName; SkinId = skinId; } public Item Create() { var item = ItemManager.CreateByName(ShortName, Amount, SkinId); item.name = $"{item.info.displayName.english} - ${Price}"; return item; } } Does anyone have a suggestion as to how I should convert ItemsToBuyFromPlayers = new List<object> { new ShopItem(1, 1, "stones"), new ShopItem(1, 1, "wood") }; back to an instance my class? NOTE: Typical casting ((ShopItem)x) doesn't work. A: The problem is here: // you create the List of `object`s ItemsToBuyFromPlayers = new List<object> { new ShopItem(1, 1, "stones"), new ShopItem(1, 1, "wood") }; The right way: var shopItems = new List<ShopItem> { new ShopItem(1, 1, "stones"), new ShopItem(1, 1, "wood") }; var serialized = JsonConvert.SerializeObject(shopItems); var copyOfShopItems = JsonConvert.DeserializeObject<List<ShopItem>>(serialized);
doc_23529399
kernel version 2.6.34.1 #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/crypto.h> #include <linux/scatterlist.h> #include <linux/vmalloc.h> void my_test(void) { uint32_t *input; uint32_t *output; uint32_t *temp; unsigned char *src; unsigned char *dst; size_t blk_len=16; size_t key_len=16; int ret; struct crypto_blkcipher *my_tfm; struct blkcipher_desc desc; struct scatterlist *src_sg; struct scatterlist *dst_sg; unsigned char my_key[32] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; unsigned char *my_iv; void *iv; size_t ivsize=16; my_iv = vmalloc(blk_len); memset(my_iv, 0, blk_len); temp = vmalloc(blk_len); src_sg = vmalloc(sizeof(struct scatterlist)); if (!src_sg) { printk("MY_TEST: failed to alloc src_sg!!!\n"); goto src_sg_free; } dst_sg = vmalloc(sizeof(struct scatterlist)); if (!dst_sg) { printk("MY_TEST: failed to alloc dst_sg!!!\n"); goto dst_sg_free; } input = vmalloc(blk_len); if (!input) { printk("MY_TEST: failed to alloc input!!!\n"); goto input_free; } output = vmalloc(blk_len); if (!output) { printk("MY_TEST: failed to alloc output!!!\n"); goto output_free; } src = vmalloc(blk_len); if (!src) { printk("MY_TEST: failed to alloc src!!!\n"); goto src_free; } dst = vmalloc(blk_len); if (!dst) { printk("MY_TEST: failed to alloc dst!!!\n"); goto dst_free; } my_tfm = crypto_alloc_blkcipher("ecb(aes)", 0, 0); if (!my_tfm) { printk("MY_TEST: failed to alloc tfm!!!\n"); goto crypto_free; } desc.tfm = my_tfm; desc.flags = 0; crypto_blkcipher_setkey(my_tfm, my_key, key_len); iv = crypto_blkcipher_crt(my_tfm)->iv; ivsize = crypto_blkcipher_ivsize(my_tfm); memcpy(iv, my_iv, ivsize); input[0]=0x80000000; input[1]=0x00000000; input[2]=0x00000000; input[3]=0x00000000; printk("MY_TEST: input: %x,%x,%x,%x\n",input[0],input[1],input[2],input[3]); *((uint32_t *)(&src[ 0])) = input[0]; *((uint32_t *)(&src[ 4])) = input[1]; *((uint32_t *)(&src[ 8])) = input[2]; *((uint32_t *)(&src[12])) = input[3]; temp[0]=0xFFFFFFFF; temp[1]=0xFFFFFFFF; temp[2]=0xFFFFFFFF; temp[3]=0xFFFFFFFF; *((uint32_t *)(&dst[ 0])) = temp[0]; *((uint32_t *)(&dst[ 4])) = temp[1]; *((uint32_t *)(&dst[ 8])) = temp[2]; *((uint32_t *)(&dst[12])) = temp[3]; sg_init_one(src_sg, src, blk_len); sg_init_one(dst_sg, dst, blk_len); ret = crypto_blkcipher_encrypt(&desc, dst_sg, src_sg, src_sg->length); if (ret < 0) pr_err("MY_TEST: phase one failed %d\n", ret); output[0] = *((uint32_t *)(&dst[ 0])); output[1] = *((uint32_t *)(&dst[ 4])); output[2] = *((uint32_t *)(&dst[ 8])); output[3] = *((uint32_t *)(&dst[12])); printk("MY_TEST: output: %x,%x,%x,%x\n", output[0], output[1], output[2], output[3]); crypto_free_blkcipher(my_tfm); vfree(temp); crypto_free: vfree(dst); dst_free: vfree(src); src_free: vfree(output); output_free: vfree(input); input_free: vfree(dst_sg); dst_sg_free: vfree(src_sg); src_sg_free: printk("MY_TEST: END!!!\n"); } static int test_mod_init(void) { printk("MY_TEST: init.\n"); my_test(); return 0; } static void test_mod_exit(void) { printk("MY_TEST: exit.\n"); } module_init(test_mod_init); module_exit(test_mod_exit); MODULE_AUTHOR("A.MAS"); MODULE_DESCRIPTION("my test module"); MODULE_LICENSE("GPL"); here is part of kernel log: [ 335.770838] MY_TEST: init. [ 335.860494] MY_TEST: input: 80000000,0,0,0 [ 335.864738] MY_TEST: output: ffffffff,ffffffff,ffffffff,ffffffff [ 335.865459] MY_TEST: END!!! [ 342.484247] MY_TEST: exit.