id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23537800
ConnectivityManager cm = (ConnectivityManager)context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnected()) { try { URL url = new URL("http://www.google.com/"); HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); urlc.setRequestProperty("User-Agent", "test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(5000); // mTimeout is in seconds urlc.connect(); if (urlc.getResponseCode() == 200) { return true; } else { return false; } } catch (IOException e) { Log.i("warning", "Error checking internet connection", e); return false; } } After trying several times, i encounter that the problem is that im doing ping to "www.google.com.". I dont understand why is this happening. This code was woking fine for the last 2 years in my project. A: If you are testing this on a latest version of android, then you need to verify that you have whitelisted domains. You should read below: https://developer.android.com/training/articles/security-config As a quick fix you can add below property to application tag: android:usesCleartextTraffic="true"
doc_23537801
var db = window.sqlitePlugin.openDatabase({name: "mydb"}); alert("open"); db.transaction(function(tx) { alert("transaction"); tx.executeSql('select * from mytable',[],function(tx,rs) { alert("select"); }); }); } I have two pages in my application, index.html and second.html. If I call this code on index.html, it alerts correctly "open"-"transaction"-"select". But when I leave index.html and go to second.html afterwards, it does not alert "select", neither does it throw an Exception or call the error callback function which I optionally include. It just does nothing besides alerting "open"-"transaction". If I go directly to second.html without calling the script from index.html, it works well. The problem seems to occur only, when the script -or parts of it - is called for the second time. Who can help?
doc_23537802
Attached documents Important Notes We are setting two postprocessors , which does minmalistic work and making the ack mode as auto along with channel as transactional enabled while starting the SimpleMessageListenerContainer. We are using SpringAMQP 1.4.3 and RabbitMQ 3.4.4, Erlang 17.4 with CentOS as its OS having Quad core Intel Xeon CPU processor @ 2.5 GHz processor along with 16GB of RAM
doc_23537803
const Player = db.define('player', { // The primary key of the table. playerId: { type: DataTypes.INTEGER(11), primaryKey: true, }, playerName: DataTypes.STRING(11), teamId: { type: Sequelize.STRING(32), allowNull: false, references: { model: 'team', key: 'teamId', } }, managerId: { type: Sequelize.STRING(32), allowNull: true, references: { model: 'manager', key: 'managerId', } }, }); If I do Player.upsert( { teamId: p.teamId, managerId: p.managerId, playerName: p.name } ) will a new player be created or an existing player with same teamId and managerId will be updated ? How can I know which values does upsert look for in order to check if an entry already exists ? Does it look only for primaryKey, all the foreignKeys ? A: It looks for a primary key value just like similar SQL commands in many DBMSs. All other fields may be equal but PK is designed to be unique to distinguish one record from another.
doc_23537804
My validation is OK : 'exam_date' => 'required|date_format:d/m/Y H:i', I have a Postgres database, the type column for the date is timestamp(0) without time zone. So if I have understood, I have to transform the date before inserting it in the table . And I have to convert it after reading to display it in the good format. To do that, I have these mutator and accessor: public function setExamDateAttribute($value): void { $this->attributes['exam_date'] = DateTime::createFromFormat('d/m/Y H:i', $value); } public function getExamDateAttribute($value) { return date_format( DateTime::createFromFormat('Y-m-d H:i', $value), 'd/m/Y H:i'); } I have this error: date_format() expects parameter 1 to be DateTimeInterface, bool given In other words, I do not understand how mutators and accessors work with dates. A: This problem is nothing to do with mutator and accessor. The problem occurs because DateTime::createFromFormat('Y-m-d H:i', $value) return false; Your column for the date is timestamp, so the value format is Y-m-d H:i:s DateTime::createFromFormat('Y-m-d H:i' is not match to Y-m-d H:i:s, You need to use Y-m-d H:i:s instead of Y-m-d H:i: public function getExamDateAttribute($value) { return date_format( DateTime::createFromFormat('Y-m-d H:i:s', $value), 'd/m/Y H:i'); } A: You can use casts for dates, bools, integers and custom (in laravel 7), and you can also format the date in the model's definition: protected $dates = [ 'exam_date', ]; protected $dateFormat = 'Y-m-d H:i'; And you can format it in the blade template if needed: <td>{{$exam->exam_date->format('Y-m-d H:i:s')}}</td> Also your get method should be something like (docs): public function getExamDateAttribute() // <-- No parameter { return date_format( DateTime::createFromFormat('Y-m-d H:i', $this->exam_date), 'd/m/Y H:i'); //The value is in the model $this->exam_date } P.S: The error occurs because DateTime could not create a date object and returns FALSE, I think this happens because the getter doesn't need a parameter and null is passed...hence the error
doc_23537805
Article UOM Quantity 1002121 CAS 500 1002121 EA 1 1002121 INN 10 1002121 LAY 2,000 1002121 PAL 10,000 1002127 CAS 500 1002127 CS1 250 1002127 CS2 10 1002127 EA 1 1002127 INN 10 1002127 LAY 3,000 1002127 PAL 12,000 1002129 CAS 500 1002129 CS1 250 1002129 EA 1 1002129 INN 10 1002129 LAY 1,750 1002129 PAL 7,000 Column 1 is SKU nos, Column 2 is unit of measure and column 3 is quantity What I want to know is how many cases(CAS) = one layer(LAY) when SKU is same. E.g.: for SKU 1002121, one layer will be equal to 4 cases (2000/4)(LAY/CAS). Hence I need a formula which satisfies three conditions 1. SKU must be the same 2. when column b=LAY and Column B=CAS then divide column C and show result in column D in layer's Row Thanks for your help. Any suggestion is welcomed. A: This expression is rather a complicated one: =IF(B2="CAS",SUMIFS($C:$C,$A:$A,$A2,$B:$B,"LAY")/SUMIFS($C:$C,$A:$A,$A2,$B:$B,"CAS"),"") (or =IF(B2="CAS";SUMIFS($C:$C;$A:$A;$A2;$B:$B;"LAY")/SUMIFS($C:$C;$A:$A;$A2;$B:$B;"CAS");"") if your locale uses as delimiters ; instead of ,) Put in in the cell D2 and copy it to cells in the column D just bellow it. Explanation: * *IF decides if it is a cell where you want put the result. *The result is a quotient. Both the dividend and divisor use almost the same formula. *SUMIFS($C:$C,$A:$A,$A2,$B:$B,"LAY") details: * *$C:$C is the range of numbers for creating the sum (in your case from only 1 number) *$A:$A is the range for making comparisons with: *$A2 a value to be compared with *Next 2 parameters have the same meaning as 2nd and 3rd, they make an another condition. *So there are 2 conditions. They are evaluated again and again for each pair of corresponding cells in the columns A and B (so A2 and B2, A3 and B3, etc.) and if both of them are satisfied, the corresponding cell from the 1st argument (i. e. C2, C3, etc.) are included to the sum (in your case at most 1 cell). A: You could make a pivot table with your table as source. You would then put SKU in the filter and UOM in column fields. In the UOM you just filter the CAS and LAY. Then you get your numbers for CAS and LAY, which you just need to divide. You can also do the division in a pivot table calculated field.
doc_23537806
I'm trying to get all four images to line up on the same "row". Any future images will start on a new row. I've tried various methods, though none of them have worked. If a user can give my a rough start, I'd be grateful. I'd like to add that each image has a simple animation: $(document).ready(function(){ $("#id").hover(function(){ $(this).stop().animate({opacity: 0.75, marginTop: -10}, 400); },function(){ $(this).stop().animate({opacity: 1.0, marginTop: 0}, 400); }); }); A: One method you can do to get all your images to line up and not have to throw your elements outside of the DOM (using Floats do that). Use display: inline-block; and vertical-align: top; See example img { display: inline-block; // This will align your items side-by-side vertical-align: top; // Why because by default Inline-block sets your vertical to baseline } Hope this helps. A: Can you please post the html code where the images are included ? Normally you should be able to add them by applying the css style "float: left" and by making sure that the available width is enough (make sure to count padding of the container and margins of images to determine de available width). A: if you use float:left this will solve your problem. * *http://goo.gl/vtHg3b A: Without seeing your code it's hard to say for sure but it looks like your images don't fit in their container. If you are floating them when you run out of space elements are forced down to the next row. You can try, as mentioned by @davidpauljunior, to remove any right margins being applied to your images. If that doensnt work you can shrink the size of the images (if being applied by the background property) by reducing the width and height values by 90% (or whatever you may need) and applying background size: 90%; to the image containers. If they are inline images all the better. Just use img { max-width:100%; } and remove any applied dimensions to the inline element. Hope that helps.
doc_23537807
A: Have you tried copying & modifying some of Node.JS examples, such as SqlExample.js? More are available through Ignite Node.JS docs section.
doc_23537808
* *Component 1 triggers a function inside Service on click *Service then gets data from an API and stores it *Component 2 gets the data that has been stored and displays it So far I managed to get steps 1 and 2 working but I can't get my Component 2 to get the updated value, I'm still new to Angular so I must have not grasped a basic concept I suppose, here's the code (I removed unnecessary parts like the form and so on) Component 1 import { Component, OnInit } from '@angular/core'; import {FormBuilder, FormControl, FormGroup} from "@angular/forms"; import axios from "axios"; import {UserService} from "../../user.service"; import {map, Observable, startWith} from "rxjs"; import {CreatureType} from "../../models/creaturetype.model"; import {Creature} from "../../models/creature.model"; @Component({ selector: 'app-creatures-form', templateUrl: './creatures-form.component.html', styleUrls: ['./creatures-form.component.scss'] }) export class CreaturesFormComponent implements OnInit { constructor(private _formBuilder: FormBuilder , private UserService: UserService ) {} ngOnInit(): void {} onSubmitCustomCreature() { // @ts-ignore let creature : string = '/api/creatures/'+this.CreatureControl.value.id // "creature": "/api/creatures/1" let references = { capacities : [], gears : [], effects : [], turn : [] } const customCreature = { ...this.customCreaturesForm.value, creature: creature , account: '/api/accounts/'+this.UserService.user.id , ...references } const headers = { "Content-Type" : 'application/json' } axios.post('http://127.0.0.1:8000/api/custom_creatures' , customCreature, {headers}).then( (res) => { console.log(res) this.UserService.setCreatures(this.UserService.user.id) }) } } Component 2 import {Component, Input, OnInit} from '@angular/core'; import { UserService} from "../user.service"; import { Observable , of } from "rxjs"; import axios from "axios"; @Component({ selector: 'app-cards-panel', templateUrl: './cards-panel.component.html', styleUrls: ['./cards-panel.component.scss'] }) export class CardsPanelComponent implements OnInit { panelActive : boolean = false cards$! : any creatures : any constructor(private UserService: UserService) { } ngOnInit(): void { axios.get('http://127.0.0.1:8000/api/accounts/1', { headers : { "Accept" : 'application/json' } }).then( (res) => { this.UserService.setUser(res.data) // this.getAccountCreatures() }) this.UserService.getCreatures().subscribe(data => { this.cards$ = data console.log(this.cards$) // only trigger on Init, never updates }) // also tried this but it never triggers aswell // this.cards$ = of(this.UserService.userCreatures).subscribe((data) => { // console.log(data) // }) } } Service import { Injectable } from '@angular/core'; import {User} from "./models/user.model"; import {Observable, Subject} from "rxjs"; import axios from "axios"; import {HttpClient} from "@angular/common/http"; @Injectable({ providedIn: 'root' }) export class UserService { user!: User userCreatures: Subject<any> = new Subject() constructor(private http: HttpClient) { } setUser(user : User) { this.user = user } setCreatures(id: number) { axios.get('http://127.0.0.1:8000/api/custom_creatures?account=/api/accounts/'+id , { headers: { "Accept" : 'application/json' } }).then( (res) => { console.log(res) this.userCreatures = res.data console.log(this.userCreatures) }) console.log(this.getCreatures()) } getCreatures() { return this.userCreatures } } A: I'm gonna be honest, I'm a bit too lazy to figure out your entire use case. I prepared a simple example to let you see how to call an api in one component and read the result from another. I'm just getting a dumb joke from the jokes api. Stackblitz: https://stackblitz.com/edit/angular-ivy-yhhegu?file=src/app/api.service.ts Service @Injectable({ providedIn: 'root' }) export class ApiService { url = 'https://v2.jokeapi.dev/joke/Programming?type=single'; apiResult = 'no joke yet'; constructor(private http: HttpClient) {} callApi() { this.http .get(this.url) .subscribe((res: any) => (this.apiResult = res.joke)); } } Calling Component export class CallComponent { constructor(private apiService: ApiService) {} callApi() { this.apiService.callApi(); } } <button (click)="callApi()">CALL API</button> Reading Component export class ReadComponent { constructor(private apiService: ApiService) { } get apiResult(){ return this.apiService.apiResult; } } <p>{{ apiResult }}</p> You don't need to create a wrapper method / getter method for the service, you can declare it as public and use it directly in your html. I prefer this way because the linting / auto complete / refactoring in html is not great. Angular's change detection will know when apiResult has changed and your html will update automatically. Services are singleton so the service property will persist as long as your app does. If you require that other components execute other functions on receiving the result, you can use a Subject or BehaviorSubject instead of a simple local variable in the service. Let me know if you need any more details.
doc_23537809
workspace logs file content is: !ENTRY org.eclipse.osgi 4 0 2017-12-05 13:55:59.305 !MESSAGE Application error !STACK 1 java.lang.OutOfMemoryError: Java heap space at org.eclipse.swt.custom.StyledTextRenderer.setStyleRanges(StyledTextRenderer.java:1228) at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9913) at org.eclipse.swt.custom.StyledText.setStyleRanges(StyledText.java:9976) at org.eclipse.jface.text.TextViewer.applyTextPresentation(TextViewer.java:4884) at org.eclipse.jface.text.TextViewer.changeTextPresentation(TextViewer.java:4936) at org.eclipse.jface.text.presentation.PresentationReconciler.applyTextRegionCollection(PresentationReconciler.java:582) at org.eclipse.jface.text.presentation.PresentationReconciler.processDamage(PresentationReconciler.java:571) at org.eclipse.jface.text.presentation.PresentationReconciler.access$3(PresentationReconciler.java:567) at org.eclipse.jface.text.presentation.PresentationReconciler$InternalListener.textChanged(PresentationReconciler.java:227) at org.eclipse.jface.text.TextViewer.updateTextListeners(TextViewer.java:2826) at org.eclipse.jface.text.TextViewer.invalidateTextPresentation(TextViewer.java:3478) at org.eclipse.ui.texteditor.AbstractTextEditor.handlePreferenceStoreChanged(AbstractTextEditor.java:4628) at org.eclipse.ui.texteditor.AbstractDecoratedTextEditor.handlePreferenceStoreChanged(AbstractDecoratedTextEditor.java:906) at org.eclipse.wst.jsdt.internal.ui.javaeditor.JavaEditor.handlePreferenceStoreChanged(JavaEditor.java:2519) at org.eclipse.wst.jsdt.internal.ui.javaeditor.CompilationUnitEditor.handlePreferenceStoreChanged(CompilationUnitEditor.java:1530) at org.eclipse.ui.texteditor.AbstractTextEditor$PropertyChangeListener.propertyChange(AbstractTextEditor.java:715) at org.eclipse.ui.texteditor.ChainedPreferenceStore.firePropertyChangeEvent(ChainedPreferenceStore.java:164) at org.eclipse.ui.texteditor.ChainedPreferenceStore.handlePropertyChangeEvent(ChainedPreferenceStore.java:431) at org.eclipse.ui.texteditor.ChainedPreferenceStore.access$0(ChainedPreferenceStore.java:408) at org.eclipse.ui.texteditor.ChainedPreferenceStore$PropertyChangeListener.propertyChange(ChainedPreferenceStore.java:69) at org.eclipse.ui.preferences.ScopedPreferenceStore$3.run(ScopedPreferenceStore.java:351) !ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.266 !MESSAGE !STACK 0 java.lang.NullPointerException at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:209) at org.eclipse.jface.resource.JFaceResources.getResources(JFaceResources.java:230) at org.eclipse.ui.part.WorkbenchPart.dispose(WorkbenchPart.java:109) at org.eclipse.ui.internal.views.markers.ExtendedMarkersView.dispose(ExtendedMarkersView.java:634) at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.invalidate(CompatibilityPart.java:238) at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.destroy(CompatibilityPart.java:394) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:898)at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.dispose(EclipseContextOSGi.java:106) at org.eclipse.e4.core.internal.contexts.osgi.EclipseContextOSGi.bundleChanged(EclipseContextOSGi.java:139) at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:902) at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230) at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148) at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:165) at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:75) at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:67) at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:102) at org.eclipse.osgi.container.Module.publishEvent(Module.java:466) at org.eclipse.osgi.container.Module.doStop(Module.java:624) at org.eclipse.osgi.container.Module.stop(Module.java:488) at org.eclipse.osgi.container.SystemModule.stop(SystemModule.java:186) at org.eclipse.osgi.internal.framework.EquinoxBundle$SystemBundle$EquinoxSystemModule$1.run(EquinoxBundle.java:159) at java.lang.Thread.run(Unknown Source) !ENTRY org.eclipse.e4.ui.workbench 4 0 2017-12-05 13:59:31.269 !MESSAGE FrameworkEvent ERROR if you konw ,place tell me . thanks A: Please try to increase heap size of the eclipse * *Go to Eclipse Folder *Edit eclipse.ini *Set\increase the heap memory size like below -startup plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar --launcher.library plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807 -showsplash org.eclipse.platform --launcher.XXMaxPermSize 256m --launcher.defaultAction openFile -vmargs -Xms512m -Xmx1024m -XX:+UseParallelGC -XX:PermSize=256M -XX:MaxPermSize=1024M A: The above error is due to out of space of java heap memory are, you can increase your java heap size using : Go to the Run icon and select Run Configurations Select Arguments and Specify head size in VM Arguments. eg: Xmx1024
doc_23537810
SQL script myvar below is the parameter I'd like to be prompted when the script is run so that I enter the Table I want the changes applied to. PARAMETERS [myvar] TableID; UPDATE [myvar] INNER JOIN Excel_Data ON [myvar].[Part Number] = Excel_Data.[Part Number] SET [myvar].[Value] = '?', [myvar].Description = Excel_Data.Description, [myvar].[Ref] = '?' . . . WHERE [myvar].Description Is Null; Output Error message: Too few parameters. Expected 0. What I need I prefer a solution for above in a SQL script form as above, not involving VBA, preferably. I'd like to enter the Table name when prompted so the script knows which table to UPDATE. FYI: The PARAMETERS work when it is not a Table as I've shown in my script above. Help/advise is highly appreciated. EDIT 1 Since it seems not possible to use parameters as Table names, could you suggest a VBA solution? A sample code, perhaps? A: As said in the comments, you can't really solve this without VBA. You can store your SQL query in a string, and use a placeholder to indicate the tablename. Then get the tablename using an inputbox and replace the placeholder with the tablename. Dim sqlString As String sqlString = "UPDATE [%Placeholder%] " & vbCrLf & _ "INNER JOIN Excel_Data ON [%Placeholder%].[Part Number] = Excel_Data.[Part Number] " & vbCrLf & _ "SET [%Placeholder%].[Value] = '?', " & vbCrLf & _ ... "WHERE [%Placeholder%].Description Is Null;" sqlString = Replace(sqlString, "%PlaceHolder%", InputBox("Enter a tablename")) CurrentDb.Execute sqlString In a more mature solution, I'd create a form with a combobox containing all available table names, and add a function to sanitize tablenames (replace "]" with "]]")
doc_23537811
from setuptools import setup, Extension import pybind11 # The following is for GCC compiler only. #cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7'] cpp_args = [] sfc_module = Extension( 'test_sample', sources=['Test.cpp'], include_dirs=[pybind11.get_include()], language='c++', extra_compile_args=cpp_args, ) setup( name='test_sample', version='1.0', description='Python package with Test C++ extension (PyBind11)', ext_modules=[sfc_module], ) Then in the windows power shell, I will run python setup.py build However it complains cannot find multiple include files, I believe it will complain about missing library files later too: C:\VS2017Pro\VC\Tools\MSVC\xxxx\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Anaconda3_CS\lib\site-packages\pybind11\include -IC:\Anaconda3_CS\include -IC:\Anaconda3_CS\include -IC:\VS2017Pro\VC\Tools\MSVC\xxxx\ATLMFC\include -IC:\VS2017Pro\VC\Tools\MSVC\xxxx\include /EHsc /TpCppPython.cpp /Fobuild\temp.win-amd64-3.7\Release\Test.obj Test.cpp Z:\test_pybind11\stdafx.h(8): fatal error C1083: Cannot open include file: 'targetver.h': No such file or directory I know where this targetver.h is, just don't know how to add its location to the include path. Your help will be greatly appreciated. A: I know where to add more include paths, and the lib paths. One need to add them in the system environment variables: INCLUDE and LIB. Control Panel->Edit Environment Variable. Then add all the intended paths for include files to the variable INCLUDE, and add all the library paths to the variable LIB. Then the rebuild should be successful.
doc_23537812
"company": [ { "region": [ "Europe", "Germany" ], "productLine": "Produce" }, { "region": [ "Europe", "France" ], "productLine": "Produce" } ], "company2": [ { "region": [ "Europe", "Germany" ], "productLine": "Produce" }, { "region": [ "Americas", "USA" ], "productLine": "Produce" } ] } With this json data how can I rebuild it so that I have Europe/Americas value as the primary(unique) node with Germany/France as it's children? company/company1 would be sub-children of France/Germany. I cant seem to figure out how to build arrays while keeping the relations correct. I essence I need to reverse the node tree. Expected Output: Tree structure like this: -Europe -France -Company -Company2 I also need a special structure for a tree plugin: var source = [ { label: "Europe", items: [ {label: "France", items: [ {label: "SuperShop", items: [ {label: "Produce"} ]} ] }] }] What I need in the end is an Object array with value pair: label, items. Items being an object with sub-objects within. A: Obviously, I don't know why you need the new format, but it seems overly complex. If you have a large data set that you are looking through, you are going to take a hit on speed because, under it's current set up, you are going to have traverse over every element of the new array to find the one you are looking for ... var inputs = { "company": [ { "region": [ "Europe", "Germany" ], "productLine": "Produce" }, { "region": [ "Europe", "France" ], "productLine": "Produce" } ], "company2": [ { "region": [ "Europe", "Germany" ], "productLine": "Produce" }, { "region": [ "Americas", "USA" ], "productLine": "Produce" } ] }; var converter = {}; // This new format requires a 2 step process to prevent it from being N^2 // So convert the input into a tree // Region // -> Country // -> Company // -> Array of Products for(var company in inputs){ for(var i = 0; i < inputs[company].length; i++){ // Because the regions are an array of hashes it is simplest // to grab the value by using the previously gathered keys // and the key region var r = inputs[company][i]['region']; // Check if the region exists. If not create it. if(!converter[r[0]]){ converter[r[0]] = {}; } // Check if the country exists. If not create it. if(!converter[r[0]][r[1]]){ converter[r[0]][r[1]] = {}; } // Add the company to the array. if(!converter[r[0]][r[1]][company]){ converter[r[0]][r[1]][company] = []; } converter[r[0]][r[1]][company].push(inputs[company][i]['productLine']); } } var outputs = []; // Now walk converter and generate the desired object. for( var region in converter){ converted_region = {}; converted_region["label"] = region; converted_region["items"] = []; for( var country in converter[region]){ converted_country = {}; converted_country["label"] = country; converted_country["items"] = []; for( var company in converter[region][country]){ converted_company = {}; converted_company["label"] = company; converted_company["items"] = []; for(var i = 0; i < converter[region][country][company].length; i++){ converted_company["items"].push(converter[region][country][company][i]); } converted_country["items"].push(converted_company); } converted_region["items"].push(converted_country); } outputs.push(converted_region); }
doc_23537813
CREATE TABLE testA ( id integer, checked boolean ) CREATE TABLE testB ( id integer, testA_id integer ) I want to do a select from testB joined with testA and get all results which are checked. There are two ways: SELECT tA.*, tB.* FROM testB AS tB JOIN testA AS tA ON (tA.id = tB.testA_id AND tA.checked) or SELECT tA.*, tB.* FROM testB AS tB JOIN testA AS tA ON tA.id = tB.testA_id WHERE tA.checked Which way is preferred? And are there performance differences? A: Well, the WHERE clause filters the results. The ON just defines the way the tables are joined together. In your example there would be no difference. But take a look at the following: CREATE TABLE testA ( id integer, checked boolean ) CREATE TABLE testB ( id integer, testA_id integer, checked boolean ) As you can see i have added a checked column in TestB. There might be rows in TableA that have no rows in TableB Like the following data: TestA ID|checked 1|true 2|true 3|false TestB ID|testA_id|checked 1|1|true 2|1|false 3|3|true As you can see there is no TestB for TestA id = 2 Now, let's assume you want to display ALL TestA rows along with the checked TableB rows (if any). So you need a left join: First Case SELECT tA.*, tB.* FROM testB AS tB LEFT JOIN testA AS tA ON (tA.id = tB.testA_id AND tB.checked) Reults ID|checked|ID|testA_id|checked 1|true|1|1|true 2|true|null|null|null 3|false||3|3|true ID 1, 2 and 3 of TableA is returned and if there is a checked TableB row then we return that too. Second Case SELECT tA.*, tB.* FROM testB AS tB LEFT JOIN testA AS tA ON tA.id = tB.testA_id WHERE tB.checked Reults ID|checked|ID|testA_id|checked 1|true|1|1|true 3|false||3|3|true In this case only IDs 1 and 3 are returned because we filter the results to show only the ones that have TableB checked. A: No performance differences, the optimizer takes care of it, so the two queries are actually the same. You can confirm by using EXPLAIN on your query.
doc_23537814
int main() { namespace bp = boost::python; Py_Initialize(); bp::object main_module = bp::import("__main__"); bp::import("ldap"); bp::import("ldif"); bp::object main_namespace = main_module.attr("__dict__"); bp::exec("import ldap,ldif\n" "l = ldap.initialize('ldaps://RIO-PC')\n", main_namespace); //get the ldap object from the main_namespace boost::python::object ldap = boost::python::extract<boost::python::object>(main_namespace["l"]); //...do something... } Now I want to get a brain new ldap object, could I do it like this? bp::object main_module_2 = bp::import("__main__"); bp::import("ldap"); bp::import("ldif"); bp::object main_namespace_2 = main_module_2.attr("__dict__"); bp::exec("import ldap,ldif\n" "l = ldap.initialize('ldaps://RIO-PC')\n", main_namespace); //get the ldap object from the main_namespace boost::python::object ldap_2 = boost::python::extract<boost::python::object>(main_namespace_2["l"]); If this is unsafe, what should I do?If this is safe, do I have another options? environment : boost version : 1_55_0 compiler : vc2008 os : win7 64bits A: Now I want to get a brain new ldap object, could I do it like this? Yes you can. The ldap module is a wrapper over the OpenLDAP C API, and as such if the documentation of the python module isn't clear enough in itself, you can always consult the original documentation [1,2]. There you will find that the LDAP structure returned from the open/init/initialize method calls is a per-connection descriptor. To further increase your confidence, you can verify that on your particular platform the object is not reused. You can do so by checking that the returned python object identifiers (id(obj)) are different: #include <boost/python.hpp> #include <iostream> int main() { namespace bp = boost::python; Py_Initialize(); bp::object main_module = bp::import("__main__"); bp::import("ldap"); bp::object main_namespace = main_module.attr("__dict__"); bp::exec( "import ldap\n" "a = ldap.initialize('ldaps://tls.example.com')\n" "b = ldap.initialize('ldaps://tls.example.com')\n", main_namespace); boost::python::object a = boost::python::extract< boost::python::object>(main_namespace["a"]); boost::python::object b = boost::python::extract< boost::python::object>(main_namespace["b"]); std::cout << "id(a) = " << reinterpret_cast<long>(a.ptr()) << std::endl; std::cout << "id(b) = " << reinterpret_cast<long>(b.ptr()) << std::endl; }
doc_23537815
'train' and 'class' have different lengths In spite of having both of them with same lengths y_pred=knn(train=training_set[,1:2], test=Test_set[,-3], cl=training_set[,3], k=5) Their lengths are given below- > dim(training_set[,-3]) [1] 300 2 > dim(training_set[,3]) [1] 300 1 > head(training_set) # A tibble: 6 x 3 Age EstimatedSalary Purchased <dbl> <dbl> <fct> 1 -1.77 -1.47 0 2 -1.10 -0.788 0 3 -1.00 -0.360 0 4 -1.00 0.382 0 5 -0.523 2.27 1 6 -0.236 -0.160 0 > Test_set # A tibble: 100 x 3 Age EstimatedSalary Purchased <dbl> <dbl> <fct> 1 -0.304 -1.51 0 2 -1.06 -0.325 0 3 -1.82 0.286 0 4 -1.25 -1.10 0 5 -1.15 -0.485 0 6 0.641 -1.32 1 7 0.735 -1.26 1 8 0.924 -1.22 1 9 0.829 -0.582 1 10 -0.871 -0.774 0 A: It's because knn is expecting class to be a vector and you are giving it a data table with one column. The test knn is doing is whether nrow(train) == length(cl). If cl is a data table that does not give the answer you are expecting. Compare: > length(data.frame(a=c(1,2,3))) [1] 1 > length(c(1,2,3)) [1] 3 If you use cl=training_set$Purchased, which extracts the vector from the table, that should fix it. This is specific gotcha if you are moving from data.frame to data.table because the default drop behaviour is different: > dt <- data.table(a=1:3, b=4:6) > dt[,2] b 1: 4 2: 5 3: 6 > df <- data.frame(a=1:3, b=4:6) > df[,2] [1] 4 5 6 > df[,2, drop=FALSE] b 1 4 2 5 3 6
doc_23537816
public static void main(String[] args) { Alpha_Core engine = new Alpha_Core(); setDisplayMode(1280,720, "FullScreenMode"); engine.Init_Program_Loop(); } public static void setDisplayMode(int width, int height, String title) { Display.setTitle(title); try { // DisplayMode[] modes = Display.getAvailableDisplayModes(); // // for (int i=0;i<modes.length;i++) { // DisplayMode current = modes[i]; // System.out.println(current.getWidth() + "x" + current.getHeight() + "x" + // current.getBitsPerPixel() + " " + current.getFrequency() + "Hz"); // } Display.setDisplayMode(new DisplayMode(width, height)); Display.setFullscreen(true); Display.create(); Keyboard.create(); Mouse.create(); } catch (LWJGLException e) { e.printStackTrace(); } } What am I missing, has it something to do with BitsPerPixel? A: I think you're looking for this: DisplayMode displayMode = null; DisplayMode[] modes = Display.getAvailableDisplayModes(); for (int i = 0; i < modes.length; i++) { if (modes[i].isFullscreenCapable()) { displayMode = modes[i]; } } Replace Display.setDisplayMode(new DisplayMode(width, height)); With Display.setDisplayMode(displayMode); Or, to show you the full code, public static void main(String[] args) { Alpha_Core engine = new Alpha_Core(); setDisplayMode(1280,720, "FullScreenMode"); engine.Init_Program_Loop(); } public static void setDisplayMode(int width, int height, String title) { Display.setTitle(title); DisplayMode displayMode = null; DisplayMode[] modes = Display.getAvailableDisplayModes(); for (int i = 0; i < modes.length; i++) { if (modes[i].isFullscreenCapable()) { displayMode = modes[i]; } } Display.setDisplayMode(displayMode); Display.setFullscreen(true); Display.create(); Keyboard.create(); Mouse.create(); } catch (LWJGLException e) { e.printStackTrace(); } }
doc_23537817
We have to index multiple manufactures and each manufacturer has a different catalog per country. Each catalog for each manufacture per country is about 8GB of data. I was thinking it might be easier to have an index per manufacture per country and have some way to tell Solr in the URL which index to search from. Is that the best way of doing this? If so, how would I do it? Where should I start looking? If not, what would be the best way? I am using Solr 3.5 A: In general there are two ways of solving this: * *Split each catalog into its own core, running a large multi core setup. This will keep each index physically separated from each other, and will allow you to use different properties (language, etc) and configuration for each core. This might be practical, but will require quite a bit of overhead if you plan on searching through all the core at the same time. It'll be easy to split the different cores into running on different servers later - simply spin the cores up on a different server. *Run everything in a single core - if all the attributes and properties of the different catalogs are the same, add two fields - one containing the manufacturer and one containing the country. Filter on these values when you need to limit the hits to a particular country or manufacturer. It'll allow you to easily search the complete index, and scalability can be implemented by replication or something like SolrCloud (coming in 4.0). If you need multilanguage support you'll have to have a field for each language with the settings you need for that language (such as stemming). There are a few tidbits of information about this on the Solr wiki, but my suggestion is to simply try one of the methods and see if that solves your issue. Moving to the other solution shouldn't be too much work. The simplest implementation is to keep everything in the same index.
doc_23537818
here's the sample string 5/31/1948@14:57 I need to strip out the / @ : Theres this doc: http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html But it's really confusing. A: You can use the replaceAll method as: String filetredStr = inputStr.replaceAll("[@/:]",""); And if you want to delete any non-digit you can do: String filetredStr = inputStr.replaceAll("[^0-9]",""); A: If you're looking to split it up, use String#split() String[] parts = "5/31/1948@14:57".split("[/@:]"); A: Do something like this:- s.replaceAll("[\\/@:]", ""); A: An alternative to replaceAll(a,b) is as follows: String str = "5/31/1948@14:57"; String charsToRemove = "/@:"; for (int i = 0; i < charsToRemove.length(); i++) { str = str.replace(charsToRemove.charAt(i)+"", ""); }
doc_23537819
I got one sample code for iPad which is able to render the dynamic form,but this sample code is using UIPopoverController, which is not supported by iPhone application. So I am looking for some sample code which should work in iPhone. Below is the code which shows combo box on clicking the button in dynamic form. I need the code which should show picker with list items. sample code: https://github.com/ecrichlow/iPad-Dynamic-Table-Cells - (IBAction)buttonPressed:(id)sender { [delegate rowItemWasSelected:self]; if (self.itemControlType == ControlTypeToggleButton) { ... } else if (self.itemControlType == ControlTypePopup) { ... } else if (self.itemControlType == ControlTypeCombo) { UITableViewController *popoverTable = [[[UITableViewController alloc] initWithStyle:UITableViewStylePlain] autorelease]; UIToolbar *toolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, DEFAULT_POPOVER_WIDTH, DEFAULT_TOOLBAR_HEIGHT)] autorelease]; UIView *containerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, DEFAULT_POPOVER_WIDTH, ([self.controlSelections count] * popoverTable.tableView.rowHeight) + DEFAULT_TOOLBAR_HEIGHT)] autorelease]; UIViewController *containerViewController = [[[UIViewController alloc] init] autorelease]; UIPopoverController *popoverController = [[UIPopoverController alloc] initWithContentViewController:containerViewController]; UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(DEFAULT_COMBO_TEXTFIELD_MARGIN, (DEFAULT_TOOLBAR_HEIGHT - DEFAULT_COMBO_TEXTFIELD_HEIGHT) / 2, DEFAULT_POPOVER_WIDTH - (DEFAULT_COMBO_TEXTFIELD_MARGIN * 2), DEFAULT_COMBO_TEXTFIELD_HEIGHT)]; textField.delegate = self; textField.autocorrectionType = UITextAutocorrectionTypeNo; textField.autocapitalizationType = UITextAutocapitalizationTypeNone; textField.font = [UIFont systemFontOfSize:DEFAULT_COMBO_FONT_SIZE]; textField.borderStyle = UITextBorderStyleRoundedRect; textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; [textField addTarget:self action:@selector(fieldTextDidUpdate:) forControlEvents:UIControlEventEditingDidEnd]; containerViewController.view = containerView; popoverTable.tableView.dataSource = self; popoverTable.tableView.delegate = self; popoverTable.tableView.frame = CGRectMake(0, DEFAULT_TOOLBAR_HEIGHT, DEFAULT_POPOVER_WIDTH, [self.controlSelections count] * popoverTable.tableView.rowHeight); popoverController.popoverContentSize = CGSizeMake(DEFAULT_POPOVER_WIDTH, ([self.controlSelections count] * popoverTable.tableView.rowHeight) + DEFAULT_TOOLBAR_HEIGHT); popoverController.delegate = self; [toolbar addSubview:textField]; [containerView addSubview:toolbar]; [containerView addSubview:popoverTable.tableView]; optionPopoverController = popoverController; [popoverController presentPopoverFromRect:control.frame inView:control.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; // If there's currently an object that's first responder, make it resign that status for (UIView *subview in self.control.superview.subviews) { if ([subview isKindOfClass:[UITextField class]]) { if ([subview isFirstResponder]) { [subview resignFirstResponder]; [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]]; } } } [textField becomeFirstResponder]; } else if (self.itemControlType == ControlTypeButton) { // Don't need to do anything here. Caller passed in target and action. But in order to trigger delegate rowItemWasSelected this control type was added here. } } A: The project available on git-hub Popover for iPhone will help you to implement the popover in iPhone app. The only thing you need to do is check the device in your above code & perform the actions accordingly. Add 6 files to your project FPPopoverController.h/.m, FPPopoverView.h/m, and FPTouchView.h/.m then create two sample DemoPopOverTableController.h #import <UIKit/UIKit.h> #import "FPPopoverController.h" @interface DemoPopOverTableController : UITableViewController { FPPopoverController *popOverController; NSArray *subCat; } -(id)initWithStyle:(UITableViewStyle)style andSubCategory:(NSArray *)subCategories -(void)setPopOver:(FPPopoverController*)popOver; @end and DemoPopOverTableController.m #import "DemoPopOverTableController.h" #import "FPPopoverController.h" @interface DemoTableController () @end @implementation DemoTableController -(id)initWithStyle:(UITableViewStyle)style andSubCategory:(NSArray *)subCategories { self = [super init]; if (self) { // Custom initialization subCat = [NSArray arrayWtihArray:subCategories] ; } return self; } -(void)setPopOver:(FPPopoverController *)popOver { popOverController=popOver; } - (void)viewDidLoad { [super viewDidLoad]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [subCat count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil) cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease]; NSString *tempCat=[subCat objectAtIndex:indexPath.row]; cell.textLabel.text =tempCat; return cell ; } #pragma mark - Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"selected Category: %@",[subCat objectAtIndex:indexPath.row]); [popOverController dismissPopoverAnimated:YES]; } @end This is not complete answer but this is something you can do in your above code if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone) { //iPhone popover lines of code DemoPopOverTableController *controller = [[DemoPopOverTableController alloc] initWithStyle:UITableViewStylePlain andSubCategory:subCat]; FPPopoverController *popover = [[FPPopoverController alloc] initWithViewController:controller]; [controller setPopOver:popover]; [controller release]; popover.delegate = self; popover.tint = FPPopoverDefaultTint; popover.arrowDirection = FPPopoverArrowDirectionUp; popover.contentSize = CGSizeMake(200, 200); //sender is the UIButton view [popover presentPopoverFromView:sender]; [popover release]; } else { //the original line of code you have already in your code } And you can implement the delegate methods to perform some actions upon touching teh table view - (void)presentedNewPopoverController:(FPPopoverController *)newPopoverController shouldDismissVisiblePopover:(FPPopoverController*)visiblePopoverController { [visiblePopoverController dismissPopoverAnimated:YES]; [visiblePopoverController autorelease]; } - (void)popoverControllerDidDismissPopover:(FPPopoverController *)popoverController { // do something of your choice } A: You can modify the sample code iPad-Dynamic-Table-Cells for rendering dynamic form in iPhone along with with popover display also Add the below 6 files of project available on git-hub https://github.com/50pixels/FPPopover to your iPad-Dynamic-Table-Cells sample code FPPopoverController.h/.m, FPPopoverView.h/m, and FPTouchView.h/.m Now modify the FPTouchView.m, EditableTableDataRowItem.h and EditableTableDataRowItem.m as below //In EditableTableDataRowItem.h @interface EditableTableDataRowItem : UIViewController <UITableViewDataSource, UITableViewDelegate, UIPopoverControllerDelegate, UITextFieldDelegate,FPPopoverControllerDelegate> { id<EditableTableDataRowItemDelegate> delegate; RowItemControlType itemControlType; // So named to denote that this does not correspond to a UIControl NSArray *controlSelections; // List of items to display for popup control type NSString *listKey; // If controlSelections array contains NSManagedObjects or NSDictionaries, the key to use to get a string to represent the item CGSize baseSize; // Default size of the control, with width relative to other items on the row BOOL resizeable; // Determines whether item can be resized based on row width UIControl *control; // Standard control particular to the type of row item UIImage *normalImage; // Used to customize the appearance of any button-based control type UIImage *selectedImage; // Used to customize the appearance of any button-based control type CGSize originalBaseSize; int state; int selectedIndex; UIPopoverController *optionPopoverController; FPPopoverController *popover; id<FPPopoverControllerDelegate> delegate1; } @property(assign) id<EditableTableDataRowItemDelegate> delegate; @property(assign) id<FPPopoverControllerDelegate> delegate1; @property(nonatomic, retain) FPPopoverController *popover; . . //In EditableTableDataRowItem.m - (IBAction)buttonPressed:(id)sender { [delegate rowItemWasSelected:self]; if (self.itemControlType == ControlTypeToggleButton) { . . . } else if (self.itemControlType == ControlTypePopup) { UITableViewController *popoverTable = [[[UITableViewController alloc] initWithStyle:UITableViewStylePlain] autorelease]; popoverTable.tableView.dataSource = self; popoverTable.tableView.delegate = self; popover = [[FPPopoverController alloc] initWithViewController:popoverTable]; popover.tint = FPPopoverDefaultTint; if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { popover.contentSize = CGSizeMake(300, 500); } else { popover.contentSize = CGSizeMake(200, 300); } popover.arrowDirection = FPPopoverArrowDirectionAny; [popover presentPopoverFromView:sender]; } . . . } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [popover dismissPopoverAnimated:YES]; } //In FPTouchView.m file //Need to handle this method -(UIView*)hitTest:(CGPoint)point withEvent:(UIEvent *)event { UIView *subview = [super hitTest:point withEvent:event]; //To-Do // return subview; }
doc_23537820
Documents can sometimes exchange objects, but a single object should never be 'part' of more than one document. My document class contains a bunch of methods which serve as event handlers. Whenever an object enters the document, I use AddHandler to set up the events, and whenever an object is removed from the document I use RemoveHandler to undo the damage. However, there are cases where it's difficult to make sure all the steps are properly taken and I might thus end up with rogue event handlers. Long story short; how do I remove all the handlers that are pointing to a specific method? Note, I don't have a list of potential event sources, these could be stored anywhere. Something like: RemoveHandler *.SolutionExpired, AddressOf DefObj_SolutionExpired A: You can use Delegate.RemoveAll(). (The part you're interested in is in button2_Click) public void Form_Load(object sender, EventArgs e) { button1.Click += new EventHandler(button1_Click); button1.Click += new EventHandler(button1_Click); button2.Click += new EventHandler(button2_Click); TestEvent += new EventHandler(Form_TestEvent); } event EventHandler TestEvent; void OnTestEvent(EventArgs e) { if (TestEvent != null) TestEvent(this, e); } void Form_TestEvent(object sender, EventArgs e) { MessageBox.Show("TestEvent fired"); } void button2_Click(object sender, EventArgs e) { Delegate d = TestEvent as Delegate; TestEvent = Delegate.RemoveAll(d, d) as EventHandler; } void button1_Click(object sender, EventArgs e) { OnTestEvent(EventArgs.Empty); } You should note that it doesn't alter the contents of the delegates you pass in to it, it returns an altered delegate. Consequently, you won't be able to alter the events on a button you've dropped on a form from the form, as button1.Click can only have += or -= used on it, not =. This won't compile: button1.Click = Delegate.RemoveAll(d, d) as EventHandler; Also, be sure that wherever you're implementing this you're watching out for the potential of race conditions. You could end up with some really strange behavior if you're removing handlers from an event that is being called by another thread! A: public class TheAnswer { public event EventHandler MyEvent = delegate { }; public void RemoveFromMyEvent(string methodName) { foreach (var handler in MyEvent.GetInvocationList()) { if (handler.Method.Name == methodName) { MyEvent -= (EventHandler)handler; } } } } EDIT 2: Apologies for my misunderstanding--I see that you were pretty clear about not having access to the event sources in your original post. The simplest way I can think of to solve this problem involves implementing a Shared dictionary of object-to-document bindings. When an object enters a document, check the dictionary for an existing binding to another document; if present, remove handlers that refer to the old document before adding them for the new. Either way, update the dictionary with the new binding. I think in most cases the performance and memory impacts would be negligible: unless you're dealing with many tens of thousands of small objects and frequently exchange them between documents, the memory overhead of each key/value pair and performance hit for each lookup operation should be fairly small. As an alternative: if you can detect (in the document event handlers) that the sender of the event is no longer relevant to the document, you can detach the events there. These seem like the kind of ideas you might have already rejected--but maybe not! A: Use Delegate.RemoveAll (maybe using reflection if the Delegate instance is private).
doc_23537821
Here is an example of data that I am working with: set.seed(9909) Subjects <- 1:100 values <- c(rnorm(n = 50, mean = 30, sd = 5), rnorm(n = 50, mean = 35, sd = 8)) data <- cbind(Subjects, values) group1 <- rep("group1", 50) group2 <- rep("group2", 50) group <- c(group1, group2) data <- data.frame(data, group) data And this is what my current ggplot2 code looks like (distribution as points with the mean and 90% CI overlaid on top for each group): ggplot(data, aes(x = group, y = values, group = 1)) +   geom_point() + stat_summary(fun.y = "mean", color = "red", size = 5, geom = "point") + stat_summary(fun.data = "mean_cl_normal", color = "red", size = 2, geom = "errorbar", width = 0, fun.args = list(conf.int = 0.9)) + theme_bw() Is it possible to get the mean and confidence intervals to position_dodge to the right of their respective groups? A: You can use position_nudge: ggplot(data, aes(x = group, y = values, group = 1)) + geom_point() + stat_summary(fun.y = "mean", color = "red", size = 5, geom = "point", position=position_nudge(x = 0.1, y = 0)) + stat_summary(fun.data = "mean_cl_normal", color = "red", size = 2, geom = "errorbar", width = 0, fun.args = list(conf.int = 0.9), position=position_nudge(x = 0.1, y = 0)) + theme_bw()
doc_23537822
doc_23537823
import pytest @pytest.fixture def pyplug<ID>_fixture(): pass where <ID> is replaced with the number I gave the plugin, i.e. '0', '1'... I created a setup.py for each plugin: from setuptools import setup setup( name='pyplug<ID>', packages=['pyplug<ID>'], entry_points={'pytest11': ['pkg = pyplug<ID>.plugin']} ) and inside each package, I created another dir (same name) with plugin.py file, containing the fixture described earlier. This is my dir tree AFTER I run python setup.py bdist_wheel for each plugin: src/ ├── pyplug0 │   ├── build │   │   ├── bdist.linux-x86_64 │   │   └── lib │   │   └── pyplug0 │   │   └── plugin.py │   ├── dist │   │   └── pyplug0-0.0.0-py3-none-any.whl │   ├── pyplug0 │   │   └── plugin.py │   ├── pyplug0.egg-info │   │   ├── dependency_links.txt │   │   ├── entry_points.txt │   │   ├── PKG-INFO │   │   ├── SOURCES.txt │   │   └── top_level.txt │   └── setup.py └── pyplug1 ├── build │   ├── bdist.linux-x86_64 │   └── lib │   └── pyplug1 │   └── plugin.py ├── dist │   └── pyplug1-0.0.0-py3-none-any.whl ├── pyplug1 │   └── plugin.py ├── pyplug1.egg-info │   ├── dependency_links.txt │   ├── entry_points.txt │   ├── PKG-INFO │   ├── SOURCES.txt │   └── top_level.txt └── setup.py This is my pip freeze: attrs==19.3.0 importlib-metadata==1.6.0 more-itertools==8.2.0 packaging==20.3 pluggy==0.13.1 py==1.8.1 pyparsing==2.4.7 pyplug0==0.0.0 pyplug1==0.0.0 pytest==5.4.1 pytest-html==2.1.1 pytest-metadata==1.8.0 pytest-tldr==0.2.1 six==1.14.0 wcwidth==0.1.9 zipp==3.1.0 and this is my test file content: def test_plugin(pyplug0_fixture): pass def test_plugin2(pyplug1_fixture): pass The problem is, the plugins are not registered OK. When I install only one (doesn't matter which) and test it, it's OK. When I install both, one is overridden by the other, which makes no sense IMO, since they have different names (for both the fixture, and the plugin) I run py3.6.10 on Ubuntu16.04 A: Found it. Both setup.py had the same entry point: entry_points={"pytest11": ["KEY = VAL"]} the VAL was different, but I kept using the same KEY, so the latest always won
doc_23537824
Thanks :) A: Devise stores passwords and other data inside the table associated with the model you specify during setup. During setup you pass it a model name: # MODEL is a placeholder for the model you want to use with Devise, usually 'User' rails generate devise MODEL The generator then creates a migration that alters the table associated with that model. So if you passed it User, the users table will be altered. Have a look at the migration files inside Devise.
doc_23537825
A: Did you consider the XMPP service from google app engine for java? http://code.google.com/appengine/docs/java/xmpp/ It has very good integration obviously with the rest of google apis and the server can be hosted for free if you're under the quota, or running it on localserver using jetty A: You can make use of JQuery / PHP Chat which is free and can be integarted into sites. A: Can't do it with Apache. Chat is usually done through a technique called Comet, which is not supported by Apache, AFAIK. GMail uses this technique. Another, less efficient possibility is using polling strategy, which involves a lot of extraneous server-client communication.
doc_23537826
to use func1() i need to run func2(s) which is a void with a pointer to characters in it's decleration: func2(char *string_one){}; can I do this: func1(firststring,func2(s)); in which i add firststring to the result of func2() using 2 pointers just like in func2()? func1() decleration: func1(char *string_one, char *string_two){}; A: Having void as return type of func2 doesn't allow to use it as a char * parameter of func1. You have to return char * from func2: char* func2(char* string_one) { }.
doc_23537827
CONSTRAINT chk_spl_chars_model CHECK (Model LIKE '%[A-Z]+%') This didnt work. It is not allowing to enter any value. Any Help is appreciated. Following is the query u yse to create table CREATE TABLE Cars( Model VARCHAR(10) NOT NULL ,CONSTRAINT chk_spl_chars_model CHECK (Model LIKE '%^[A-Z]+$%') ); This is accepting any value to be inserted even lowercase and special characters A: You must using collation in your constraint: CONSTRAINT chk_spl_chars_model CHECK (not (Model COLLATE Latin1_General_100_CS_AI LIKE '%[a-z]%')) You can using following format too (change collation of model column): CREATE TABLE Cars( Model VARCHAR(10) COLLATE Latin1_General_100_CS_AI NOT NULL ,CONSTRAINT chk_spl_chars_model CHECK (NOT Model LIKE '%[a-z]%') ); A: You need to use a case sensitive collation, as mehdi's answer indicated, but you also need to change what you're looking for: CREATE TABLE Cars( Model VARCHAR(10) collate Latin1_General_CS_AI NOT NULL ,CONSTRAINT chk_spl_chars_model CHECK ( Model NOT LIKE '%[^ABCDEFGHIJKLMNOPQRSTUVWXYZ]%') ); You want: * *a NOT LIKE because we want to search for characters that we don't want to appear *% matches "any character" so we want to match any number of characters *then ^ within a [] block indicates to match any character not included in the set *ABCDEFGHIJKLMNOPQRSTUVWXYZ because even in most case sensitive collations, lower case letters appear between upper case letters if you use a range expression like A-Z. So the complete pattern says "match any number of characters, then one character that isn't an upper case character, then any number of characters" - and so, in other words, it matches any string that contains at least one non-upper case character - and if we match that, then we reject that value (because of the NOT LIKE). ^ (outside of []), $ and + have no special meaning for LIKE patterns.
doc_23537828
I have two tables: public class Asset { [Key] public Guid Id { get; set; } public string Name { get; set; } public string Description { get; set; } // Relationships public ICollection<AssetMixRecord> AssetMixRecords { get; set; } } public class AssetMixRecord { public decimal Percentage { get; set; } public Guid AssetId { get; set; } // Relationships public Guid ParentAssetId { get; set; } } The context looks like this: modelBuilder.Entity<Asset>() .HasMany(a => a.AssetMixRecords) .WithOne() .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity<AssetMixRecord>() .HasKey(c => new { c.ParentAssetId, c.AssetId }) .IsClustered(); The migration code for this looks like: migrationBuilder.CreateTable( name: "AssetMixRecords", columns: table => new { AssetId = table.Column<Guid>(nullable: false), ParentAssetId = table.Column<Guid>(nullable: false), Percentage = table.Column<decimal>(type: "decimal(8,7)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_AssetMixRecords", x => new { x.ParentAssetId, x.AssetId }) .Annotation("SqlServer:Clustered", true); table.ForeignKey( name: "FK_AssetMixRecords_Assets_AssetId", column: x => x.AssetId, principalTable: "Assets", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); This is all nice and right. But 'ParentAssetId' also is a foreign key to 'Assets.Id'. Our use case looks like this: var asset1 = new Asset(); var asset2 = new Asset(); dbContext.Add(asset1); dbContext.Add(asset2); dbContext.SaveChanges(); var asset3 = new Asset(); asset3.AssetMixRecords.Add(new AssetMixRecord() { AssetId = asset1.Id, ParentAssetId = asset3.Id }); asset3.AssetMixRecords.Add(new AssetMixRecord() { AssetId = asset2.Id, ParentAssetId = asset3.Id }); dbContext.Add(asset3); dbContext.SaveChanges(); I'm not able to to get this 2nd foreign key into the migration code. Should I just add it manually? Thanks and regards S. A: Please check out my solution with complete demo, it will generate following migration. I am not sure if it is possible to have DeleteBehavior.Cascade with such schema, EF migration tool was complaining about circular dependency. migrationBuilder.DropForeignKey( name: "FK_AssetMixRecords_Assets_AssetId", table: "AssetMixRecords"); migrationBuilder.AddForeignKey( name: "FK_AssetMixRecords_Assets_AssetId", table: "AssetMixRecords", column: "AssetId", principalTable: "Assets", principalColumn: "Id"); migrationBuilder.AddForeignKey( name: "FK_AssetMixRecords_Assets_ParentAssetId", table: "AssetMixRecords", column: "ParentAssetId", principalTable: "Assets", principalColumn: "Id"); Demo itself is below. Please notice that there are 2 navigation properties inside Asset. EF will load there child entities based on their location (AssetId or ParentAssetId) using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace ConsoleApp9 { public class Asset { [Key] public Guid Id { get; set; } public string Name { get; set; } public string Description { get; set; } // items where AssetMixRecord.AssetId == Id public ICollection<AssetMixRecord> AssetMixRecords { get; set; } // items where AssetMixRecord.ParentAssetId == Id public ICollection<AssetMixRecord> ParentAssetMixRecords { get; set; } } public class AssetMixRecord { public decimal Percentage { get; set; } public Guid AssetId { get; set; } public virtual Asset Asset { get; set; } public Guid ParentAssetId { get; set; } public virtual Asset ParentAsset { get; set; } } public class ApplicationDbContext : DbContext { public DbSet<Asset> Assets { get; set; } public DbSet<AssetMixRecord> AssetMixRecords { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Server=DESKTOP-1111111;Database=testef11db;Integrated Security=true;"); base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Asset>() .HasMany(a => a.AssetMixRecords) .WithOne(x => x.Asset) .HasForeignKey(x => x.AssetId) .OnDelete(DeleteBehavior.NoAction); modelBuilder.Entity<Asset>() .HasMany(x => x.ParentAssetMixRecords) .WithOne(x => x.ParentAsset) .HasForeignKey(x => x.ParentAssetId) .OnDelete(DeleteBehavior.NoAction); modelBuilder.Entity<AssetMixRecord>() .HasKey(c => new { c.ParentAssetId, c.AssetId }) .IsClustered(); base.OnModelCreating(modelBuilder); } } class Program { static void Main(string[] args) { var dbContext = new ApplicationDbContext(); var asset1 = new Asset(); var asset2 = new Asset(); dbContext.Add(asset1); dbContext.Add(asset2); dbContext.SaveChanges(); var assetDataMixRecord = new AssetMixRecord() { AssetId = asset1.Id, ParentAssetId = asset2.Id }; dbContext.Add(assetDataMixRecord); dbContext.SaveChanges(); var assets = dbContext.Assets .Include(x => x.AssetMixRecords) .Include(x => x.ParentAssetMixRecords) .ToList(); } } } If you do not want to ParentAssetId be equal to ChildAssetId simply add code below to solution above modelBuilder.Entity<AssetMixRecord>() .HasCheckConstraint("PK_Check_ChildAssetId_And_ParentAssetId", "ParentAssetId != ChildAssetId"); Your use case will work fine if you change AssetMixRecords to ParentAssetMixRecords for asset3 var dbContext = new ApplicationDbContext(); var asset1 = new Asset(); var asset2 = new Asset(); dbContext.Add(asset1); dbContext.Add(asset2); dbContext.SaveChanges(); var asset3 = new Asset(); asset3.ParentAssetMixRecords.Add(new AssetMixRecord() { AssetId = asset1.Id, ParentAssetId = asset3.Id }); asset3.ParentAssetMixRecords.Add(new AssetMixRecord() { AssetId = asset2.Id, ParentAssetId = asset3.Id }); dbContext.Add(asset3); dbContext.SaveChanges();
doc_23537829
/usr/pgsql-11/bin/postgresql-11-setup initdb systemctl enable postgresql-11 systemctl start postgresql-11 and then went and configured the postgresql.conf file. Now I need to reload the database so those changes take effect. I tried sudo pg_ctl reload using the postgres account, which then prompts me for postgres's password. This account was created with the initializing, to my understanding, and doesn't have a password, but just pressing enter is not accepted. I then tried changing the password by doing su -u postgres psql postgres from root and in the shell executing ALTER USER postgres PASSWORD 'myPasswordHere'; which did return ALTER ROLE as confirmation. Retrying the reload as above, the new password still is not being accepted. I then tried doing systemctl restart postgres-11 as root, but that seemed to have completely broken the database, not allowing me to do any process involving the database or even access the Postgres shell. I had to delete the data directory and rerun the initdb command above to restart everything (and the pg_ctl commands still doesn't accept my password). How do I correctly reload the database so my changes to postgresql.conf are implemented? A: You are confused on many levels. * *Database users are different from operating system users. If you change postgres's password in the database, the operating system user still has no password. I cannot see how that breaks the database though. Maybe your pg_hba.conf file is misconfigured. *You run pg_ctl reload as operating system user postgres, not as root, because postgres owns the PostgreSQL processes, so there is no need for sudo and hence no need for an operating system password. You should probably read the PostgreSQL documentation about client authentication and user management.
doc_23537830
I'm currently have this effect. And this is my code return Scaffold( body: SafeArea( child: Container( margin: EdgeInsets.symmetric(horizontal: 12), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Icon( Icons.search, size: 30, ), Icon( Icons.more_horiz, size: 30, ), ], ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Recipes'), ], ) ], ), ), ), ); I'm open to any Widget I'm new and I come from a React background thats why I'm using Row and Columns. Also its putting a nested Column a good idea. Do Flutter have a tag to put the recipe name? A: Try out below code: return Scaffold( body: SafeArea( child: Container( margin: EdgeInsets.symmetric(horizontal: 12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, // added this line here instead of child column children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Icon( Icons.search, size: 30, ), Icon( Icons.more_horiz, size: 30, ), ], ), Column( children: [ Text('Recipes'), ], ) ], ), ), ), ); A: You are using crossAxisAlignment at the inner Column. Instead of that You have to apply crossAxisAlignment at outer Column. Note: Flutter apply your margin and padding in priority based. So outer Column has more priority than inner Column return Scaffold( body: SafeArea( child: Container( margin: EdgeInsets.symmetric(horizontal: 12), child: Column( // use alignment here crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Icon( Icons.search, size: 30, ), Icon( Icons.more_horiz, size: 30, ), ], ), Column( //crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Recipes'), ], ) ], ), ), ), ); A: wrap your Text Widget with Align widget and give alignment to centerLeft. And remove crossAxisAlignment from inner column.. i have provided the code below.. Scaffold( body: SafeArea( child: Container( margin: EdgeInsets.symmetric(horizontal: 12), child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Icon( Icons.search, size: 30, ), Icon( Icons.more_horiz, size: 30, ), ], ), Column( children: [ Align( alignment: Alignment.centerLeft, child: Text( 'Recipes', ), ), ], ) ], ), ), ), ),
doc_23537831
when i create a new project, this error occurs
doc_23537832
Today I installed Debugger for Chrome from Visual Studio Marketplace. https://marketplace.visualstudio.com/items/msjsdiag.debugger-for-chrome In theory I should be able to set break points in vscode but I keep getting this error when I run the debugger: [webkit-debug-adapter] Got response from target app, but no valid target pages found The reason for this is because I do not know how to set it up properly. I have my app running on port 9000 using Grunt. Here is the debugger config file: { "version": "0.2.0", "configurations": [ { "name": "Attach", "type": "chrome", "request": "attach", "port": 9000, "webRoot": "./app/scripts" } ] } Does anyone know how to attach the debugger? A: I managed to get this working myself. For anyone else who comes across this problem, here is the config file. { "version": "0.2.0", "configurations": [ { "name": "Launch", "type": "chrome", "request": "launch", "url": "http://localhost:9000/",//Change to whatever you homepage is "runtimeArgs": [ "--new-window", //Open in new window "--user-data-dir=C:/dev/", //Can be any directory. Makes chrome load in a different directory so that it opens in a new instance. "--remote-debugging-port=9222" //Open in port 9222 (standard chrome debug port) ], "webRoot": "src/app/", //The directory that contains js, ts and map files "sourceMaps": true } ] } A: I got it working with angular-cli with following launch.json { "version": "0.2.0", "configurations": [ { "name": "Launch localhost with sourcemaps", "type": "chrome", "request": "launch", "url": "http://localhost:4200/", //your application running with ng serve "sourceMaps": true, "diagnosticLogging": true, "runtimeArgs": [ "--new-window", //Open in new window "--user-data-dir=remote-profile", "--remote-debugging-port=9222" //Open in port 9222 (standard chrome debug port) ], "webRoot": "${workspaceRoot}/src/" }, { "name": "Attach with sourcemaps", "type": "chrome", "request": "attach", "port": 9222, "sourceMaps": true, "diagnosticLogging": true, "webRoot": "${workspaceRoot}/src/" } ] } A: From the readme If Code can't find the target, you can always verify that it is actually available by navigating to http://localhost:< port >/json in a browser. If you get a response with a bunch of JSON, and can find your target page in that JSON, then the target should be available to this extension. I'm guessing you are getting a Cannot GET /json but how to fix that i have no idea. A: { "version": "0.2.0", "configurations": [ { "name": "Launch Chrome against localhost, with sourcemaps", "type": "chrome", "request": "launch", "url": "http://www.xgqfrms.xyz/HTML5/Web-Front-End-Job-Interviews/absolutely-center/01.html", "sourceMaps": true, "webRoot": "${wwwroot}" }, { "name": "Attach to Chrome, with sourcemaps", "type": "chrome", "request": "attach", "port": 9222, "sourceMaps": true, "webRoot": "${wwwroot}" } ] }
doc_23537833
ERROR: type should be string, got "https://www.erlang.org/doc/man/erlang.html#term_to_binary-2\nIs there a way to decode the above compressed blob to original text using a cqlsh query?\n\nA: You can convert the blob back to an Erlang term with binary_to_term, but it cannot be done in cqlsh, it has to be done in Erlang/Elixir on the application level.\nIf you want to read from the database using a language which doesn't have binary_to_term, then you might be interested in BERT which is almost 100% compatible with Erlang Term Format and has libraries for Javascript and Ruby.\nAlternatively, any other serialisation format like Piqi, JSON, XML etc would work.\n"
doc_23537834
http://jsbin.com/enoYONAv/1/edit A: Instead of valueBinding you can use selectionBinding in your Ember.Select, to retrieve the selected model directlly instead of your id. For example: {{ view Ember.Select prompt="Gender" contentBinding="genders" optionValuePath="content.id" optionLabelPath="content.type" selectionBinding="selectedGender" }} So in you action you can do: var gender = this.get('selectedGender'); ... var hash = { name : personName, gender : gender, organization : organization }; this.savePerson(hash).then(this.saveAgentAssociation(agentAddress)); This is your updated jsbin please give a look http://jsbin.com/efeReDer/1/edit
doc_23537835
A: Something like this is what you're looking for: function MYMODULE_form_alter(&$form, &$form_state, $form_id) { $form['my_val'] = array( '#type' => 'textfield', '#title' => 'Some Text' ); $form['#submit'][] = 'MYMODULE_my_form_submit'; } function MYMODULE_my_form_submit(&$form, &$form_state) { $val = $form_state['values']['my_val']; db_insert('my_table')->fields(array('val' => $val))->execute(); } That's obviously a very basic example but it shows you how to add a submit handler to an existing form, how to add an extra field, and how to then get the data for that field in the submit handler.
doc_23537836
I would access my website on 'localhost:8080/HotelPromo' Then I got a no-ip account and got a domain hotelpromo.no-ip.biz, and in no-ip this is pointing to my IP address(which I can ping). I thought I would be able to access my web application using hotelpromo.no-ip.biz:8080/HotelPromo, but it's not working. Is it because I'm trying to use the port 8080? If yes, where and How should I change that? A: The problem may be with the port. Make sure it's open on your router. You can check if the port is open on this site: https://www.site24x7.com/port-test.html A: I don't know weather my suggested answer is going to solve this problem or not(it might), but it might be helpful to you Accessing hotelpromo.no-ip.biz instead of hotelpromo.no-ip.biz:8080/HotelPromo * *Open server.xml (ProjectExplorer|Navigator > Servers > Tomcat v7.0 Server at localhost-config - Servers > server.xml) *Accessing localhost/HotelPromo instead localhost:8080/HotelPromo change <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> to <Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443"/> *Now, accessing localhost instead localhost/HotelPromo change <Context docBase="HotelPromo" path="/HotelPromo" reloadable="true" source="org.eclipse.jst.jee.server:HotelPromo"/> to <Context docBase="HotelPromo" path="/" reloadable="true" source="org.eclipse.jst.jee.server:HotelPromo"/> NOTE: You can replace the localhost with hotelpromo.no-ip.biz when accessing through web Image Links step 1 step 2 and 3
doc_23537837
wdApp.Visible = True ' Do show Word. For Each f In fo.Files If f.Name Like "*.docx" And Left(f.Name, 2) <> "~$" Then Set wdDoc = wdApp.Documents.Open(f.Path, False, True, Format:="doc Files") tableTot = wdDoc.Tables.Count If tableTot = 0 Then MsgBox "The file" & wdDoc.Name & "does not have invoice table", vbInformation, "Invoice sheet is invalid" End If Set xlwb = Workbooks.Add Set xlsh = xlwb.Sheets(1) Set rng = xlsh.Range("A1") xlsh.Activate For Each t In wdDoc.Tables t.Range.Copy rng.Select rng.Parent.PasteSpecial Format:="Text", Link:=False, _ DisplayAsIcon:=False With rng.Resize(t.Rows.Count, t.Columns.Count) .Cells.UnMerge .Cells.ColumnWidth = 14 .Cells.RowHeight = 14 .Cells.Font.Size = 10 End With Set rng = rng.Offset(t.Rows.Count, 0) Next xlwb.SaveAs (excel_path & "\" & Replace(f.Name, ".docx", ".xlsx")) wdDoc.Close False xlwb.Close False Set t = Nothing: Set rng = Nothing: Set wdDoc = Nothing tableTot = 0 End If Next Hi, I am trying to create new excel sheets for all invoices from a given folder. But the invoice has many other text which are in small tables so it copies that too. Is there a way I can start my table based on keyword from a row (since the keyword column is also not constant) and pull my table without repeating the header in my excel file? A: You could replace: For Each t In wdDoc.Tables t.Range.Copy rng.Select with: h As Long: h = 0 For Each t In wdDoc.Tables With t If InStr(1, .Range.Text, "KeyWord", vbTextCompare) > 0 Then If h > 0 Then .Rows(1).Delete .Range.Copy h = h + 1 End If End With or, if you don't want any header rows (you post isn't clear): For Each t In wdDoc.Tables With t If InStr(1, .Range.Text, "KeyWord", vbTextCompare) > 0 Then .Rows(1).Delete .Range.Copy End If End With
doc_23537838
public static class Watermarker { public static string AddWatermark(string imgPath, string text, string outputPath) { if (!File.Exists(imgPath)) throw new FileNotFoundException(); SKBitmap bitmap = null; using (FileStream file = new FileStream(imgPath, FileMode.Open, FileAccess.Read)) { bitmap = SKBitmap.Decode(file); } using (SKPaint textPaint = new SKPaint { TextSize = bitmap.Width / 30, Typeface = SKTypeface.FromFamilyName("Arial", SKFontStyle.Bold), ColorF = SKColorF.FromHsl(0,0,40), BlendMode = SKBlendMode.Modulate }) using (SKSurface surface = SKSurface.Create(new SKImageInfo(bitmap.Width, bitmap.Height))) using (SKCanvas canvas = surface.Canvas) { canvas.DrawBitmap(bitmap, new SKPoint(0,0)); canvas.DrawText(text, (bitmap.Width / 2) - (textPaint.MeasureText(text) / 2), bitmap.Height / 2, textPaint); using (var image = surface.Snapshot()) using (var data = image.Encode(SKEncodedImageFormat.Jpeg, 80)) using (var stream = File.OpenWrite(outputPath)) data.SaveTo(stream); } return outputPath; } } It works fine with an exsisting image file from the disk. However when using this method with a file uploaded from a WebApi that is saved temporarily on the disk, the method fails when trying to decode the image into a bitmap, creating the FileStream works just fine. Here's the WebApi Controller: public class WatermarkController : UmbracoApiController { private readonly IWebHostEnvironment _env; public WatermarkController(IWebHostEnvironment env) { _env = env; } public async Task<IActionResult> AddWatermarkToImage(IFormFile file, string text) { using (Stream fileStream = new FileStream(Path.Combine(_env.WebRootPath, "upload", $"test.jpg"), FileMode.Create)) { await file.CopyToAsync(fileStream); } var uploadPath = Path.Combine(_env.WebRootPath, "upload", "tmp", $"test.jpg"); var finishedPath = Watermarker.AddWatermark(uploadPath, "Muster", Path.Combine(_env.WebRootPath, "upload", $"test.jpg")); var finishedStream = System.IO.File.Create(finishedPath); return File(finishedStream, "image/jpeg"); } } And here's the error it produces: System.ArgumentNullException: Value cannot be null. (Parameter 'buffer') at SkiaSharp.SKManagedStream.OnReadManagedStream(IntPtr buffer, IntPtr size) at SkiaSharp.SKAbstractManagedStream.ReadInternal(IntPtr s, Void* context, Void* buffer, IntPtr size) at SkiaSharp.SkiaApi.sk_codec_new_from_stream(IntPtr stream, SKCodecResult* result) at SkiaSharp.SKCodec.Create(SKStream stream, SKCodecResult& result) at SkiaSharp.SKBitmap.Decode(Stream stream) at Watermark.Watermarker.AddWatermark(String imgPath, String text, String outputPath) in C:\Users\Herrmann AG\source\repos\Watermark\Watermark\Watermarker.cs:line 16 at Umbraco10Test.Controllers.WatermarkController.AddWatermarkToImage(IFormFile file, String text) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Umbraco.Cms.Web.Common.Middleware.BasicAuthenticationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext() --- End of stack trace from previous location --- at Umbraco.Cms.Web.BackOffice.Middleware.BackOfficeExternalLoginProviderErrorMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at SixLabors.ImageSharp.Web.Middleware.ImageSharpMiddleware.Invoke(HttpContext httpContext, Boolean retry) at StackExchange.Profiling.MiniProfilerMiddleware.Invoke(HttpContext context) in C:\projects\dotnet\src\MiniProfiler.AspNetCore\MiniProfilerMiddleware.cs:line 119 at Umbraco.Cms.Web.Common.Middleware.UmbracoRequestMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) at Umbraco.Cms.Web.Common.Middleware.UmbracoRequestMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext() --- End of stack trace from previous location --- at Umbraco.Cms.Web.Common.Middleware.PreviewAuthenticationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext() --- End of stack trace from previous location --- at Umbraco.Cms.Web.Common.Middleware.UmbracoRequestLoggingMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) ```
doc_23537839
The issue is having when i change the orientation it is clipping from right side while the same thing is working correctly on all android devices. Please help me out this is my code #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIWebView *webView=[[UIWebView alloc]initWithFrame:CGRectMake(0.0, 0.0,768,1024)]; NSString *httpSource=@"http://www.mydomain.com"; NSURL *fullUrl=[NSURL URLWithString:httpSource]; NSURLRequest *httpRequest=[NSURLRequest requestWithURL:fullUrl]; webView.delegate=self; [webView loadRequest:httpRequest]; [self.view addSubview:webView]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end A: You have to set Autoresizing mask for your webView, or you can use Autolayout. - (void)viewDidLoad { [super viewDidLoad]; //Here you use the frame of Total View, irrespective of device type UIWebView *webView=[[UIWebView alloc]initWithFrame:self.view.bounds]; //Autoresizemask webView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; NSString *httpSource=@"http://www.mydomain.com"; NSURL *fullUrl=[NSURL URLWithString:httpSource]; NSURLRequest *httpRequest=[NSURLRequest requestWithURL:fullUrl]; webView.delegate=self; [webView loadRequest:httpRequest]; [self.view addSubview:webView]; } A: Try to change your UIWebView frame when device is rotate. Try bellow code - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{ [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration]; [webView setFrame: CGRectMake(0, 0, 1024, 768)]; }
doc_23537840
<zip destfile="${dist}/myzip.zip"> <zipfileset prefix="product/install" includes="docs/resources/**,docs/*.*" excludes="docs/build.bat,docs/*.xml,docs/resources/*.html"/> </zip> Now, how do I ensure that empty directories don't get included in this zipfileset. Eg: docs/resources directory only has html files, all of which I have excluded above. How do I make sure docs/resources folder doesn't get included. Should I be checking for this manually everytime? or is there an option like includeEmptyDirs="false"? A: I think there isn't an option for this in zip task, see documentation. But what you can do is to make a copy with excludes/includes, and define to exclude the empty directories and then call the zip task on the copied folder: <copy todir="tmp2" includeEmptyDirs="false"> <fileset dir="tmp1" excludes="**/*.txt"/> </copy> <zip>... Documentation of copy
doc_23537841
Thanks! A: In case someone stumbles across this, I will post the answer I found. The route I used was creating my own Walker class and using $item->object_id to get the id of the corresponding page to then retrieve the value I need with ACF get_field('field_name', id) function.
doc_23537842
#main { width: auto; height: auto; margin: auto; padding: 2px 0px 0px 0px; border: 3px solid #ccc; } The problem is that main DIV border is not extending and images are dropping out of it as shown in following screenshot: Here is the HTML scippet: <body> <div id="main"> ... <table> <tr id="image-list"> </tr> </table> ... </body> Please suggest how to alter code so that DIV border automically increase its width as per images in it? A: The issue which you are encountering - Demo And this is what will fix the issue, am doing nothing fancy, I assigned width: 100%; to the table element, and than am using table-layout: fixed; which is important here, and than just use max-width: 100%; for your img tag... Also make sure you use width for your td elements as well... Demo (Fixed issue) #main { width: auto; height: auto; margin: auto; padding: 2px 0px 0px 0px; border: 3px solid #ccc; } img { outline: 1px solid #eee; } table { width: 100%; border-collapse: collapse; table-layout: fixed; } table tr td { width: 33%; } table tr td img { max-width: 100%; } A: give : table{width:100%;} as well as #main { width: 100%; /*not auto*/ /*remaining css */ } that would solve your problem so, final css : html, body { width:100%; /* important */ height:100%; /* important */ margin:0; padding:0; } #main { width: 100%; /* changed*/ height: auto; padding: 2px 0px 0px 0px; border: 3px solid #ccc; } table{ width:100%; /* changed*/ height:auto; border-collapse: collapse; /* added and very important*/ table-layout: fixed;/* added and very important*/ } img{ width:auto; /* change as per your need */ max-width: 100%; height:auto; /* important to maintain aspect ratio of images */ } your problem solution demo A: Put this CSS in your stylesheet to fix it: #main { width: 400px /*you can give fixed value or auto value*/; height: auto; margin: auto; padding: 2px 0px 0px 0px; border: 3px solid #ccc; } #main table { width:100%; }
doc_23537843
func writeMessageWithResponse(message: String) -> [String] { self.waitingForResponse = true let runLoop = NSRunLoop.currentRunLoop() if self.response != nil { self.response?.removeAll() } writeMessage(message) // this will set self.waitingForResponse to false when a response is received while self.waitingForResponse && runLoop.runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture()) { // waiting for flag (self.waitingForResponse) to be set } return self.response! } When I use this same code with a CBCentralManager BLE connection, the main thread is blocked and does not receive the response from the connection. I've tried changing the CBCentralManager to a different queue, but I get the same results. Does anybody have an idea how to wait in a loop and still be able to receive a BLE response? I know a response is being sent, but the thread is blocked and not reading it. Using an async function with a completionHandler won't work for this use case because I need a reusable function that can issue a chain of commands that each depend on the result of the last response. A: The CBCentralManager and CBPeripheral APIs are not really designed for this. You should be using the methods provided by CBPeripheralDelegate and CBCentralManagerDelegate protocols. Initialize your central manager with a dedicated queue so that you can listen for responses to your peripherals and act on that data as appropriate.
doc_23537844
On my local machine, I was able to run server.php file from the terminal. What I wanna know that, Is there any way to create a php file act like server.php? A: You need server hosting with access to shell/bash console. This is usually unavailable on shared ones. The basic hosting that would allow you to run this is a VPS or advanced a dedicated one. But with VPS you might run into problems with hosting company if your script takes too much resources or the VPS instance is configured so that it will kill 'lingering' processes (depends on VM and configuration).
doc_23537845
Thanks, Sanjeev A: First to install @types/strophe npm install --save @types/strophe Second to download Strophe library from Strophe Site Then, You should put the framework inside /src/assets/ Then, You should add the script tag to the index.html before polyfills.js and main.js Thus <script src="assets/strophejs-1.2.14/strophe.js"></script> Last, you should put this declare statement before to use the strophe. declare var Strophe: any; It works for me! I hope to help you. Regards.
doc_23537846
x=int(input("How many columns?\n")) y=int(input("How many rows?\n")) maze=[[0]*x for n in range(y)] So with the inputs 90 and 70, there should be a total of 6300 zeroes. However, when I use while 0 in maze[:]: #stuff ...the loop ends instantly without doing anything. I've also tried while 0 in maze: #stuff It's like Python completely ignores every single one of the six thousand three hundred zeroes in the maze list. I know of a way to fix this, but it involves slowly scrolling through the range of y values for every iteration. Is there a simpler way that allows it to look at all of the sublists in one line? A: Use the any() function together with a generator expression: while any(0 in sublist for sublist in maze): # do stuff A: I think you could use numpy array to do what you want. The in operator will not find 0 in your list of lists, bu would work as intended with numpy. Minimal and verifiable example: x = [[0,0,0,1], [1,2,3,1]] >>> 0 in x False np_x = np.array(x) >>> 0 in np_x True Why 0 in x won't work? Because x holds lots of objects of type list, and an object of type list will not be equal to 0 in any occasion. The in operator will not dig in to deepest level of your list to find out if there are zeroes there or not. A: Checking if 0 exists in a 2-D matrix is always going to cost O(n*m), which is rather inefficient especially since your loop is going to iterate many times. For your purpose I would suggest that you simply use a counter and increment it whenever your operation inside the loop sets an item of 0 to a non-0 value, so that you can use something like this as a condition for the while loop: while counter < x * y: A: Since 0 is False in Boolean and all the items in maze are going to be numbers, you can use this instead: while not all(map(all, maze)): A: Numpy does not convert it to array if your sub-lists have different sizes So, you'd better unravel your list: x = [[0,0,0,1], [1,2,3,1,4,3,22,-4]] x_flat = [val for sublist in x for val in sublist] 0 in x_flat >> True
doc_23537847
Project A - .pylintrc - .git - src/ -- __init__.py -- hello.py Project B - .pylintrc - .git - src/ -- __init__.py -- there.py Project C - .pylintrc - .git - src/ -- __init__.py -- general_kenobi.py I would like to be able to use packages and modules from any of the projects. So for example, in ProjectA/src/hello.py I would like to be able to do import ProjectB.src.there Is this possible? I've spent all morning trying to put pylintrc in an enclosing folder called PROJECT. Currently my PYTHONPATH variable looks like this: /Documents/Sites/PROJECT:/Documents/Sites/PROJECT/ProjectA:/Documents/Sites/PROJECT/ProjectB However, I can't get this to work. It's important to keep the repositories separate, but doing so seems to make this kind of importing impossible. If anyone can point me in the direction of a solution I'd appreciate it.
doc_23537848
@MappedSuperclass public abstract class Base implements Serializable { @Id @Column(name="ID", nullable = false) private Integer id; public Integer getId(){return id;} public void setId(Integer id){this.id = id;} ... } @Entity @Table(name="TABLE_A") public class TableA extends Base { // Table_A wants to set an application-defined value for ID ... } @Entity @Table(name="TABLE_B") public class TableB extends Base { // How do I specify @GeneratedValue(strategy = AUTO) for ID here? ... } Is there some way to do this? I've tried including the following into TableB but hibernate objected to my having the same column twice and it seems wrong: @Override // So that we can set Generated strategy @Id @GeneratedValue(strategy = AUTO) public Integer getId() { return super.getId(); } A: In the code above, it looks like you're mixing annotations on fields (superclass) and methods (subclass). The Hibernate reference documentation recommends avoiding this, and I suspect it might be causing the problem. In my experience with Hibernate, it's safer and more flexible to annotate getter/setter methods instead of fields anyway, so I suggest sticking to that design if you can. As a solution to your problem, I recommend removing the id field from your Base superclass altogether. Instead, move that field into the subclasses, and create abstract getId() and setId() methods in your Base class. Then override/implement the getId() and setId() methods in your subclasses and annotate the getters with the desired generation strategy. Hope this helps. A: On the method in the child dont add the second @Id tag. @Override // So that we can set Generated strategy @GeneratedValue(strategy = AUTO) public Integer getId() { return super.getId(); } A: My resolution: Refactor the Base class into: @MappedSuperclass abstract class SuperBase<K> { public abstract K getId(); } @MappedSuperclass class Base<K> extends SuperBase<K> { @Id @GeneratedValue(AUTO) public K getId() { ... } } Then, you can extends from Base for most of your entity classes, and if one needs to override the @GeneratedValue, just extend from SuperBase and define it. A: If you put your annotations on the getter rather than the field, when you override the method in the subclass, the annotations placed there will be used rather than the ones in the superclass.
doc_23537849
Basically I have a huge 39x39 matrix and I need to do a Principle component analysis on them. For context each row and column represents a country and the number inside represents a how much they gave to the country in the column, lets say UK, France and Sweden 0 1 1 8 0 1 8 1 0 The 0s indicate that a country couldn't vote for itself (eg UK gave UK 0 points) and 1 indicates they could vote for them but gave 0 points, and obviously 1-n is whatever point they gave to that country (France and Sweden both gave 7 points to the UK). I have the 1s and 0s because there are countries who voted but couldn't recieve points, they are at the end of the huge matrix. I'm not sure if the format is even correct to do it, just looking for any guidance on how to go about this. Eventually I want to end up something looking similar to : I think I've installed the package correctly and tested using the iris sample codes http://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html file = open('rawresults2014eurovision.txt', 'rb') table = [row.strip().split('\t') for row in file] X = table print(X) I'm using Spyder to code it all I have so far is loading the data using this code Any help will be greatly appreciated! Thanks
doc_23537850
* *TextSelectionDelegate.copySelection *TextSelectionDelegate.cutSelection *TextSelectionDelegate.pasteText *TextSelectionDelegate.selectAll Try to either *provide an implementation, *inherit an implementation from a superclass or mixin, *mark the class as abstract, or *provide a 'noSuchMethod' implementation. class InternalSelectableMathState extends State ^^^^^^^^^^^^^^^^^^^^^^^^^^^ /C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:985:8: Context: 'TextSelectionDelegate.copySelection' is defined here. void copySelection(SelectionChangedCause cause); ^^^^^^^^^^^^^ /C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:965:8: Context: 'TextSelectionDelegate.cutSelection' is defined here. void cutSelection(SelectionChangedCause cause); ^^^^^^^^^^^^ /C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:973:16: Context: 'TextSelectionDelegate.pasteText' is defined here. Future pasteText(SelectionChangedCause cause); ^^^^^^^^^ /C:/src/flutter/packages/flutter/lib/src/services/text_input.dart:979:8: Context: 'TextSelectionDelegate.selectAll' is defined here. void selectAll(SelectionChangedCause cause); ^^^^^^^^^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_datetime_picker-1.5.1/lib/flutter_datetime_picker.dart:311:32: Warning: Operand of null-aware operation '??' has type 'Color' which excludes null. * *'Color' is from 'dart:ui'. color: theme.backgroundColor ?? Colors.white, ^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_neumorphic-3.1.0/lib/src/widget/button.dart:200:14: Error: 'AnimatedScale' is imported from both 'package:flutter/src/widgets/implicit_animations.dart' and 'package:flutter_neumorphic/src/widget/animation/animated_scale.dart'. child: AnimatedScale( ^^^^^^^^^^^^^ /C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_neumorphic-3.1.0/lib/src/widget/switch.dart:167:20: Error: 'AnimatedScale' is imported from both 'package:flutter/src/widgets/implicit_animations.dart' and 'package:flutter_neumorphic/src/widget/animation/animated_scale.dart'. child: AnimatedScale( ^^^^^^^^^^^^^ FAILURE: Build failed with an exception. * *Where: Script 'C:\src\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070 *What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'. Process 'command 'C:\src\flutter\bin\flutter.bat'' finished with non-zero exit value 1 * *Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. *Get more help at https://help.gradle.org BUILD FAILED in 2m 25s Exception: Gradle task assembleDebug failed with exit code 1 A: I faced this error once I upgraded to Flutter 2.8.1. Solution: just add flutter_math_fork: ^0.5.0 to your dependencies in pubspec.yaml to force Flutter to use the newer version of the package. Reference A: You need to upgrade your dependencies to fix this issue, so run: flutter pub upgrade
doc_23537851
var searchFields = localStorage.searchFields; if(searchFields) { $scope.fields = JSON.parse(searchFields); } else { // Make http call and populate $scope.fields } console.log(new Date().getSeconds()) If the flow gets into if condition then the DOM takes 4 seconds to render $scope.fields. But in the else condition it takes only 2 seconds. In both the cases the response is same and the response size is of 125Kb. Why is there so much delay when using localStorage? I also tried to use ngStorage but that too takes 4 seconds. A: Probably parsing JSON takes too much time. Did you tested: console.log(new Date().getSeconds()); var searchFields = localStorage.searchFields; console.log(new Date().getSeconds());
doc_23537852
How can i get the following result? (function '(a b a a b c)) => ((a a a) (b b)) A: It's quite easy. You have remove-if and remove-if-not. They work like this: (remove-if-not (lambda (x) (eq x 'a)) '(a b a a b c)) ; ==> (a a a) (remove-if (lambda (x) (eq x 'a)) '(a b a a b c)) ; ==> (b b c) Now if you have an argument and it's not nil you use the above to make the first element of the result and what list to pass to the recursion. A typical recursive function: (defun group (list) (if (endp list) nil (cons <??> (group <??>)))) There are more efficient ways to do it and you might want to make your own functions instead of relying on remove-if(-not) as an exercise.
doc_23537853
<%@ ServiceHost Language="C#" Debug="true" Service="LongTermStorage.WebService.LongTermStorageService" Factory="LongTermStorage.WebService.SteelServiceHostFactory" CodeBehind="LongTermStorageService.svc.cs" %> SteelServiceHostFactory is not being invoked and I do not get any errors. Factory: public class SteelServiceHostFactory : ServiceHostFactory { protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { return new SteelServiceHost(SteelWcfApplication.InstanceProvider, serviceType, baseAddresses); } } A: It works if I switch from Cassini (development web server) to IIS.
doc_23537854
I am using JSF 1.2 and I want to conditionally set the color of the items in my drop down list. In other words, I have a collection of items that, along with a key and a value, also have a boolean property, warning, that is dynamically set by user action. I want the drop down to show all of the items, but those whose warning property is set to true should be displayed in red. I assume I have to extend the SelectItem class to add in the boolean property. How do I then conditionally set the color of the font of those items whose warning property is set to true in my JSP pages? Thanks in advance A: Unfortunately, the JSF standard implementation of the HTML <select> element, the h:selectOneMenu doesn't provide facilities to set style classes on each individual <option> element. You can however create a custom renderer which does that and configure your webapp to use that renderer instead. Basically you just need to add an extra attribute to the component wherein you pass some separated string with all option style classes which are to be applied on the options repeatedly. The renderer should then take care about picking this attribute and applying the style classes on the option elements accordingly. You can find code examples and explanations in this article. You can then end up with something like: <h:form> <h:selectOneMenu value="#{myBean.selectedItem}"> <f:attribute name="optionClasses" value="option1, option2" /> <f:selectItems value="#{myBean.selectItems}" /> </h:selectOneMenu> <h:commandButton value="submit" action="#{myBean.submit}" /> </h:form> You can of course also generate and return the value from the bean: <f:attribute name="optionClasses" value="#{myBean.optionClasses}" />
doc_23537855
"D" "B" "C" "F" "G" "A" where each letter corresponds to an id in a related model. When I add the association into the TreeNode model to form the relation, the tree stops iterating and I only get the first set of results (D > B > C) and not (D > B > F) or (D > G > A) as I wanted. Here is the output when I add the relations: {"label":"Fred","language":"en","id":"D","datatype":"number"} {"label":"is friends with","language":"en","id":"B","datatype":"text"} {"label":"Violet","language":"en","id":"C","datatype":"text"} I'm new to backbone relational and not sure if i'm doing this correctly. Here is the sample code (i paired it down as much as possible and noted the problem area with HERE IS THE PROBLEM) Thanks in advance!!! <!DOCTYPE html> <html> <head> <title>Relational Graph</title> <meta charset="utf-8" /> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.1/underscore-min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script> <script src="js/backbone.marionette.js"></script> <script src="js/backbone.relational.js"></script> </head> <body> <div id="model"></div> <script> $(document).ready(function(){ MainApp = new Backbone.Marionette.Application(); MainApp.addRegions({treeRegion: "#model"}); MainApp.addInitializer(function(options){ var trunk = things.search({id: "D"}).first(); var tree = new TreeNodeCollection(graphify(options.relationships, trunk)); var treeView = new TreeRoot({collection: tree}); this.treeRegion.show(treeView); }); TreeNode = Backbone.RelationalModel.extend({ initialize: function(){ var nodes = this.get("nodes"); if (nodes){ this.nodes = new TreeNodeCollection(nodes); this.unset("nodes"); } }, render: function(){ var that = this; TemplateManager.get(this.template, function(template){ var html = $(template).tmpl(); that.$el.html(html); }); return this; } // !!! HERE IS THE PROBLEM - when I add this line, it stops looping through the tree :( //, relations: [{type: Backbone.HasOne, key: 'id', relatedModel: "Thing"}] }); TreeNodeCollection = Backbone.Collection.extend({model: TreeNode}); TreeView = Backbone.Marionette.CompositeView.extend({ template: "#node-template", tagName: "ul", initialize: function(){ this.collection = this.model.nodes; }, appendHtml: function(collectionView, itemView){ collectionView.$("li:first").append(itemView.el); } }); TreeRoot = Backbone.Marionette.CollectionView.extend({itemView: TreeView}); Thing = Backbone.RelationalModel.extend(); Things = Backbone.Collection.extend({ model: Thing, search: function(opts){ return new Things(this.where(opts)); } }); Relationship = Backbone.RelationalModel.extend({ relations: [ {type: Backbone.HasOne, key: 's', relatedModel: Thing}, {type: Backbone.HasOne, key: 'p', relatedModel: Thing}, {type: Backbone.HasOne, key: 'o', relatedModel: Thing} ] }); Relationships = Backbone.Collection.extend({ model: Relationship, search: function(opts){ return new Relationships(this.where(opts)); } }); things = new Things([ new Thing({label: 'Sam', language: 'en', id: 'A', datatype: 'text'}), new Thing({label: 'Fred', language: 'en', id: 'D', datatype: 'number'}), new Thing({label: 'Jake', language: 'en', id: 'E', datatype: 'text'}), new Thing({label: 'Sally', language: 'en', id: 'F', datatype: 'number'}), new Thing({label: 'is friends with', language: 'en', id: 'B', datatype: 'text'}), new Thing({label: 'is working with', language: 'en', id: 'G', datatype: 'text'}), new Thing({label: 'Violet', language: 'en', id: 'C', datatype: 'text'}) ]); relationships = new Relationships([ new Relationship({s: "A", p: "B", o: "C"}), new Relationship({s: "A", p: "B", o: "D"}), new Relationship({s: "A", p: "B", o: "E"}), new Relationship({s: "A", p: "B", o: "F"}), new Relationship({s: "D", p: "B", o: "C"}), new Relationship({s: "D", p: "B", o: "F"}), new Relationship({s: "A", p: "G", o: "F"}), new Relationship({s: "D", p: "G", o: "A"}) ]); MainApp.start({things: things, relationships: relationships}); function arrUnique(field, arr){ var all = []; arr.each(function(item){ all.push(item.get(field).get('id')); }); return _.uniq(all); } function graphify(arr, obj){ var graphNew = []; var uniqueSubjects = arrUnique("s", arr.search({s: obj})); for (var i=0; i<uniqueSubjects.length; i++){ var subject = uniqueSubjects[i]; var newSubject = {id: subject}; var subNodes = []; var uniquePredicates = arrUnique("p", arr.search({s: obj})); for (var j=0; j<uniquePredicates.length; j++){ var predicate = uniquePredicates[j]; var newPredicate = {id: predicate}; var relatedObjects = []; arr.each(function(o){ if (o.get("s").get("id") == subject && o.get("p").get("id") == predicate){ relatedObjects.push({id: o.get("o").get("id")}); } }); newPredicate.nodes = relatedObjects; subNodes.push(newPredicate); } newSubject.nodes = subNodes; graphNew.push(newSubject); } return graphNew; } }); </script> <script type="text/template" id="node-template"> <li><label><%= JSON.stringify(id) %></label></li> </script> </body> </html>
doc_23537856
<controls:SplitButton Grid.Row="3" HorizontalContentAlignment="Left" HorizontalAlignment="Center" VerticalContentAlignment="Center" Width="120" DisplayMemberPath="Title" VerticalAlignment="Top"> <controls:SplitButton.Items> <Label>1</Label> <Label>2</Label> </controls:SplitButton.Items> </controls:SplitButton> However, I'm not able to see the popup window. Any ideas? A: You should use the ItemsSource and an enumerable and don't specify a DisplayMemberPath. <controls:SplitButton HorizontalContentAlignment="Left" HorizontalAlignment="Center" VerticalContentAlignment="Center" Width="120" VerticalAlignment="Top"> <controls:SplitButton.ItemsSource> <x:Array Type="system:String"> <system:String>Label 1</system:String> <system:String>Another one</system:String> <system:String>Works now</system:String> </x:Array> </controls:SplitButton.ItemsSource> </controls:SplitButton> Hope that works. A: That's because you define your items source twice: ItemsSource="{Binding}" and <controls:SplitButton.Items> <Label>1</Label> <Label>2</Label> </controls:SplitButton.Items> Just remove the ItemsSource attribute. <controls:SplitButton Grid.Row="3" HorizontalContentAlignment="Left" HorizontalAlignment="Center" VerticalContentAlignment="Center" Width="120" VerticalAlignment="Top"> <controls:SplitButton.Items> <Label>1</Label> <Label>2</Label> </controls:SplitButton.Items> </controls:SplitButton>
doc_23537857
Is it possible to use the google map API to get cities within a certain radius from a location so that I can reduce the number of times I have to query on my database before I get the results I want? I have previously done a radius search by using the locations stored on my database and I'm thinking that if it is not possible to get the cities within radius with just the use of the google map API, My alternative solution would be to get all locations (stored in my database) within a certain radius by filtering them via lat and lng and get all distinct localities of the returned locations. However, results can be inaccurate. Because there can be datas stored up in my database that might not show up if it is not within radius from the location specified during radius search, despite being in the same city/locality, which is actually the filter that I want.
doc_23537858
Select Case When transfer.trf_type = 'c' then 'Transfer to own card' When transfer.trf_type = 'o' then 'Transfer to own account' When transfer.trf_type = 'I' then 'Transfer to a domestic bank' When transfer.trf_type = 'b' then 'Transfer to another AIIB Customer' End As Type , Count(transfer.trf_type) As total, Sum (transfer.amount*currency.rate) AS totalSum From transfer Inner Join currency on transfer.currency = currency.currency Where transfer.to_card IS null Group By Rollup(Type) It gives me the result set with the sum but with an empty space. I want the rollup row to appear with a specific alias , eg :"Total fund transfers".How can i achieve this? Here is my query result, I need to add total in the last row thank you A: Try this with grpSum as (Select Case When transfer.trf_type = 'c' then 'Transfer to own card' When transfer.trf_type = 'o' then 'Transfer to own account' When transfer.trf_type = 'I' then 'Transfer to a domestic bank' When transfer.trf_type = 'b' then 'Transfer to another AIIB Customer' End As Type , Count(transfer.trf_type) As total, Sum (transfer.amount*currency.rate) AS totalSum From transfer Inner Join currency on transfer.currency = currency.currency Where transfer.to_card IS null Group By ROLLUP(Type)) select COALESCE(Type,'Total found transfers'),total,totalSum from grpSum
doc_23537859
$scope.errormessage = response.message; $scope.myform.myinput.$setValidity('errormessage', false); This works but the message is not being animated - it appears instantly. If I use ng-required the message is animated. Any ideas what I'm doing wrong or if there is some other way to approach this problem? Angular material demo for messages is located here: https://material.angularjs.org/latest/demo/input Thank you.
doc_23537860
var externalDataRetrievedFromServerAreas = ""; while..... { externalDataRetrievedFromServerAreas.push({COLUMNNAME: document.getElementById('table1').rows[i].cells[j].innerHTML}); } and here i want to have column name instead of 'COLUMNNAME', for example like this: document.getElementById('table1').rows[0].cells[j].innerHTML but i have an error, doing this way. Can someone please help? A: var externalDataRetrievedFromServerAreas = []; while..... { const COLUMNNAME = document.getElementById('table1').rows[0].cells[j].innerHTML externalDataRetrievedFromServerAreas.push({ [COLUMNNAME]: document.getElementById('table1').rows[i].cells[j].innerHTML}); }
doc_23537861
I've tested on two devices. One went to sleep (idle for 7hours), and this device didn't receive any notifications. Second device did get notifications, but It was forced not to sleep ( I used app for this ). Well I'm just assuming that this is it, because there is no other explanation. Because I used AlarmManager. Here is my brief code. public void setAlarm(boolean isCanceled) { Intent intent = new Intent(NOTIFICATION_TIME); if(!isCanceled) { pendingIntent = PendingIntent.getBroadcast(activityContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime()+TWELVEHOURS, TWELVEHOURS, pendingIntent); } else { pendingIntent = PendingIntent.getBroadcast(activityContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); } } "isCanceled", cancels the alarm only if you make changes in settings. So this is not it. Is this implemented right, and it should launch my broadcast receiver, or.. ? A: Use following code, PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "bbbb"); wl.acquire(); This will wake your CPU and then perform the code that you want to execute when Alarm fires. You need to device following permission in your AndroidManifest.xml file <uses-permission android:name="android.permission.WAKE_LOCK" />
doc_23537862
React: Setting State for Deeply Nested Objects w/ Hooks What seems to work like a charm there, will somehow break for me when doing the following: I have a table populated with items from an array defined like so: const [items, setItems] = useState([ { selected: false, title: 'Item 1', status: 'new' }, { selected: false, title: 'Item 2', status: 'used' }, ]); When selecting an item from that list this function gets called to update selected variable for the object with the index i like so: const select = (e) => { const i = e.target.getAttribute('data-index'); setItems((prevState) => { prevState[i].selected = !prevState[i].selected; return [...prevState]; }); }; This will work exactly once. If I trigger select a second time or any time after that return [...prevState] somehow keeps returning the state unchanged. (selected stays true forever). I can't solve this. items is attached to a component List like so: <List items={items} /> and inside List (shortened code): {items.map((item, i) => { return ( <tr className="list-table-tr"> {hasSelector ? ( <td className="list-table-td-selector"> {item.selected ? ( <div data-index={i} className="global-selector-selected" onClick={select} ></div> ) : ( <div data-index={i} className="global-selector-unselected" onClick={select} ></div> )} </td> ) : null} A: You're breaking one of the primary rules of React state: You're modifying a state object directly, rather than making a copy. To correctly do the update, you'd do this: const select = (e) => { const i = e.target.getAttribute('data-index'); setItems((prevState) => { // Copy the array (your code was doing that) const update = [...prevState]; const item = update[i]; // Copy the object (your code wasn't doing that) and update its // `selected` property update[i] = {...item, selected: !item.selected}; return update; }); }; Note how both the array and the object are copied, rather than just the array.
doc_23537863
XmlSerializer serializer = new XmlSerializer(typeof(Notchs)); XDocument xmlDoc = XDocument.Parse(dataInXmlFile); Notchs notchs = (Notchs)serializer.Deserialize(xmlDoc.CreateReader()); var query = from l in xmlDoc.Descendants("Category") select new Notch { name = (string)l.Attribute("name").Value, Titles = l.Element("Articles").Elements("article") .Select(s => s.Attribute("title").ToString()) .ToList(), Image = l.Element("Articles").Elements("article").Elements("thumb_image").Elements("image") .Select(x => x.Attribute("url").ToString()).ToList() }; foreach (var result in query) { Console.WriteLine(result.name); foreach (var detail in result.Titles) { Console.WriteLine(detail); } } NotchsList.ItemsSource = query.ToList(); I tried this code but i got the output like below ..but I want the details and images are list. name System.Collection.Generic.List'1[string.system] name System.Collection.Generic.List'1[string.system] A: I think your Titles = l.Element("Articles").Elements("article") .Select(s => s.Attribute("title").ToString()) .ToList() is returning an IEnumerable<IEnumerable<String>>. You may want to do a .SelectMany instead of .Select.
doc_23537864
I have added an extra field to my serializer, called distance (distance is equal the distance in miles between 2 different locations) I am looking to return the Business Object order my this new field, would it be possible? or am I taking the wrong path for this soluction? Down here you have my Serializer and ModelViewSet Serializer class BusinessesSerializer(serializers.ModelSerializer): distance = serializers.SerializerMethodField('get_location') class Meta: model= Businesses fields = ('id', 'address_first_line', 'address_second_line', 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance') def get_location(self, business): ip_info = requests.get('https://api64.ipify.org?format=json').json() ip_address = ip_info["ip"] response = requests.get(f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json() latitude = response.get("latitude") longitude = response.get("longitude") first = (float(latitude), float(longitude)) second = (business.lat, business.long) distance = great_circle(first, second).miles return distance ModelViewSet class BusinessesViewSet(ModelViewSet): serializer_class = BusinessesSerializer queryset = Businesses.objects.all() A: You cannot filter in your view against a SerializerMethodField (or even object property) as Django filters operate at the database level. Also, you cannot use annotate() in this case as it does not accept python function. One thing tyou could do would be to retrieve all entries, then filtering them using "raw python". The best solution is probably to just add a new field in your model where you store this value, and you can easily filter / order against it whenever you want. A: You should probably move your external API calls to fetch the distance field outside of your serializer as calling APIs is a side effect and should not be made in a serializer. Its purpose is to simply serialize data, not to fetch it from the web. If you're performing these calls on a big data set, your code is going to execute slow and possibly get throttled by the ipify. A possible solution would be to move away from ModelViewSet to a regular APIView and perform a custom request. class BusinessesAPIView(APIView): def get(self, request): # Get IP info once ip_info = requests.get('https://api64.ipify.org?format=json').json() ip_address = ip_info["ip"] response = requests.get( f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json() latitude = response.get("latitude") longitude = response.get("longitude") first = (float(latitude), float(longitude)) # Calculate distances for all businesses and pass them as a context to our serializer businesses = Businesses.objects.all() distances = {} for business in businesses: second = (business.lat, business.long) distance = great_circle(first, second).miles distances[business.id] = distance # Sort by distance businesses_processed = BusinessesSerializer(businesses, many=True, context={'distances': distances}).data businesses_processed.sort(key=lambda x: x['distance']) return Response({'businesses': businesses_processed}) class BusinessesSerializer(serializers.ModelSerializer): distance = serializers.SerializerMethodField() class Meta: model= Businesses fields = ('id', 'address_first_line', 'address_second_line', 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance') # Get distance by business id from context we passed from our APIView def get_distance(self, business): return self.context['distances'][business.id]
doc_23537865
However, I've run into a problem. public class App { public static void main(String[] args) throws Exception { int n = 3; int k = 2; int result = combRecursion(n, k); System.out.println(result); } private static int combRecursion(int n, int k) { if (k == 0) { return 1; } else { return (combRecursion(n - 1, k - 1) + combRecursion(n - 1, k)); } } Output: many repetitions of this line: at App.combRecursion(App.java:14) A: It's possible to pick k items from the set of n items only if n is greater or equal to k. You need to cut off fruitless branches of recursion spawn by the call combRecursion(n - 1, k) which doesn't reduce the number of item in the sample. When you need to create a recursive method, it should always contain two parts: * *Base case - that represents a set of edge-cases, trivial scenarios for which the result is known in advance. If the recursive method hits the base case (parameters passed to the method match one of the conditions of the base case), recursion terminates. In for this task, the base case will represent a situation when the source list was discovered completely and position is equal to its size (invalid index). *Recursive case - a part of a solution where recursive calls are made and where the main logic resides. Your recursive case is correct: it spawns two recursive branches of execution (one will "pick" the current item, the second will "reject" it). But in the base case, you've missed the scenario mentioned above, we need to address these situations: * *n isn't large enough (k > n), so that is not possible to fetch k item. And the return value will be 0 (or instead of returning a value, you might throw an exception). *k == 0 result should be 1 (it's always possible to take 0 items, and there's only one way to do it - don't pick anything). *When k == n - there's only one way to construct a combination, as @akuzminykh has pointed out. And the return value will be 1 Note that because your goal is to get familiar with the recursion (I'm pretty sure that you're doing it as an exercise) there's no need to mimic the mathematical formula in your solution, use pure logic. Here is how you can implement it: private static int combRecursion(int n, int k) { if (k > n) return 0; // base case - impossible to construct a combination if (n == k || k == 0) return 1; // base case - a combination was found // recursive case return combRecursion(n - 1, k - 1) + combRecursion(n - 1, k); } main() - demo public static void main(String[] args) { System.out.println(combRecursion(3, 2)); System.out.println(combRecursion(5, 2)); } Output 3 // pick 2 item from the set of 3 items 10 // pick 2 item from the set of 5 items A: Your base case ought to include both n == k || k == 0 for "n choose k" to be implemented correctly. That way, both calls will eventually terminate (even though your current implementation is rather inefficient as it has exponential runtime). A better implementation would use the formula n!/k!/(n-k)! or the multiplicative formula to run in linear time: int factorial(int n) { int res = 1; for (; n > 1; n--) { res *= n; } return res } int choose(int n, int k) { return factorial(n)/factorial(k)/factorial(n-k); } further optimizing this is left as an exercise to the reader (hint: a single for loop suffices).
doc_23537866
Any help on the subject would be much appreciated. package fplforum; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; public class RegistrationForm extends JFrame implements ActionListener { public RegistrationPanel panel; public JButton submit, cancel; public boolean done; public Object UITools; public RegistrationForm() { JPanel main = new JPanel(); main.setLayout(new BorderLayout()); main.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10)); JLabel label = new JLabel("Java CoG Kit Registration"); label.setFont(Font.decode("Arial-bold-18")); label.setBorder(BorderFactory.createEmptyBorder(5, 10, 20, 10)); main.add(label, BorderLayout.NORTH); panel = new RegistrationPanel(); //panel.getReregister().addActionListener(this); //main.add(panel, BorderLayout.CENTER); setTitle("Java CoG Kit Registration Form"); JPanel buttons = new JPanel(); buttons.setLayout(new FlowLayout()); submit = new JButton("Submit"); submit.addActionListener(this); buttons.add(submit); //submit.setEnabled(panel.getReregister().isSelected()); cancel = new JButton("Cancel"); cancel.addActionListener(this); buttons.add(cancel); main.add(buttons, BorderLayout.SOUTH); getContentPane().add(main); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == submit) { try { panel.submit(false); JOptionPane.showMessageDialog(this, "Thank you for registering the Java CoG Kit", "Registration successful", JOptionPane.INFORMATION_MESSAGE); done(); } catch (IOException e1) { JOptionPane.showMessageDialog(this, "Could not submit registration information: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == cancel) { done(); } else { //must be the don't send switch submit.setEnabled(panel.getReregister().isSelected()); } } private void done() { done = true; synchronized (this) { notify(); } } public void run() { setSize(500, 380); UITools.left(null, this); setVisible(true); try { synchronized (this) { while (!done) { wait(); } } } catch (InterruptedException e) { JOptionPane.showMessageDialog(this, "The main thread was interrupted", "Error", JOptionPane.ERROR_MESSAGE); } setVisible(false); dispose(); } public static void main(String[] args) { //RegistrationFrame frame = new RegistrationFrame(); //frame.run(); //System.exit(0); } private static class RegistrationPanel { public RegistrationPanel() { } private Object getReregister() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private void submit(boolean b) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } } It will compile but nothing happens, how do I fix it? A: If it compiles and executes, then it works. It does not work as you want it to work, but it surely works. You have an empty main method, so it will not do anything. This is your main method: public static void main(String[] args) { //RegistrationFrame frame = new RegistrationFrame(); //frame.run(); //System.exit(0); } All the lines are commented out, so there are no operations to execute. Take out the // at the start of your lines to have some action. Also, as far as I know, you do not have a RegistrationFrame class, you might want to instantiate RegistrationForm instead. Also, why do you call System.exit(0) ?
doc_23537867
* *term_id *name *slug Term_taxonomy table: * *term_taxonomy_id *term_id *description My Term model: public function TermTaxonomy(){ return $this->hasOne('TermTaxonomy'); } My TermTaxonomy model: public function Term(){ return $this->belongsTo('Term'); } My Categories controller: public function update($id){ echo "$id"; // echo success echo $data['name']; // it should update name field in term table echo $data['slug']; // it should update slug field in term table echo $data['TermTaxonomy']['description']; // it should update description field in termtaxonomy table } how i can update one to one relationships ? maybe with push() Thanks, sorry i am new in laravel. A: as Jarek Tkaczyk comment in this question Laravel eloquent: Update A Model And its Relationships There is no other way, as Eloquent currently doesn't know what relations are on the model until you call them as dynamic property, load with load method, eager load etc. (push works only with loaded relations that are present in model's relations array) so i use this code. $Term = Term::with('TermTaxonomy')->find($id); $Term->name = $data['name']; $Term->slug = $data['slug']; $Term->TermTaxonomy->taxonomy = 'category'; $Term->TermTaxonomy->description = $data['TermTaxonomy']['description']; $Term->push(); and it works. Term and TermTaxonomy table is updated, but if change push() to save() it only update Term table even TermTaxonomy relationships already loaded with Eager load Term::with('TermTaxonomy') Thanks for all :D A: You can use Eloquent's update() method: https://laravel.com/docs/5.4/eloquent#updates $Term = Term::with('TermTaxonomy')->find($id); $Term->name = $data['name']; $Term->slug = $data['slug']; // Save The Term first $Term->save(); // Now update the relation $Term->TermTaxonomy->update([ 'taxonomy' => 'category', 'description' => $data['TermTaxonomy']['description'] ]);
doc_23537868
I even tried to use intersection observer but it doesn't work const section = document.querySelector(".parallax"); const img = document.querySelectorAll("img"); const title = document.querySelector(".title") const observer = new IntersectionObserver((entries) =>{ entries.forEach((entry) =>{ if(entry.isIntersecting){ window.addEventListener("scroll", ()=>{ console.log(window.scrollY); img[0].style.top = `-${window.scrollY/12}px`; img[1].style.top = `-${window.scrollY /13}px`; img[2].style.top = `-${window.scrollY / 14}px`; img[3].style.top = `-${window.scrollY / 15}px`; img[4].style.top = `-${window.scrollY / 16}px`; img[5].style.top = `-${window.scrollY / 17}px`; img[6].style.top = `-${window.scrollY / 18}px`; title.style.marginRight = `${window.scrollY}px`; }) } }) }, { threshold:0 }) observer.observe(section); A: There's a post by w3schools.com on this topic. Here is a very simple snippet showing what you would need to do to achieve this: .parallax { /* The image used */ background-image: url("https://cdn4.iconfinder.com/data/icons/social-media-logos-6/512/121-css3-512.png"); /* Set a specific height */ min-height: 500px; /* Create the parallax scrolling effect */ background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover; } <!DOCTYPE html> <html> <body> <p>Scroll Up and Down this page to see the parallax scrolling effect.</p> <div class="parallax"></div> <div style="height:1000px;background-color:lightblue;font-size:36px"> The image stays in place! </div> </body> </html>
doc_23537869
thanks you so much in advance for your help. public class Books extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.books); addTextView("Hello World"); } public void addTextView(String text) { ScrollView viewport = (ScrollView)findViewById(R.id.books); TextView textview= (TextView)new TextView(this); textview.setText(text); //textview.setLayoutParams(new ScrollView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); viewport.addView(textview, new ScrollView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } public void addButton(String text) { ScrollView scrollview = (ScrollView)findViewById(R.id.books); Button btnTag = (Button)new Button(Books.this); btnTag.setLayoutParams(new ScrollView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); btnTag.setText(text); scrollview.addView(btnTag); } } A: ScrollViews can only have one child, typically a LinearLayout. When you call scrollview.addView(blah blah) you're adding more children to the ScrollView which is not allowed. See here for documentation about ScrollView. -- On a side note, when posting questions on StackOverflow about errors you encounter, please state: * *the error you encounter (in Android, this'll be found in the LogCat view) *your expected results (what you were trying to do) *the relevant code (in this case, you should include your layout XML file too - while the ScrollView error is definitely one of the errors you'll get, it might not be the first one that needs fixing, in order to move forward). It'll help everyone, including people in future who stumble upon this question.
doc_23537870
The Query that works: SELECT Customers.sBarcode, CAST(FLOOR(CAST(Tickets.dtCreated AS FLOAT)) AS DATETIME) AS dtCreatedDate, COUNT(Customers.sBarcode) AS [Number of Scans], MAX(Customers.sLastName) AS LastName FROM Tickets INNER JOIN Customers ON Tickets.lCustomerID = Customers.lCustomerID WHERE (Tickets.dtCreated BETWEEN @startdate AND @enddate) AND (Tickets.dblTotal <= 0) GROUP BY Customers.sBarcode, CAST(FLOOR(CAST(Tickets.dtCreated AS FLOAT)) AS DATETIME) HAVING (COUNT(*) > 1) ORDER BY dtCreatedDate The Output is: sBarcode dtcreated Date Number of Scans slastname 1234 1/4/2013 12:00:00 AM 2 Jimbo 1/5/2013 12:00:00 AM 3 Jimbo2 1578 1/6/2013 12:00:00 AM 3 Jimbo3 My current Query with the subquery SELECT customers.sbarcode, Max(customers.slastname) AS LastName, Cast(Floor(Cast(tickets.dtcreated AS FLOAT)) AS DATETIME) AS dtCreatedDate, Count(customers.sbarcode) AS [Number of Scans], Stuff ((SELECT ', ' + RIGHT(CONVERT(VARCHAR, dtcreated, 100), 7) AS [text()] FROM tickets AS sub WHERE ( lcustomerid = tickets.lcustomerid ) AND ( dtcreated BETWEEN Cast(Floor(Cast(tickets.dtcreated AS FLOAT)) AS DATETIME ) AND Cast(Floor(Cast(tickets.dtcreated AS FLOAT )) AS DATETIME ) + '23:59:59' ) AND ( dbltotal <= '0' ) FOR xml path('')), 1, 1, '') AS [Times Scanned] FROM tickets INNER JOIN customers ON tickets.lcustomerid = customers.lcustomerid WHERE ( tickets.dtcreated BETWEEN @startdate AND @enddate ) AND ( tickets.dbltotal <= 0 ) GROUP BY customers.sbarcode, Cast(Floor(Cast(tickets.dtcreated AS FLOAT)) AS DATETIME), tickets.lcustomerid HAVING ( Count(*) > 1 ) ORDER BY dtcreateddate The Current output (notice the record without a barcode is missing) is: sBarcode dtcreated Date Number of Scans slastname Times Scanned 1234 1/4/2013 12:00:00 AM 2 Jimbo 12:00PM, 1:00PM 1578 1/6/2013 12:00:00 AM 3 Jimbo3 03:05PM, 1:34PM A: UPDATE: Based on our "chat" it seems that customerid is not the unique field but barcode is, even though customer id is the primary key. Therefore, in order to not GROUP BY customer id in the subquery you need to join to a second customers table in there in order to actually join on barcode. Try this: SELECT customers.sbarcode, Max(customers.slastname) AS LastName, Cast(Floor(Cast(tickets.dtcreated AS FLOAT)) AS DATETIME) AS dtCreatedDate, Count(customers.sbarcode) AS [Number of Scans], Stuff ((SELECT ', ' + RIGHT(CONVERT(VARCHAR, dtcreated, 100), 7) AS [text()] FROM tickets AS subticket inner join customers as subcustomers on subcustomers.lcustomerid = subticket.lcustomerid WHERE ( subcustomers.sbarcode = customers.sbarcode ) AND ( subticket.dtcreated BETWEEN Cast(Floor(Cast(tickets.dtcreated AS FLOAT)) AS DATETIME ) AND Cast(Floor(Cast(tickets.dtcreated AS FLOAT )) AS DATETIME ) + '23:59:59' ) AND ( dbltotal <= '0' ) FOR xml path('')), 1, 1, '') AS [Times Scanned] FROM tickets INNER JOIN customers ON tickets.lcustomerid = customers.lcustomerid WHERE ( tickets.dtcreated BETWEEN @startdate AND @enddate ) AND ( tickets.dbltotal <= 0 ) GROUP BY customers.sbarcode, Cast(Floor(Cast(tickets.dtcreated AS FLOAT)) AS DATETIME) HAVING ( Count(*) > 1 ) ORDER BY dtcreateddate A: I can't directly solve your problem because I don't understand your data model or what you are trying to accomplish with this query. However, I can give you some advice on how to solve the problem yourself. First do you understand exactly what you are trying to accomplish and how the tables fit together? If so move on to the next step, if not, get this knowledge first, you cannot do complex queries without this understanding. Next break up what you are trying to accomplish in little steps and make sure you have each covered before moving to the rest. So in your case you seem to be missing some customers. Start with a new query (I'm pretty sure this one has more than one problem). So start with the join and the where clauses. I suspect you may need to start with customers and left join to tickets (which would move the where conditions to the left joins as they are on tickets). This will get you all the customers whether they have tickets or not. If that isn't what you want, then work with the jon and the where clasues (and use select * while you are trying to figure things out) until you are returning the exact set of customer records you need. The reason why you use select * at this stage is to see what in the data may be causeing the problem you are having. That may tell you how to fix. Usually I start with a the join and then add in the where clasues one at a time until I know I am getting the right inital set of records. If you have multiple joins, do them one at time to know when you suddenly start have more or less records than you would expect. Then go into the more complex parts. Add each in one at a time and check the results. If you suddenly go from 10 records to 5 or 15, then you have probably hit a problem. When you work one step at a time and run into a problem, you know exactly what caused the problem making it much easier to find and fix. Group BY is important to understand thoroughly. You must have every non-aggregated field in the group by or it will not work. Think of this as law like the law of gravity. It is not something you can change. However it can be worked around through the use of derived tables or CTEs. Please read up on those a bit if you don't know what they are, they are very useful techniques when you get into complex stuff and you shoud understand them thoroughly. I suspect you will need to use the derived table approach here to group on only the things you need and then join that derived table to the rest of teh query to get the ontehr fields. I'll show a simple example: select t1.table1id , t1.field1 , t1.field2 , a.field3 , a.MostRecentDate From table1 t1 JOIN (select t1.table1id, t2.field3, max (datefield) as MostRecentDate from table1 t1 JOin Table2 t2 on t1.table1id = t2.table1id Where t2.field4 = 'test' group by t1.table1id,t2.field3) a ON a.table1id = t1.table1id Hope this approach helps you solve this problem.
doc_23537871
1. CRUD of user management - add & login users -forget pass (intranet) -3 wrong attempt login - locked account (the admin is the one to unlock) -user - can view accounts only -admin- edit accounts -ID is system generated -have high security -XML Database (once opened, show data) He said that we should integrate MVP model. I am not familiar with backend programming. Hoping you can help me. Thank you ! A: In my opinion, PHP is the language more easily to learn. With it you can use many good frameworks and well documented: Zend Framework, Symphony, CodeIgniter, WordPress (have much ready thing in WordPress, mainly relationship of users, login, users list, user management) ...
doc_23537872
I tried manually with Sublime Text to write "CAFE BABE" and save it with Hex encoding. It works. I tried different fwrite and fprintf but can't find the good way to do it. FILE *dest = fopen("HelloWorld.class", "wb"); fwrite("CAFEBABE", sizeof(unsigned int), 4, dest); I also saw some fprintf with 02x... fprintf(dest, "%02x", "0xCA"); I really don't understand how to write directly with hex encoding... Thanks you so much for any help. A: Hex is a text representation of numbers. You don't want to write hex; you want to write the actual numbers. To produce the four bytes CA FE BA BE, you can use any of the following: const unsigned char* bytes = (const unsigned char*)"\xCA\xFE\xBA\xBE"; unsigned char bytes[] = "\xCA\xFE\xBA\xBE"; unsigned char bytes[] = { 0xCA, 0xFE, 0xBA, 0xBE }; As for outputting them, fprintf is not ideal. While you could use the %s format specifier if you made sure the data was NUL-terminated, you couldn't actually output a NUL using it. On the other hand, fwrite is intended to write arbitrary bytes.
doc_23537873
System: windows 7 Cmake version: 3.16.0-rc1 Boost version: boost_1_71_0. And boost is installed through .exe file. Gcc version: 4.8.1(rev5, Built by MinGW-W64 project) Visual studio: vs 2015 When I run cmake .. in build dir, no error occurs. The output is: The C compiler identification is MSVC 19.0.24215.1 The CXX compiler identification is MSVC 19.0.24215.1 Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe -- works Detecting C compiler ABI info Detecting C compiler ABI info - done Detecting C compile features Detecting C compile features - done Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe -- works Detecting CXX compiler ABI info Detecting CXX compiler ABI info - done Detecting CXX compile features Detecting CXX compile features - done Found Boost: C:/local/boost_1_71_0 (found version "1.71.0") Boost_Found Success! Found OpenCV: C:/Users/gph/opencv/binaries (found version "3.4.5") Found OpenCV: C:/Users/gph/opencv/binaries (found version "3.4.5") found components: core highgui imgproc videoio Configuring done But I want to use minGW to compile, so When I rum cmake -G "MinGW Makefiles", error occured saying "Could NOT find Boost (missing: Boost_INCLUDE_DIR)". The output is: The C compiler identification is GNU 4.8.1 The CXX compiler identification is GNU 4.8.1 Check for working C compiler: C:/MinGW/bin/gcc.exe Check for working C compiler: C:/MinGW/bin/gcc.exe -- works Detecting C compiler ABI info Detecting C compiler ABI info - done Detecting C compile features Detecting C compile features - done Check for working CXX compiler: C:/MinGW/bin/g++.exe Check for working CXX compiler: C:/MinGW/bin/g++.exe -- works Detecting CXX compiler ABI info Detecting CXX compiler ABI info - done Detecting CXX compile features Detecting CXX compile features - done CMake Error at C:/Users/gph/cmake/share/cmake-3.16/Modules/FindPackageHandleStandardArgs.cmake:146 (message): Could NOT find Boost (missing: Boost_INCLUDE_DIR) Call Stack (most recent call first): C:/Users/gph/cmake/share/cmake-3.16/Modules/FindPackageHandleStandardArgs.cmake:393 (_FPHSA_FAILURE_MESSAGE) C:/Users/gph/cmake/share/cmake-3.16/Modules/FindBoost.cmake:2162 (find_package_handle_standard_args) CMakeLists.txt:34 (find_package) Configuring incomplete, errors occurred! See also "C:/Users/gph/Desktop/libvibe++/build/CMakeFiles/CMakeOutput.log". How to solve the error when running cmake -G "MinGW Makefiles"? Thanks guys! A: I solved this by adding sentence set(BOOST_ROOT C:/local/boost_1_71_0) before find_package(Boost REQUIRED) LOL... But I still wonder why I need to add this. A: You can also set variables BOOST_ROOT during the creation of the cmake project (or CMake options in CLion and other IDE). For example: mkdir buildtest; cd buildtest cmake -DBOOST_ROOT=/you_path_to_boost/boost .. cmake --build . -- -j 4 A: I had a similar problem on Linux/Manjaro. Make sure you have boost installed, more specifically the boost development headers. I had the boost runtime libraries installed but not the headers. I installed those sudo pacman -S boost and it fixed the problem for me. A: After I solved this problem, thanks to ToughMind here, these problems occurred to me: _Boost_COMPONENT_DEPENDENCIES and _Boost_MISSING_DEPENDENCIES. What helped me was to update to the newest cmake verison and I got the answer from here: CMake finds Boost but the imported targets not available for Boost version
doc_23537874
- common - webapp1 - webapp2 and then use relative paths to import shared code. This worked fine for simple cases where it was just javascript/typescript or a view component. However, once I started moving over coder that uses other public npm packages (axios) it worked at first but if you delete the node modules folder which I assume deletes the npm cache it started breaking with the error below. VITE v3.0.4 ready in 428 ms ➜ Local: http://localhost:8081/ ➜ Network: http://192.168.254.3:8081/ Failed to resolve import "axios" from "../common/infrastructure/http/index.js". Does the file exist? 3:56:43 PM [vite] Internal server error: Failed to resolve import "axios" from "../common/infrastructure/http/index.js". Does the file exist? Plugin: vite:import-analysis File: /Users/ryan/code/analyzer-app/common/infrastructure/http/index.js 1 | import axios from "axios"; | ^ 2 | import * as Sentry from "@sentry/vue"; 3 | at formatError (file:///Users/ryan/code/analyzer-app/webapp/node_modules/vite/dist/node/chunks/dep-71eb12cb.js:35035:46) at TransformContext.error (file:///Users/ryan/code/analyzer-app/webapp/node_modules/vite/dist/node/chunks/dep-71eb12cb.js:35031:19) at normalizeUrl (file:///Users/ryan/code/analyzer-app/webapp/node_modules/vite/dist/node/chunks/dep-71eb12cb.js:40181:33) at async TransformContext.transform (file:///Users/ryan/code/analyzer-app/webapp/node_modules/vite/dist/node/chunks/dep-71eb12cb.js:40315:47) at async Object.transform (file:///Users/ryan/code/analyzer-app/webapp/node_modules/vite/dist/node/chunks/dep-71eb12cb.js:35284:30) at async loadAndTransform (file:///Users/ryan/code/analyzer-app/webapp/node_modules/vite/dist/node/chunks/dep-71eb12cb.js:39812:29) Shared Code // common/infrastructure/http/index.js import axios from "axios"; import * as Sentry from "@sentry/vue"; let handleErrorMessage; let handleSuccessMessage; // removed for brevity const configure = ({ onErrorMessage, onSuccessMessage} = {}) => { handleErrorMessage = onErrorMessage; handleSuccessMessage = onSuccessMessage; } export default { // removed for brevity configure }; ** Consuming Code ** // common/infrastructure/http/index.js // removed for brevity import { configure as configureDoAsync } from "../../common/infrastructure/doAsync"; // removed for brevity // Configure doAsync for error and success message handling configureDoAsync({ onErrorMessage: message => store.dispatch("toastMessage/notifyError", { message }, { root: true }), onSuccessMessage: message => store.dispatch("toastMessage/notifySuccess", { message: message }, { root: true }) }); // removed for brevity
doc_23537875
* *Is there any head first WebGL tutorial online ? *Should I learn GLSL ? *The code to draw something with WebGL is too complex, is there any way to reduce the code lines? A: There are interactive tutorials here: http://www.webglacademy.com I think it's cool because you can change your code, test it again, and it is step by step. You can also check webgl lesson on http://www.learningwebgl.com Then, when I want to search some help about a specific webgl API/GLSL command, I search on http://www.opengl.org/sdk/docs/manglsl/ A: This is the best tutorial I have found so far! http://my2iu.blogspot.in/2011/11/webgl-pre-tutorial-part-2-drawing-2d.html A: * *http://learningwebgl.com/blog/?p=11 (dead link as of Nov 2018, backup: https://web.archive.org/web/20180615095219/http://learningwebgl.com/blog/?p=11) *Yes, I could recommend Light House 3D: http://www.lighthouse3d.com/tutorials/glsl-core-tutorial/ *It's not that complex, just focus on the code written on Learning webGL. I wouldn't recommend working with some other library/engine at the start. Learn basics and later use libraries to speed up your coding. Learning webGL is great place to start, probably best. Don't hesitate to read from as many resources you can. Opera developer, Mozilla Hacks, Light House 3D, Scratch a Pixel, Aerotwist (http://www.aerotwist.com/tutorials/an-introduction-to-shaders-part-1/ more shaders)... It's very difficult at the beginning, but later you'll get the grasp of the pipeline and way of thinking. It takes time (1-2 months to learn only basics), but be persistent. Hope this helps. A: * *Probably, but I don't know it. *Yes; in order to render anything with WebGL, you need a shader. GLSL is the language of shaders, so if you want to render anything, you'll need to use GLSL. *Yes; use a library like Three.js.
doc_23537876
However I have this weird issue that I don't understand. When I cancel an ongoing HTTP request on the client (I use Insomnia) side, the server will exit with logs like this: 2017/05/15 11:25:24 context canceled Process finished with exit code 1 Can someone help me explain why the server exits itself ? I use pressly/chi to implement my http handlers. A: I figured it out. Apparently, in one place, I call log.Fatalf() when there's an error, causing the app to exit when the context canceled. Furthermore, my lack of understanding of how context cancelling works makes it difficult to make debug the problem.
doc_23537877
A: I was able to solve the problem as follows. Uninstall VirtualBox via the command line (sudo apt-get remove virtualbox and sudo apt-get remove virtualbox-guest-utils) and reinstall VirtualBox with the sudo apt-get install virtualbox command. Voilà, Genymotion started working normally. I also noticed that VirtualBox was installed with a different icon.
doc_23537878
[name] John Smith [address] 4260 Russell Road Kent, USA [e-mail] john.smith@something.com [familymember] - Lisa Smith - Randy Smith - Lauren Smith [contact] +1876543 Notice that all the field names is between [ and ]. the value sometimes only one line, sometimes multiple lines. Some even have blank lines. Question: how do I convert the data above into mysl, or even csv? I have tried using excel to import the data, but it cannot handle the multiple line values without creating new rows for each lines.
doc_23537879
Same process i.e deploying the war file from Glassfish 4.1 (opened from Netbeans 8) worked fine on our local machine on which the project is developed (in Netbeans). Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.glassfish.webservices.WSServletContextListener. Please see server.log for more details. Server log:: java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException: javax.servlet.ServletException: com.sun.enterprise.container.common.spi.util.InjectionException: Error creating managed object for class: class org.glassfish.webservices.WSServletContextListener at com.sun.enterprise.web.WebApplication.start(WebApplication.java:168) at org.glassfish.internal.data.EngineRef.start(EngineRef.java:122) at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:291) at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:352) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:500) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:356) at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565) at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:356) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722) at org.glassfish.admin.rest.utils.ResourceUtil.runCommand(ResourceUtil.java:253) at org.glassfish.admin.rest.utils.ResourceUtil.runCommand(ResourceUtil.java:231) at org.glassfish.admin.rest.utils.ResourceUtil.runCommand(ResourceUtil.java:275) at org.glassfish.admin.rest.resources.TemplateListOfResource.createResource(TemplateListOfResource.java:133) 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:606) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:387) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:331) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:103) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:254) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1028) at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:365) at org.glassfish.admin.rest.adapter.RestAdapter$2.service(RestAdapter.java:316) at org.glassfish.admin.rest.adapter.RestAdapter.service(RestAdapter.java:179) at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545) at java.lang.Thread.run(Thread.java:745) A: I'm having a similar problem. However I'm attempting to deploy to AIX 6.1, which may be the source of the problem for me. In prior versions of Glassfish, Oracle released a separate version of Glassfish to run on AIX machines due to the differences between IBM Java and Oracle Java. Since there is not a separate version of Glassfish 4.1 for AIX, I suspect that my efforts to get it to operate on AIX will be in vain. In my case I've been experimenting with the jaxws-rt-2.2.6-6.jar and rt.jar (from Oracle Java 1.7.0_21) and seeing if adding them to the classpath within Glassfish 4.1 will allow me to generate some other error, if not fix the problem. Having a real tough time determining if Glassfish is able to see those libraries (I assume no since I keep getting the same error). Anyhow, if you're still having the same problem, you might want to state what OS you were developing on and what OS you're attempting to deploy to. That might shed more light on the problem.
doc_23537880
The problem w/ how I have it is, sometimes this is causing multiple 301 redirects. I'd really like each rule to apply in turn and then if neccessary redirect once to the final url. For example a url might need to be converted to lowercase and have a slash added. Or may need to be lowecase and change from index.html to a directory. Any ideas how I can do this? Thanks very much. The rules are below: #LOWERCASE URLS For Directories, aspx, html files RedirectRule ^/(.*[A-Z].*(/|\.html|\.aspx))$ /#L$1#E [R=301] #ADD SLASH TO DIRECTORIES #--------------------------------------------- #Perm Redirect If: #Starts w/ Forward Slash #Match Any Characters Except (. or ?) 1 or more times #End w/ someting besides a dot, ?, or slash #If So, Perm Redirect captured piece W/ Slash At End and at front RedirectRule ^/([^.?]+[^.?/])$ /$1/ [I,R=301] #CHANGE INDEX.HTML REQUESTS TO DIRECTORY REQUESTS #--------------------------------------------- RedirectRule ^/(.*)/index\.html$ /$1/ [I,R=301] A: There's an excellent answer to this question on the IIRF Forums. A: I only see the chance to combine the latter two: RedirectRule ^/([^A-Z?]*[A-Z].*(/|\.html|\.aspx))$ /#L$1#E [R=301] RedirectRule ^/([^.?]+?[^.?/])(/index\.html)?$ /$1/ [I,R=301] A: unfortunately, the response on the IIRF forums does not solve the multiple redirect issue. each rule still causes its own redirect. using a RewriteRule [without a redirect flag] instead of a RedirectRule throws an error in IIRF status: # rule: # force HTTPS [disable on dev site until port 80 and port 443 served by same site] # after rewrite continue with remaining tests RewriteCond %{HTTPS} off RewriteRule ^/(.*)$ https://www.example.com/$1 [NC] error: C:\Inetpub\wwwroot\example-com\www\Iirf.ini(26): WARNING: Rewriting to a fully-qualified URL. Probably wrong. You may want RedirectRule or ProxyPass. I'd anticipated that IIRF would have taken the results of this rule and sent it back through the IIRF rules again, pickup up any other URL modifications along the way, and ultimately sending a single 301 redirect back to the browser with the final result of all rewrites. The [N] flag does this in mod_rewrite, from what I understand.
doc_23537881
tuples( [ (a,b,[1,3,5,7]), (a,b,[9,11,13,15]), (a,b,[17,19,21,23]), (c,d,[0,2,4,6]), (c,d,[8,10,12,14]), (c,d,[16,18,20,22]), (e,f,[100,200,300,400]), (e,f,[500,600,700,800]), (e,f,[900,1000,1100,1200]) ] ). How to group them so it becomes: [ (a,b,[1,3,5,7,9,11,13,15,17,19,21,23]), (c,d,[0,2,4,6,8,10,12,14,16,18,20,22]), (e,f,[100,200,300,400,500,600,700,800,900,1000,1100,1200]) ] As we can see, we grouped the (a,b) (c,d) (e,f) and concatenated their respective lists. thank you for the help. A: How about this somewhat SQL-ish way: Define a predicate to access data in the original deep and nasty datastructure (which uses conjunction (_,_) to create what looks like n-tuples but are actually "nearly" lists, except at the final position of the backbone). On backtracking, it will pull out the individual records one by one and present the information therein in the head variables: some_tuple(V,W,Values) :- tuples(Tuples), member((V,W,Values), Tuples). And then collect using a 2-level bagof/3 call. solution(Bag) :- bagof((V,W,FlatBagForVW), % will backtrack over V,W SubBag^(bagof(L,some_tuple(V,W,L),BagForVW), % collect lists for a given V,W flatten(BagForVW,FlatBagForVW)), % flatten it Bag). % what we want Done! If you are in SWI-Prolog, first tell the toplevel printer to not elide long lists so much: ?- set_prolog_flag(answer_write_options,[max_depth(100)]). Then: ?- solution(Bag). Bag = [(a,b,[1,3,5,7,9,11,13,15,17,19,21,23]), (c,d,[0,2,4,6,8,10,12,14,16,18,20,22]), (e,f,[100,200,300,400,500,600,700,800,900,1000,1100,1200])]. A: A variation using foldl/4 and then library(yall): 'Grouping list elements based on values in list'(Gs) :- tuples(Ts), foldl([(X,Y,L),V0,V1]>>( ( append(N,[(X,Y,L0)|M],V0) -> append(L0,L,L1) ; N=V0, L1=L ), append(N,[(X,Y,L1)|M],V1) ) ,Ts,[],Gs). a day after... There is a bug going unnoticed, namely M remains unbound where a pair of keys (that is, X,Y in a tuple) is not present in V0 (have attempted to keep the variables naming coherent to the docs for foldl/4). A possible correction, that illustrates a single unification call (=/2) to perform multiple 'assignments' at once: ... foldl([(X,Y,L),V0,V1]>>( ( append(N,[(X,Y,L0)|M],V0) -> append(L0,L,L1) ; (N,M,L1)=(V0,[],L1) ), append(N,[(X,Y,L1)|M],V1) ... Still, it's not clear to me why the bug didn't materialized... for instance, here it's clearly visible... ?- append([1,2,3],[4,5,6|_],R). R = [1, 2, 3, 4, 5, 6|_19156]. another way... library(solution_sequences) is a recent addition to SWI-Prolog arsenal, providing more 'SQL like' constructs, for instance group_by/4: by_group_by(Gs) :- tuples(Ts), findall((X,Y,All_xy), ( group_by([X,Y],L,member((X,Y,L),Ts),Lt), append(Lt,All_xy) ),Gs). The documentation is too much terse, but overall, the library is worth a try. There are some examples posted in SWI-Prolog discourse group, but I find the data used there boring and difficult to understand. Note: I used the syntax [X,Y] for the free variables, to make clear the 'shape' of this important specification is unrelated to the pattern. A: group([],L,L). group([(A,B,L)|T],Acc,Out):- ( append(L1,[(A,B,LL)|L2], Acc) -> append(LL,L,LLL), append(L1,[(A,B,LLL)|L2], NewAcc), group(T,NewAcc,Out) ; append(Acc,[(A,B,L)],NewAcc), group(T,NewAcc,Out) ). ?- tuples(L), group(L,[],G). G = [ (a,b,[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]), (c,d,[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]), (e,f,[100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]) ], L = [ (a,b,[1, 3, 5, 7]), (a,b,[9, 11, 13, 15]), (a,b,[17, 19, 21, 23]), (c,d,[0, 2, 4, 6]), (c,d,[8, 10, 12, 14]), (c,d,[16, 18, 20, 22]), (e,f,[100, 200, 300, 400]), (e,f,[500, 600, 700, 800]), (e,f,[900, 1000, 1100, 1200]) ]. Basically I'm stripping an element from the (tuple) list ([(A,B,L)|T]) and look if I got a similar entry within my bag-list (2nd argument, append(L1,[(A,B,LL)|L2], Acc)). I use append/3 to do so because it can be used to find an element and at the same time dividing the original list into the list before and after the found element. If I found an entry in the baglist, I append the two number lists (L and LL) to a new one (LLL) and exchange the values within the bag-list. Then I call the predicate again with the rest list and the altered bag-list. If no element fits, I just add the element to the bag-list (as last element, append(Acc,[(A,B,L)],Acc2)) and call the predicate again. So each time I call the predicate group/3 it's first argument loses an element. Until there is no element left (group([],L,L).), in this case I state my bag-list is my ouput. After playing a bit around with group_by/4 and/or bagof/3 as suggested by Guy coder, and using a variant of Davids "extraction" predicate here is another solution: one_tuple(V,W,Value) :- tuples(Tuples), member((V,W,Values), Tuples), member(Value, Values). ?- findall((A,B,Cs), bagof(C, one_tuple(A, B, C), Cs), O). O = [(a,b,[1,3,5,7,9,11,13,15,17,19,21,23]), (c,d,[0,2,4,6,8,10,12,14,16,18,20,22]), (e,f,[100,200,300,400,500,600,700,800,900,1000,1100,1200])]. A: First we need to be able to find the list of unique A,B pairings in the list of tuples: foo(X,A,B) :- setof( p(A,B), C^member( (A,B,C), X ), T), member( p(A,B), T). /* 48 ?- tuples(_X), foo(_X,A,B). A = a, B = b ; A = c, B = d ; A = e, B = f. */ Next we collect the tuples for each pair of the A and B values: bar(X,A,B,G) :- foo(X,A,B), % for each unique (A,B,_) in X findall( C, % find all Cs such that (A,B,C) is in X member( (A,B,C), X), CS), append( CS,G). % and append them together /* 66 ?- tuples(_X), bar(_X,A,B,G). A = a, B = b, G = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23] ; A = c, B = d, G = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22] ; A = e, B = f, G = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200].*/ So that the grouping is done with groups(X,GS):- findall( (A,B,G), bar(X,A,B,G), GS). /* 68 ?- tuples(_X), groups(_X, GS). GS = [(a, b, [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]), (c, d, [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]), (e, f, [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200])]. */ update: from David Tonhofer's answer, we see that it can be done with just one nested bagof call, solution( Sol ) :- tuples(TS), bagof( (A,B,FLS), % (* collect (A,B,FLS) for each (A,B) *) LS^( % (* such that (A,B,L) is in TS *) bagof( L, member((A,B,L), TS), LS ), flatten( LS, FLS) ), % (* with the lists LS flattened *) Sol ). The outer bagof's goal predicate (i.e. the inner bagof call) is automatically backtracking to produce its LS result for each distinct pair of the A,B values, automagically achieving the same effect as we had "manually", in this answer.
doc_23537882
A: When hosting npm packages via git, npm also needs to know which transfer protocol to use to transfer the package files from the repo to the client. For this the following options exist: ssh, https, http, file (see https://docs.npmjs.com/cli/install). The creators of npm decided to place this information in the protocol name separating the information with a + symbol so it becomes more schematic. So when npm install iterates over your dependencies and sees a dependency with git+ssh it knows that it will connect to the repo via ssh and then use your local git binaries to checkout the project files locally. I guess they could have also named the protocol gitwithssh as in gitwithssh://git@github.com/xxx.git but git+ssh looks just more concise and logically separated, thus easier to parse via a regex. Here is the part in the npm source code that is actually responsible for splitting the protocol information into the type (= git) and the actual protocol (e.g. ssh): https://github.com/npm/npm-package-arg/blob/v7.0.0/npa.js#L221 I only use git@github.com/xxx.git. You cannot use this format to register a package as dependency with npm. Try executing npm i git@github.com/xxx.git – it won't work. This format can only be used e.g. via git clone. However, you can use this format when prefixing it with the ssh protocol: ssh://git@github.com/xxx.git. This is actually the "normalized" form of "git+ssh" which is used by npm behind the curtains (see also how https://github.com/npm/normalize-git-url transforms your git+ssh://... into ssh://git@...). A: From an NPM perspective this similar to any other remote setup. Many dependency managers support using Git over SSH. Under the hood, this drives Git to connect over SSH. The end result is NPM clones the repository and installs it into your node_modules directory. When Git communicates with a remote repository it launches one of two programs using SSH: either git-upload-pack or git-receive-pack. The repository is given as an option to these commands. SSH is used a tunneling mechanism to issue commands to these remote programs using the pkt-line protocol. More details about the protocol can be found in the Git source.
doc_23537883
[['Service eka godaak hondai', 'සේවාව ගොඩාක් හොඳයි '], ['Kama rasai ', 'කෑම රසයි '], ['Godak fresh and maarama rasaii, perfect. ', 'ඉතා රසවත් හා ඉතා රසවත්, පරිපූර්ණයි'], ['place eka piliwelai, clean , kama godaak rasai', 'ස්ථානය පිළිවෙලට, පිරිසිදුයි, කෑම හරිම රසයි']] when I try this following code singlish_tokenizer = create_tokenizer(dataset[:,0]) This error below is shown TypeError Traceback (most recent call last) <ipython-input-138-74d68e010cad> in <module> 3 # a[:stop] # items from the beginning through stop-1 4 #a[:] means a copy of the whole array 5 singlish_tokenizer = create_tokenizer(dataset[:,0]) TypeError: list indices must be integers or slices, not tuple this is the create_tokenizer method def create_tokenizer(lines): tokenizer = Tokenizer() tokenizer.fit_on_texts(lines) return tokenizer Can anyone please help me in this issue. I tried different solutions but nothing worked. I am stuck with this code.
doc_23537884
I have the following model. class Post(Base): __tablename__ = "post" id = Column(Integer, primary_key=True, index=True) title = Column(String) author = Column(String) content = Column(String) time_created = Column(DateTime(timezone=True), server_default=func.now()) with this schema class PostSchema(SQLAlchemyObjectType): class Meta: model = Post Problem How to to get the graphql schema definition in form of string like this """ type Post{ id: ID title: string! author: String! content: String! time_created: Int! } """ * *I tried this, but there is not type_defs option. *graphene.Field(PostModel).type_defs A: One option you can use is to introspect your schema not just the object type. Suppose you have a graphene schema called schema, from graphene_sqlalchemy import SQLAlchemyObjectType class schema(SQLAlchemyObjectType): class Meta: model = MyModel you can do something like: schema_dict = schema.introspect() This will return a dict version of your schema and the types that you want can be found here: types = schema_dict["__schema"]["types"] Unfortunately, this returns a list of all object types so you might need to process it to narrow down what you want with something like: list(filter(lambda types: types['name'] == 'PostSchema', types)) alternative way def make_schemas(model): d = """ """ for i, key in model.__table__.columns.items(): x = str(key.type.python_type) x = x.replace("<class '", '') x = x.replace("'>", '') x = x.title() if x in ['Str', 'Datetime.Datetime']: x = 'String' if x == 'Bool': x = 'Boolean' d += f""" {i}: {x} """ y = f""" type {model.__tablename__.title()} {{ {d} }} """ return y
doc_23537885
version bash :4.2.45 #!/bin/bash echo "ca va (y/n)?" read answer if [ "$answer" == "y" ];then echo "yes" else echo "no" fi this is the error ca va (y/n)? y test.sh: 13: [: y: unexpected operator no thank a lot A: That script works fine as a Bash script. However, the error you're getting is because you're running it as: sh test.sh rather than: ./test.sh which means it's being run in /bin/sh mode. As explained in [ :Unexpected operator in shell programming, sh only accepts = and not ==. A: I tried it on my system, and it seems to work fine. It could be because Bash 4.x is fussy about syntax (I'm on Bash 3.2), or it could be that you aren't specifying Bash when you run it: $ sh test.sh On many systems, this would run something like the Bourne shell. (On mine, it runs Bash in POSIX mode, so it still works). The == is not a valid test in Bourne shell (although it works in Bash and Kornshells). Using a single equals (=) instead of a double equals will solve this issue. You can also try using the standard line breaks instead of the modern way lines are broken in if statements. Try this: #!/bin/bash echo "ca va (y/n)?" read answer if [ "$answer" = "y" ] then echo "yes" else echo "no" fi
doc_23537886
I got Ubuntu 14.04, Apache/2.4.7, ruby 2.2.5p319 and some Web Apllication installed on. When I try to go to application page, i see the exception and a trace in my browser. Web application could not be started cannot load such file -- bundler/setup (LoadError) /usr/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require' /usr/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require' /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:245:in `block in run_load_path_setup_code' /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:348:in `running_bundler' /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:243:in `run_load_path_setup_code' /usr/share/passenger/helper-scripts/rack-preloader.rb:100:in `preload_app' /usr/share/passenger/helper-scripts/rack-preloader.rb:158:in `' /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `' /usr/share/passenger/helper-scripts/rack-preloader.rb:28:in Also environmet variables: APACHE_PID_FILE = /var/run/apache2/apache2.pid SHELL = /bin/bash APACHE_RUN_USER = www-data PASSENGER_DEBUG_DIR = /tmp/passenger.spawn-debug.XXXXybOMMs USER = appuser APACHE_LOG_DIR = /var/log/apache2 PATH = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PWD = /var/app APACHE_RUN_GROUP = www-data LANG = C NODE_PATH = /usr/share/passenger/node SHLVL = 0 HOME = /home/appuser LOGNAME = appuser APACHE_LOCK_DIR = /var/lock/apache2 APACHE_RUN_DIR = /var/run/apache2 IN_PASSENGER = 1 PYTHONUNBUFFERED = 1 RAILS_ENV = production RACK_ENV = production WSGI_ENV = production NODE_ENV = production PASSENGER_APP_ENV = production SERVER_PROTOCOL = HTTP/1.1 SERVER_ADDR = x.x.x.x REMOTE_ADDR = y.y.y.y REQUEST_URI = / SSL_TLS_SNI = myaddr.com HTTPS = on SERVER_PORT = 443 SERVER_NAME = myaddr.com SERVER_SOFTWARE = Apache/2.4.7 (Ubuntu) SERVER_ADMIN = youremail@example.com REMOTE_PORT = 51589 DOCUMENT_ROOT = /var/myapp/public QUERY_STRING = REQUEST_METHOD = GET RUBY_VERSION = 2.2.6 RUBY_PLATFORM = i386-linux-gnu RUBY_ENGINE = ruby RubyGems version = 2.4.5.2 It seems that some parts of Ruby's previous version still has influence to the WebApp, but I can't find where to correct it. Thanks.
doc_23537887
Is there any code that could do this? I've seen it done before. Example follows. This is the menu This is where the page content starts fading This is the rest of the page content This is the footer I've tried to do this by simply using a fixed div, but it is solid, and I want the text to fade. A: I'm not sure if I understood your question correctly. The idea would be to put a div underneath the menu and make it's background gradient from white at top to transparent at bottom. And no jQuery is needed for this. Here is a sampe: http://jsfiddle.net/QL63w/1/
doc_23537888
Input: d.shape Output: (19381,) Input: d[0].shape Output: (100,6) Input: d[0][0].shape Output: (6,) Input: if any(i.shape != (100,6) for i in d): print(True) else: print(False) Output: False What am I missing? I have tried using d.shape = (19381,100,6) But I get a "cannot reshape array of size 19381 into shape (19381, 100,6) Thanks, Ian A: The problem was occurring because of the way that I was creating the numpy arrays. I was attempting to do something like l1 = [1,2,3,4] l2 = [5,6,7,8] l = zip(l1, l2) np.random.shuffle(l) l1, l2 = np.array(zip(*l)) Once I changed the code to l1, l2 = zip(*l) l1 = np.array(l1) l2 = np.array(l2) The shape output was as expected.
doc_23537889
Android Lint anywhere in my Eclipse IDE (Preferences -> Android). Are there any additional things to be done? I need some help. Thanks. A: If there is no menu point in eclipse (Window -> Run Android Lint), chances are that you only upgraded your Android SDK and not the eclipse plugin. In this case go to Help -> Check for updates. Eclipse should tell you that there are new updates available. Just click next to install them. Then restart eclipse when prompted. A: Ensure you installed it firstly, by checking pulgins installed. Then right click the project, go android tools, there is a "Run Lint"
doc_23537890
public int h, w; public Form1() { InitializeComponent(); textBox1.Text = "Image Path here ..."; } public void button1_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Select an Image"; dlg.Filter = "jpg files (*.jpg)|*.jpg"; if (DialogResult.OK == dlg.ShowDialog()) { this.pictureBox1.Image = new Bitmap(dlg.FileName); Bitmap img = new Bitmap(dlg.FileName); int w = img.Width; int h = img.Height; pictureBox1.Height = h; pictureBox1.Width = w; textBox1.Text = dlg.FileName; } } public void button2_Click(object sender, EventArgs e) { MessageBox.Show("Height is- " + h.ToString() + " Width is- " + w.ToString(), "Height & Width"); } A: In your button1_Click you are not assigning to the h and w of the class, but to local variables. Just change int w = img.Width; int h = img.Height; to w = img.Width; h = img.Height; and it should work, if I understand correctly what you are trying to achieve.
doc_23537891
I would like to get an Amazon-EC2 GPU machine running with rpud (or another R GPU package), either a cg1.4xlarge or g2.2xlarge as those are the only two GPU machines Amazon(AWS) has. This post How to run a GPU instance using Amazon EC2 Panel? helped me realize that I couldn't just change my rstudio-server machine to a gpu machine as I was using an incorrect AMI. Started out with this AMI from Amazon CentOS 6 (x86_64) - with Updates So I decided I had to build my own and started following the directions here http://www.r-tutor.com/gpu-computing/rpud-installation. As well as http://www.louisaslett.com/Talks/GPU_Programming_Basics_Getting_Started/Handout.pdf (Louis Aslett is the same guy who has an amazing demo of using rstudio-server on an ec2 (http://www.louisaslett.com/RStudio_AMI/). Both of those end up leading you to here: http://docs.nvidia.com/cuda/cuda-getting-started-guide-for-linux/index.html#package-manager-installation, so you can get the CUDA toolkit (which seems to be a necessity for GPU computing). Some of the AWS machines already have a Cuda toolkit installed, however I figured I would follow the directions on my first try (even though they are installed, sometimes the versioning of stuff hasn't been the same as some of the tutorials I've found). So I follow those directions to a T and I end up getting a few errors like nvidia-settings-319.37-30.fc18.x86_64 (cuda) Requires: libgdk-x11-2.0.so.0()(64bit) when I try to run the examples with $ cuda-install-samples-5.5.sh <dir>. So I download all of those required packages. I try again and end up with rpud errors (will detail those later). This machine is Ubuntu-12.04 So of course I think, someone must have already built an AMI for this and find someone who did it with python. I might just end up using python anyway because of more speed bonuses, but at this point I want to get it working with R. Here: http://vasir.net/blog/opencl/installing-cuda-opencl-pyopencl-on-aws-ec2 is the link to the AMI/ instructions on how to build it from scratch if you want to. Of course, then you have to install R, which defaults to R2.14, so following this great post How to install R version 3 to get R.3.1.0 running because rpud requires R>=R.2.8. Following the directions from the r-tutor site listed above (either from simply using install.packages('rpud') or the $ R CMD INSTALL rpud_<version>.tar.gz or by using the directions http://cran.r-project.org/web/packages/rpud/INSTALL, I get this message: * installing *source* package ‘rpud’ ... checking "environment variable CUDA_HOME"... "CUDA_HOME not set; using default /usr/local/cuda" checking for /usr/local/cuda/bin/nvcc... yes "nvcc found" checking "whether this is the 64 bit linux version of CUDA"... checking for /usr/local/cuda/lib64/libcublas.so... yes "yes -- using /usr/local/cuda/lib64 for CUDA libs" "using -I/usr/share/R/include for R header files" "using -Wl,--export-dynamic -fopenmp -L/usr/lib/R/lib -lR -lpcre -llzma -lbz2 -lrt -ldl -lm for R shared libraries" configure: creating ./config.status config.status: creating src/Makefile ** libs ** arch - /usr/local/cuda/bin/nvcc -c -I/usr/local/cuda/include -Xcompiler "-I/usr/share/R/include -fpic" rpud.cu -o rpud.o /usr/local/cuda/bin/nvcc -c -I/usr/local/cuda/include -Xcompiler "-I/usr/share/R/include -fpic" rpudist.cu -o rpudist.o rpudist.cu(159): warning: use of "=" where "==" may have been intended rpudist.cu(159): warning: use of "=" where "==" may have been intended ptxas /tmp/tmpxft_000006af_00000000-5_rpudist.ptx, line 904; warning : Double is not supported. Demoting to float /usr/local/cuda/bin/nvcc -shared -Xlinker "-Wl,--export-dynamic -fopenmp -L/usr/lib/R/lib -lR -lpcre -llzma -lbz2 -lrt -ldl -lm -Wl,-rpath,/usr/local/cuda/lib64" -L/usr/local/cuda/lib64 -lcublas -lcuda rpud.o rpudist.o -o rpud.so /usr/bin/ld: unrecognized option '-Wl' /usr/bin/ld: use the --help option for usage information collect2: ld returned 1 exit status make: *** [rpud.so] Error 1 ERROR: compilation failed for package ‘rpud’ * removing ‘/home/ubuntu/R/x86_64-pc-linux-gnu-library/3.1’/rpud’ So I try to find out what -Wl is doing which leads me to another dead-end here http://www.talkstats.com/showthread.php/43438-installing-rpud-got-unrecognized-option-Wl. A friend of mine pointed me to http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html for more information on -Wl, but changing the source-code of rpud or finding/installing the correct linker might be just outside my abilities. With regard to the comment: ubuntu@ip-xx-xx-xx:~$ dpkg -l | grep nvidia ii nvidia-current 319.37-0ubuntu1 NVIDIA binary Xorg driver, kernel module and VDPAU library ii nvidia-current-dev 319.37-0ubuntu1 NVIDIA binary Xorg driver development files ii nvidia-modprobe 319.37-0ubuntu1 Load the NVIDIA kernel driver and create device files ii nvidia-settings 319.37-0ubuntu1 Tool for configuring the NVIDIA graphics driver I am hoping someone is using rpud on ubuntu and could provide any further guidance on how to get rpud working. Thanks in advance for your time. If you need any more information feel free to comment. EDIT 4/8/2014 Following the python walkthrough, http://enja.org/category/tutorial/advcl/, I am able to get a simple program running on the GPU, the python/part1 example runs perfectly. So I know that the NVIDIA drivers are working properly, at least for python. However I have yet to locate an R walk-through that will even get the packages loaded correctly. Further findings from Python exploration: I have 2 devices on my current machine that both work. Choose device(s): [0] <pyopencl.Device 'Tesla M2050' on 'NVIDIA CUDA' at 0x2806460> [1] <pyopencl.Device 'Tesla M2050' on 'NVIDIA CUDA' at 0x28064b0> *Those could be seen by running any of the python scripts from the python GPU tutorial Edit 4/9/2014 Knowing that Python was interfacing with OpenCL made me think, couldn't R do the same? Obviously someone else had thought the same thing and built the package 'OpenCL' So I ran install.packages('OpenCL') and IT WORKED. Then running some of the sample code from http://cran.r-project.org/web/packages/OpenCL/OpenCL.pdf ALSO WORKED. At this point, the only question I'm left with is, has anyone else succeeded with interfacing the GPU with R and if so, how did they do it? I will post my step-by-step as an answer, but would love to see other ways. A: Walkthrough: Step 1: Lookup the AMI-ID ami-87377cee (the one Erik Hazzard built at http://vasir.net/blog/opencl/installing-cuda-opencl-pyopencl-on-aws-ec2) in AWS in the Community AMIs and start up a cg1.4xlarge machine. Step 2: From command line run: sudo apt-get update then sudo apt-get install r-base-core ** this will install R2.14.1. If you want to use the latest R version, I would use the guide here: How to install R version 3 Step 3: run R, then use install.packages('OpenCL') to install OpenCL Step 4: Have fun learning OpenCL!! It is really that easy to get it working. Writing the code in a way that OpenCL can use is a bit tricky, but once you get the hang of it utilizing the GPU can be a very powerful tool. See http://cran.r-project.org/web/packages/OpenCL/OpenCL.pdf for some code snippets to get you started. With this machine you can also easily use Python with OpenCL, where I would recommend: http://enja.org/category/tutorial/advcl/ if you want to go that route. A: My solution may apply on your case. I installed successfully by resolving two errors messages. First error message I resolved comes from the source file, rpudist.cu (in src folder), as the error message suggests it is in line 159. You can use a text editor to read the source file and find this code, (dev = 1.). rpudist.cu(159): warning: use of "=" where "==" may have been intended So I changed it to (dev == 1.), the error message was then gone. The second error message, indeed as you have found out, is about -Wl. I think this may be more critical. It seems to conflict with another linker option -Xlinker, which is used in the file, Makefile.in in the src folder of the rpud folder (if you extract the tarball rpud_0.0.2.tar.gz). LD_PARAMS := -Xlinker "@R_LIB@ @RPATHFLAG@" As explained in the gcc doc and I replicate here, both "Pass option as an option to the linker". So I think they passed options after them to ld to link with the files nvcc has compiled. In the following code, nvcc calls both -Xlinker, and -Wl /usr/local/cuda/bin/nvcc -shared -Xlinker "-Wl,--export-dynamic-fopenmp -L/usr/lib/R/lib -lR -lpcre -llzma -lbz2 -lrt -ldl -lm -Wl,-rpath,/usr/local/cuda/lib64" -L/usr/local/cuda/lib64 -lcublas -lcuda rpud.o rpudist.o -o rpud.so Thus, the not-very-elegant workaround is to make nvcc only use -Xlinker. To sum up, except changing the (maybe not critical) file, rpudist.cu, the solution is to alter the contents in the files (1) Makefile.in (in src folder) and (2) configure (in top-level folder). Changing the line 10 in original Makefile.in from LD_PARAMS := -Xlinker "@R_LIB@ @RPATHFLAG@" to: LD_PARAMS := -Xlinker @R_LIB@ -Xlinker @RPATHFLAG@ Then change the line 1786 in the original configure from, R_LIB=`"${R_HOME}/bin/R" CMD config --ldflags` to R_LIB="-E -fopenmp -L/usr/lib/R/lib -lR -lpcre -llzma -lbz2 -lz -lrt -ldl -lm" and line 1797 from, RPATHFLAG="-Wl,-rpath,${CUDA_HOME}${CUDA_LIB_DIR}" to RPATHFLAG="-rpath=${CUDA_HOME}${CUDA_LIB_DIR}" Finally, just follow Chi Yau's installation instruction 3) Expand the package in a temporary folder: tar xf rpud_<version>.tar.gz 4) Run configure in rpud: cd rpud ./configure cd .. 5) Then enter the following: R CMD INSTALL rpud HTH
doc_23537892
For instance TCPClient client = new TCPClient("some ip", 1234); using(var i = new CryptoStream(client.GetStream(), myEncryptor(), CryptoStreamMode.Write) { i.Write(some Data, 0, 1024); } I've tried the flush but it seems that the data can be communicated only FROM the client to server this way. Being aware of all the alternatives, I'm curious about how this could be made possible (sending data using TCP Client and receiving a response even without setting a second channel). A: use an intermediate MemoryStream var memstr = new MemoryStream(); using (var i = new CryptoStream(memstr.....) { i.Write(some data); var buf = memstr.GetBuffer(); client.GetStream().Write(buf); } var inp = client.GetStream.Read(..); var memstr2 = new MemoryStream(inp); using (var o = new CryptoStream(memstr2,...)) { var x = memstr2.Read(); }
doc_23537893
how can I do ? A: solved : navigationController?.navigationBar.isHidden = true super.viewDidLoad() A: Open your tableViewController and hide your navigation bar using navigationController?.navigationBar.isHidden = true in viewDidLoad method.
doc_23537894
I have tried using the .after method however that uses ms as units which I don't think is suitable for timers as long as 7 days. A: There is a way but it is not that efficient and that is using time.sleep() what this would do is wait a certain amount of time before running a command for example you could do import time while True: print("Hello World") time.sleep(604800) #the number of seconds in a week Then to print the second you could do import time print ('tasks done, now sleeping for 10 seconds') for i in range(604800,0,-1): time.sleep(1) print (i) This will print the seconds left
doc_23537895
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml-stylesheet type="text/css" href="../css/rssfeed.css"?> <rss version="2.0"> <channel> <title>Agriculture Dairy Environment</title> <link>http://topjobs.lk/applicant/vacancybyfunctionalarea.jsp?FA=AGD</link> <description>Open Vacancies Under Agriculture Dairy Environment</description> <copyright>Copyright 2006-2014 topjobs</copyright> <language>en</language> <image> <title>Agriculture Dairy Environment</title> <url>http://topjobs.lk/images/home/skllisdb.gif</url> <link>http://topjobs.lk</link> <width>208</width> <height>49</height> </image> <lastBuildDate>Wed, 28 Dec 2016 19:15:15 IST</lastBuildDate> <item> <title>Study, Work and Live in Australia - 0000398608 - Morgan HR</title> <description>Join us to learn more about enrolling for the Feb. 2017 intake at Deakin University, Australia. See Flier for details</description> <link>http://topjobs.lk/applicant/vacancybyfunctionalarea.jsp?FA=AGD</link> <pubDate>2016-12-15</pubDate> <closingDate>2017-01-15</closingDate> <ac>0000000368</ac> <js>0000398608</js> <ec>0000000483</ec> </item> <item> <title>Vacancies in Call Center Colombo 09 - 0000398679 - BLUESTEPS</title> <description>Call Center Associate (Male/Female) &amp; Call Center Executive (Male / Female)</description> <link>http://topjobs.lk/applicant/vacancybyfunctionalarea.jsp?FA=AGD</link> <pubDate>2016-12-15</pubDate> <closingDate>2016-12-29</closingDate> <ac>0000000417</ac> <js>0000398679</js> <ec>0000000550</ec> </item> </channel> </rss> I need to parse it and extract information inside each <item></item> blocks. There is a small issue. There are a couple of tags that have the same names outside the <item> blocks. See under the <channel> tag. Both have <title>, <link> and <description> tags. When I try to parse it, it detects the <title> tag within the < channel > block and ignores all others! How do I get only the info inside <item></item> blocks? I tried specifying tag names like item.title but that doesn't seem to work either. Here's what I have so far. import Foundation class RSSParser: NSObject, XMLParserDelegate { fileprivate var titleEntry: String = "" fileprivate var descriptionEntry: String = "" fileprivate var linkEntry: String = "" fileprivate var pubDateEntry: String = "" fileprivate var closingDateEntry: String = "" fileprivate var acEntry: String = "" fileprivate var jsEntry: String = "" fileprivate var ecEntry: String = "" fileprivate var currentElement: String = "" fileprivate var entryDictionary: [String: String] = [:] fileprivate var entryArray: [[String: String]] = [] func parseURL(URL: URL) { let parser = XMLParser(contentsOf: URL) parser?.delegate = self parser?.parse() } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { if elementName == "item.title" { currentElement = "title" } if elementName == "item.description" { currentElement = "description" } if elementName == "item.link" { currentElement = "link" } if elementName == "item.pubDate" { currentElement = "pubDate" } if elementName == "item.closingDate" { currentElement = "closingDate" } if elementName == "item.ac" { currentElement = "ac" } if elementName == "item.js" { currentElement = "js" } if elementName == "item.ec" { currentElement = "ec" } } func parser(_ parser: XMLParser, foundCharacters string: String) { if currentElement == "item.title" { titleEntry = titleEntry + string } if currentElement == "item.description" { descriptionEntry = descriptionEntry + string } if currentElement == "item.link" { linkEntry = linkEntry + string } if currentElement == "item.pubDate" { pubDateEntry = pubDateEntry + string } if currentElement == "item.closingDate" { closingDateEntry = closingDateEntry + string } if currentElement == "item.ac" { acEntry = acEntry + string } if currentElement == "item.js" { jsEntry = jsEntry + string } if currentElement == "item.ec" { ecEntry = ecEntry + string } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "item.title" { entryDictionary["title"] = titleEntry } if elementName == "item.description" { entryDictionary["description"] = descriptionEntry } if elementName == "item.link" { entryDictionary["link"] = linkEntry } if elementName == "item.pubDate" { entryDictionary["pubDate"] = pubDateEntry } if elementName == "item.closingDate" { entryDictionary["closingDate"] = closingDateEntry } if elementName == "item.ac" { entryDictionary["ac"] = acEntry } if elementName == "item.js" { entryDictionary["js"] = jsEntry } if elementName == "item.ec" { entryDictionary["ec"] = ecEntry } entryArray.append(entryDictionary) } func parserDidEndDocument(_ parser: XMLParser) { print(#function) print(entryArray.count) print(entryArray.first) } }
doc_23537896
After reading the API documentation, I made this. I basically just copied and pasted some stuff and replaced stuff that I thought I needed to replace: ` local Humanoid = script.parent:WaitForChild(“Guard”) (This is not part of the original code:) I put^ the name of the NPC I'm using, in this case the Guard. local original = workspace.VaultCode (This is not part of the original code:) Here^ I replaced something like part or whatever with the part name VaultCode. It doesn't seem right, but idk. local copy = original:Clone() Humanoid.Died:Connect(function() copy.Parent = original.Parent copy:SetPrimaryPartCFrame(CFrame.new(0, -300, 0)) end) ` I expected it to create a clone of the part Vaultcode when the NPC Guard died, but nothing happened. I also tried looking this question up and made something similar, but I deleted it and forgot what I did. All I know is it didn't work. A: The things that stand out to me in your code are, * *it looks like you have found the NPC's character model, but not their Humanoid, *you only clone the VaultCode object once, and *you spawn the object really far underground. It's possible that if the object isn't Anchored, that it is immediately falling down to the kill-plane (around -500 studs) and being immediately destroyed. And since you're only cloning it once, you are trying to set the position of an object that no longer exists. To fix this, try spawning the object where the NPC died instead, and clone a new one every time. I am assuming that this Script is located in the Workspace, not the NPC character model. -- find the VaultCode object local VaultCode : Model = workspace.VaultCode -- find the NPC and its humanoid local Humanoid : Humanoid = script.Parent:WaitForChild(“Guard”).Humanoid -- listen for when the Humanoid dies Humanoid.Died:Connect(function() -- create a copy of the vault code where the NPC died local npcCFrame = Humanoid.Parent:GetPivot() local copy = original:Clone() copy:SetPrimaryPartCFrame(npcCFrame) copy.Parent = original.Parent end)
doc_23537897
Front end: (in handlebars template) {{#if auth.token}} <script type="text/javascript" async> const token = {{auth.token}}; localStorage.setItem("token", token) </script> {{/if}} Backend, saving token and sending with render: jwt.sign( payload, keys.JWT_KEY, { expiresIn: 3600 }, (err, token) => { auth.token = token; auth.status = true; res.render("home", { auth: auth }); } ); The error is Syntax error: invalid or unexpected token. A: The reason why this is breaking is because you're trying to set the variable token in the handlebars template equal to the literal token. It would be the equivalant of doing something like: var token = gmndshhrjvjhsw4bnds221a Which doesn't work. You need to turn it into a string by wrapping it in double or single-quotes. This is the correct code for what you're trying to do: {{#if auth.token}} <script type="text/javascript" async> const token = '{{auth.token}}'; localStorage.setItem("token", token) </script> {{/if}}
doc_23537898
I use the following definition of browserify task : gulp.task('browserify', function() { var entries = glob.sync('./app/**/*.js*'); var bundler = browserify({entries: entries, debug: true}) .transform("babelify", {presets: ["es2015", "react"]}) .bundle() .on('error', function(err) { console.error(err); }) .pipe(source('bundle.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('dist')); }); I get one bundle.js while I expect to see transpiled js files in dist with the same folder structure as src (here app). Am I expecting a right thing ? If yes, how can I make it to work like what I expect. A: you should remove .pipe(sourcemaps.init({loadMaps: true})) .pipe(sourcemaps.write('./')) which are useless while you are using debug: true on browserify. the debug: true option writes directly the sourcemaps on bundle.js with base64 encoding. So on your browser, you get source files separatly.
doc_23537899
You don't have to pay for communication cost between t1 and t2 if you do them in the same processor. If you do t1 on p1 and t2 on p2, you need 5 time units to transfer data from p1 to p2. (5 is the weight of edge t1-t2) As illustrated in the right image, the communication c(1,2) and c(3,4) can be done in the same time, they both end at the end of 5 time unit. The makespan is the time taken to finish all 7 tasks. Given that there are as many processors as I want to, which algorithm can I use to find the scheduling result with minimum makespan (or at least near the minimum one)? Please note that the results in the right image may not be optimized.