Posts

Showing posts from April, 2011

ssl - Apache 2.4 url rewriting with https -

i'm trying url rewriting apache 2.4. want requests to http://subdomain.domain.com http://www.subdomain.domain.com https://www.subdomain.domain.com are remapped https://subdomain.domain.com to avoid error in ssl wildcard cert doesn't not match www.subdomain.domain.com. i tried with: <virtualhost ip:80> servername subdomain.domain.com rewriteengine on rewritecond %{https} off rewriterule (.*) https://%{http_host}%{request_uri} </virtualhost> <virtualhost ip:80> servername www.subdomain.domain.com redirect permanent / https://subdomain.domain.com </virtualhost> <virtualhost ip:443> servername www.subdomain.domain.com redirect permanent / https://subdomain.domain.com </virtualhost> <virtualhost ip:443> servername subdomain.domain.com ... ... ... my configuration works (1) , (2) not (3). mistake? ...

javascript - NightwatchJS: How to check if attribute is not present? -

i want check if disabled attribute not present on button using nightwatchjs. i tried doing these: .assert.attributecontains('.phone-verify-btn', 'disabled', 'null') .assert.attributecontains('.phone-verify-btn', 'disabled', null) .assert.attributecontains('.phone-verify-btn', 'disabled', 'false') .assert.attributecontains('.phone-verify-btn', 'disabled', false) but these don't seem work check if disabled set true so: .assert.attributecontains('.phone-verify-btn', 'disabled', 'true') this works fine! idea what's happening here? error rather cryptic: element not have disabled attribute. - expected "null" got: null in case,i think should attribute first until have better solution. 1 works me : browser.getattribute('@element','disabled',function(result){ if(result.value === 'true'){ // element dis...

javascript - Typeahead remote without query -

i trying use typeahead , bloodhound framework search response of api paths, remote api call. by example url api.example.com/getendpoints receive object containing endpoints. i'd want typeahead filter endpoints. far understand want specify query when using remote, can't, receive endpoints in 1 request. is there way, or suggestion, solve issue? my code like // instantiate bloodhound suggestion engine var endpoints = new bloodhound({ datumtokenizer: function (datum) { console.log('datumtokenizer, datum: ', datum, ', datum.value: ', datum.value); return bloodhound.tokenizers.whitespace(datum.value); }, querytokenizer: bloodhound.tokenizers.whitespace, remote: { url: 'https://api.example.com/getendpoints', filter: function (endpoints) { console.log(endpoints); // map remote source json array javascript object array return object.keys(endpoints).map(function (e...

c# - How to handle an unsecured or incorrectly secured fault in WCF? -

i have webapi project connects wcf service on https . project installed on 2 different development machines , started locally using iis express. the service works fine on 1 machine. however, on other machine, following error: an unsecured or incorrectly secured fault received other party. see inner faultexception fault code , detail. the inner faultexception is: exception during request the same error happens when running webapi on actual iis. code connects service is: endpointaddress ea = new endpointaddress(new uri(url), new dnsendpointidentity(identity), new addressheadercollection().toarray()); myservice service = new myservice(new custombindingsecureheader(), ea); service.endpoint.endpointbehaviors.add(new custommessageinspector()); service.clientcredentials.servicecertificate.authentication.certificatevalidationmode = x509certificatevalidationmode.none; service.clientcredentials.servicecertificate.defaultcertificate = new x509certificate2(servercert); ser...

android - Your APK's version code needs to be higher than xxx phonegap -

i using phonegap deploy apps on itunes , google play.my config file looks this <widget xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0" id="com.crondale.tippnett" version="1.1.13"> <name>tippnett</name> <description>tippnett er et system å som bidrar til bedre massebalanse. systemet finner anlegg nærheten med motsatt massebehov. det bidrar til kortere kjørelengde og raskere anleggsutførsel. du sparer penger, tillegg til @ miljøet blir spart co2 utslipp.</description> <author href="http://www.crondale.com" email="support@crondale.com">crondale</author> <content src="index.html" /> <access origin="*" /> <preference name="splashscreen" value="screen" /> <preference name="windows-target-version" value="8.0" /> <preference name="windows-phone-target-version...

Elasticsearch Aggregation Max Value -

{ "aggs":{ "nest_exams":{ "nested":{ "path": "exams" }, "aggs":{ "exams":{ "filter" : { "term": { "exams.exam_id": 96690 } }, "aggs":{ "nested_attempts":{ "nested":{ "path": "exams.attempts" }, "aggs":{ "user_attempts":{ "terms":{ "field": "exams.attempts.user_id", "size": 0 }, "aggs":{ ...

php - Syntax error when trying to put together constant and string -

this question has answer here: php parse/syntax errors; , how solve them? 12 answers normally wouldn't post syntax errors here, case bit suspicious me. trying put constant string. works fine on localhost, when push project on web server, tells me: parse error: syntax error, unexpected '.', expecting ',' or ';' in xxx on line xxx code: define("root", str_replace("index.php", "", $_server["script_filename"])); and $somepath = root . "some/path"; //synax error in line has different php versions? (5.5 on webserver, 7.0 localhost) update some updates in code: class someclass { private $somepath = root . "some/path"; //synax error in line ... } you can't use str_replace() nor function when defining contant. try: define("root", $_serv...

eclipse - Validating and showing errors in custom editor -

i have custom editor in plugin text fields @ top , table viewer below. 1 of fields on top required. if left blank want show error message on top in editor , in problems view of eclipse. using imarker able show error in problems view how highlight same in editor user. below screen shot of editor creating (not actual similar this) editor the editor content based on xml file. attributes present on child node of root displayed in table , attributes on root node displayed in text fields above table. not multipage editor - not providing source view user edit ui. the text field @ top need validate if left blank provide error message , on. thanks.

ios - Separate two images joined using UIGraphicsBeginImageContext -

i can merge 2 images using uigraphicsbeginimagecontext . can reverse process? means can have 2 separate images back? thanks you can using cgimagecreatewithimageinrect method. since merged images, should know subregion need when trying separate or un-merge. pass in cgimage first parameter image trying separate , cgrect second parameter. cgimagecreatewithimageinrect(originalimage.cgimage, croprect); apple doc cgimagecreatewithimageinrect

roslyn - How to read the source code of active document using DTE/DTE2 in visual studio project -

i trying generate assembly file (dll) current active document in editor. ex. have 3 c# source files - file1.cs, file2.cs, file3.cs , if opened file2.cs in editor. need build assembly dll single file file2.dll using roslyn compiler api. you can current document text following code: envdte.textdocument textdocument = (envdte.textdocument)dte.activedocument.object("textdocument"); envdte.editpoint editpoint = textdocument.startpoint.createeditpoint(); string result = editpoint.gettext(textdocument.endpoint);

ios - Detect the Touch on the borders of an UIView -

Image
i implementing image cropper, have circle area on top of image. area of image inside circle has cropped. have give scaling functionality cropping view. requirement have scale cropping view, when user touch on border of uiview , pan. cannot use pinch gesture. have attached image clear idea of requirement. can give optimised solution same. i tried solution , got it. viewcontroller.h #import <uikit/uikit.h> @interface viewcontroller : uiviewcontroller @property (strong, nonatomic) iboutlet uiview *viewcircletouchpoint; @end viewcontroller.m #import "viewcontroller.h" @interface viewcontroller () { float xvalue,yvalue; } @end @implementation viewcontroller @synthesize viewcircletouchpoint; now can use 2 option first option:touch event method according me when touch - (void)viewdidload { [super viewdidload]; // additional setup after loading view, typically nib. uigraphicsbeginimagecontext(viewcircletouchpoint.frame.size); [[uiima...

node.js - Node js Graph Search -

Image
i creating social application using nodejs , mysql. have table named followers . fields are: follower , following . for explain problem, create fake data in followers table: ( follower , following ) amir, reza amir, meghdad amir, batman amir, david reza, mohammad meghdad, mohammad batman, bastani mohammad, david bastani, joseph this network of ' amir ' explain want: result want: ( user , level , connections ): reza, 0, 1 meghdad, 0, 1 batman, 0, 1 david, 0, 2 mohammad, 1, 2 bastani, 1, 1 joseph, 2, 1 i not mysql, try levelgraph database , confused me in level s after 3. can me? finally own search works: let getnetwork = ( user, maxlevel = 5 )=>{ let getlevel = ( user, level )=>{ return new promise( ( resolve, reject )=>{ let search = []; for( let = 0; < level; i++ ){ search.push( { subject: db.v( ), o...

javascript - RegEx find unique words -

i'm trying parse string in javascript , find unique words, starts : symbol. wrote regular expression purpose: /(:[a-z]\w+)(?!.*\1)/g it works fine string: "test :one :one test :one test :two".match(/(:[a-z]\w+)(?!.*\1)/g) and result [':one', ':two'] online example #1 but, if after word goes new line symbol "test :one\n :one test :one test :two".match(/(:[a-z]\w+)(?!.*\1)/ig) regex not working , returns [':one', ':one', ':two'] online example #2 how modify regex , unique results? you need use [\s\s] instead of . make sure check may go far end of string (not line) , [a-za-z] instead of [a-z] (see why regex allowing caret? ): /(:[a-z]\w+)(?![\s\s]*\1)/gi see regex demo var re = /(:[a-z]\w+)(?![\s\s]*\1)/gi; var str = 'test :one\n :one test :one test :two'; console.log(str.match(re)); //or, rid of inital : console.log(str.match(re).map(function(x){return x.substr(1);...

mobile application - Wordpress api plugin V2 + post order -

i'm trying build mobile app using wordpress backend (see "wordpress hybrid client"), , use wp api v2 query posts category. crucial me control order of posts, i've installed several wp  plugins allow controll order of posts in site (eg 'simple poßt order'). while these posts work wondefully when browsing site, dont see way integrate them wp api v2 pluging - cant controll order of posts in application. know how it? i'm considering writing small plugin bridge these two. might take me long time since it's not field. any suggestion or code snippet, no matther how obvious, welcomed. i'm noob wordpress. i've ended solving issue myself - i've found 'post-order' pluging, intuitive-custom-post-order , modified support wp-api, , created pull-request . unknown reason, author not reply my-pull request. the fix small modification, can done on 'post-order' plugin, believer: add_action( 'init', array( $this, ...

Binding SSL certificates to Website in IIS -

i have server hosting domain named abc.com . have ssl certificate installed domain on server , abc.com require ssl. have sub domain sub.abc.com secured ssl certificate. now did bind. clicked main site abc.com in iis , opened bindings. in bindings, added https , ip address gave unassigned. ssl certificate selected ssl cert abc.com. again sub domain binding followed same steps under ip address gave ip (19.xxx.xx.xx) of server. under certificate picked certificate sub.abc.com. now on browser if open sub.abc.com working fine. if load abc.com site loading warning , displaying certificate of sub.abc.com instead of abc.com . in bindings can confirm have mapped correct certificate. not sure whats going wrong here. highly appreciated. unless running iis 8 , above, can use sni, http://www.iis.net/learn/get-started/whats-new-in-iis-8/iis-80-server-name-indication-sni-ssl-scalability

python - Py3.4 IMAPLib Login... 'str' does not support the buffer interface -

using imaplib, i'm trying connect mailserver. when include password normal string: 'password' connects fine. i'm trying obfuscate password, had run through b64encode, , used b64decode in login: #works: mail.login('myloginname', 'mypassword') #doesn't work: mail.login('myloginname', base64.b64decode('ja3rhsnakhdgkhervc')) # or mail.login('myloginname', bytes(base64.b64decode('ja3rhsnakhdgkhervc'))) ... traceback (most recent call last): file "./testing.py", line 15, in <module> mail.login('myloginname', bytes(base64.b64decode('ja3rhsnakhdgkhervc'))) file "/usr/local/lib/python3.4/imaplib.py", line 536, in login typ, dat = self._simple_command('login', user, self._quote(password)) file "/usr/local/lib/python3.4/imaplib.py", line 1125, in _quote arg = arg.replace('\\', '\\\\') typeerror: 'str' not support buff...

node.js - Execution of code in order for some purpose in node js -

i have scenario need first save user, once user saved need bind users id (primary key of user table ) forign key users_details table. so logic having 2 create operations. 1 store user , second store user details. here second create operation depend on result of first create operation. but issue whenever executing first create waiting result , parallel executing code. i have separate file separation of logic to connection var mysql = require("mysql"); var connection = {}; connection.getconnection = function(){ var con = mysql.createconnection({ host: "localhost", user: "root", password: "******", database: "*****" }); con.connect(function(err){ console.log("10"); if(err){ console.log('error connecting db'); return; } console.log('connection established'); }); return con; } module.exports = connection; for general cr operations var connection ...

Google popup Espresso Android studio 2.2 -

Image
how handle click on button com.google.android.gms:id/cancel (text "none of above") google dialog in screenshot attached espresso ui testing? [ i'm pretty sure in case espresso may not work due framework limitation. try achieve using google's typical instrumentation tool called uiautomator . works great along espresso . check: http://qathread.blogspot.com/2015/05/espresso-uiautomator-perfect-tandem.html you can try use open-source ui automation tool called robotium along espresso . check: https://github.com/codepath/android_guides/wiki/ui-testing-with-robotium using espresso allowed operate inside app under test context, cannot check notifications, of popup dialogs or running app exisitng , cheking both. hope

mongodb - expireAfterSeconds doesnt work mongo -

using mongo 3.2 i set expireafterseconds 3 days, because not need more 3 days of data on collection, can see in db, still have data month ago. configured wrong. the info gather db.runs.getindexes() { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "guardian.runs" }, { "v" : 1, "key" : { "created" : 1 }, "name" : "created_1", "ns" : "guardian.runs", "background" : true, "expireafterseconds" : 259200 } an entry should deleted: [ { "_id": "578c8aa25a3f72387073f2f0", "job_id": "573f62bf0e44a2796b6e9de1", "owner": null, "started": "2016-07-18t07:52:02.447z", "ended": "2016-07-18t07:52:14.119z", "status": "success", ...

server - Apache access to /www denied -

when try acces site i'm hosting wampserver 2.4.18 error 403 : don't have permission access /www on server. i've been looking time , don't think mu httpd.conf problem. my httpd.conf : # # main apache http server configuration file. contains # configuration directives give server instructions. # see <url:http://httpd.apache.org/docs/2.4/> detailed information. # in particular, see # <url:http://httpd.apache.org/docs/2.4/mod/directives.html> # discussion of each configuration directive. # # not read instructions in here without understanding # do. they're here hints or reminders. if unsure # consult online docs. have been warned. # # configuration , logfile names: if filenames specify many # of server's control files begin "/" (or "drive:/" win32), # server use explicit path. if filenames *not* begin # "/", value of serverroot prepended -- "logs/access_log" # serverroot set "/usr/local/apache2...

angular ui router - How to redirect form php page to different Angularjs template -

i have create login page in php. (example url: test.com/login) and signup page. (example url: test.com/signup) when user login page redirect in angular application. (example url: test.com/admin#/) but case 1: when user login redirect example url: test.com/admin/#dashboard case 2: when user login after signup redirect example url: test.com/admin/#accountverify how can above cases? angular route code: app.config(['$routeprovider', function ($routeprovider) { $routeprovider .when("/", {templateurl: "angular/cpmodule/templates/accountverify.html", controller: "cpcontroller"}) .when("/dashboard", {templateurl: "angular/templates/dashboard.html", controller: "admindashcontroller"}) .when("/accountverify", {templateurl: "angular/cpmodule/templates/accountverify.html", controller: "cpcontroller"}) .when("/agreeme...

apache kafka - Scalable invocation of Spark MLlib 1.6 predictive model w/a single data record -

i have predictive model (logistic regression) built in spark 1.6 has been saved disk later reuse new data records. want invoke multiple clients each client passing in single data record. seems using spark job run single records through have way overhead , not scalable (each invocation pass in single set of 18 values). mllib api load saved model requires spark context though looking suggestions of how in scalable way. spark streaming kafka input comes mind (each client request written kafka topic). thoughts on idea or alternative suggestions ? non-distributed (in practice majority) models o.a.s.mllib don't require active sparkcontext single item predictions. if check api docs you'll see logisticregressionmodel provides predict method signature vector => double . means can serialize model using standard java tools, read later , perform prediction on local o.a.s.mllib.vector object. spark provides a limited pmml support (not logistic regression)...

.net - When trying to use dependency injection and the IDisposable interface correctly should I inject an instance of SafeHandle? C# -

according msdn best way implement idisposable interface involves using instance of safehandle class. in given example have following line; safehandle handle = new safefilehandle(intptr.zero, true); i have been reading dependency injection , tdd , understanding in order both follow tdd , implement idisposable interface correctly have this; public class somedisposableclass : idisposable { private readonly stream _stream; private readonly idisposable _safehandle; public somedisposableclass(stream stream, idisposable safehandle) { _stream = stream; _safehandle = safehandle; } private bool disposed = false; public void dispose() { dispose(true); gc.suppressfinalize(this); } protected virtual void dispose(bool disposing) { if (disposed) return; if (disposing) { _safehandle.dispose(); _stream.dispose(); } disposed = true; } } i in...

inheritance - Unable to extend javascript prototype -

i playing around idea of subclassing javascript. pretend extending native objects (like array, string etc) bad idea. this, true, out of understanding why. having said that, let's on it. what i'm trying extend array (now, extend may not right term i'm doing) i want create new class myarray , want have 2 methods on it. .add , .addmultiple . so implemented this. function myarray(){ var arr = object.create(array.prototype); return array.apply(arr, arguments); } myarray.prototype = array.prototype; myarray.prototype.add = function(i){ this.push(i); } myarray.prototype.addmultiple = function(a){ if(array.isarray(a)){ for(var i=0;i<a.length;i++){ this.add(a[i]); } } } this works correctly, if do console.log(array.prototype.addmultiple ); console.log(array.prototype.add); i [function] , [function] . means code modifying native array object. trying avoid. how change code in way 2 console.log s give me und...

c# - How to serialize derived class to base class? -

i want serialize object , pass method parameter type parent of object. for example, have classes. public class base { public string typename => gettype().name; public string data => jsonconvert.serializeobject(this); } public class derived : base { public string name { get; set; } public int data1 { get; set; } public int data2 { get; set; } } public class derived2 : base { ... } .... i wrote code follows, var obj = new derived { name = "john", data1 = 2000, data2 = 1500 }; send(obj); and send(..) method is, public void send(base info) { // "info". } when instantiate variable obj, program has fallen infinite recursion because of "data" in base class. how can change code? infinite recursion caused data property, serialized - causes serialization of this , loop begins. the best solution change property method, not serialized , better serve purpose. if dead set on property - try marking pro...

C# Excel VBA make module names not depended on the language -

excelfile.vbproject.vbcomponents.add(vbext_componenttype.vbext_ct_stdmodule); this code in english version of office creates module named: "module1". if office language different "module1" in language. need know how module called in code. var standardmodule = excelfile.vbproject.vbcomponents.item("thisworkbook"); the same problem here in english version of office "thisworkbook" exits, in language called differently. it's possible make code language independent? the first 1 easy - vbcomponents.add returns vbcomponent . can inspect .name property: var module = excelfile.vbproject.vbcomponents.add(vbext_componenttype.vbext_ct_stdmodule); debug.writeline(module.name); the second 1 bit trickier. you'll need loop through of vbcomponents , test 2 things unique workbook object. have .type of vbext_ct_document , 134 properties in .properties collection default: vbcomponent thisworkbook; foreach (var module in...

swift - Internal /bin/cp command failed. xCode compiler error -

i'm working in xcode trying build simple calendar app. tried build , run error /users/zach/downloads/xcode-beta.app/cononts/developer/toolchains/xcodedefault.xctoolchain/ usr/bin/bitcode_strip: internal /bin/cp command failed. task failed exit 1 signal 0 { all know gives me error when line typed... goes away when comment out. let ce = nskeyedunarchiver.unarchiveobject(with: eventobject data) as! calenderevent update: tried recompile , given new error. "libswiftcore.dylib" couldn't copied "(a document being saved xcode)". it appears wrong swift std library. randomly switches between 2 errors. i same error when run low on disk space. try moving project different location, more space, clean project, , re-build.

Polymer custom behavior generates lint error -

i have created custom behavior extends applocalizebehavior: var jm = window.jm || {}; jm.applocalizebehavior = { properties: { myvar: string, value: 'a string' } } jm.applocalizebehavior = [polymer.applocalizebehavior, jm.applocalizebehavior]; my component imports behavior: ... behaviors: [jm.applocalizebehavior] ... and dom-module has binding: [[localize('hello','name','john')]] when run polymer lint error: computed binding method 'localize' not defined on element '...' when change name jm.localizebehavior additionally: behavior jm.localizebehavior not found when mixing properties ... using default polymer.applocalizebehavior not generate lint error. what need add code prevent linting errors?

c# - Basic Auth in URL, no authorization header in http context -

i'm trying allow users hit endpoint basic auth using url username:password@myurl.com\endpoint . however, when check httpcontext authorization header while debugging, it's null. it's possible i'm misunderstanding how works, under impression having username:password@ implies basic auth , attaches header? it's not practice allow users pass basic authentication parameters in url please read following understand why rfc2617

c++ - would deleting copy constructor/assignment break standard library operations -

i have few classes requirements instances must not have similar copies @ runtime. let's 1 of class looks - class a{ int id; int printernum; bool failstate = true; //.... public: //.... }; now id , printernum must unique each instance since no 2 instance can control same printer @ time. id generated @ construction of object printernum can change. these 2 requirements, provide checks @ constructor , failstate variable never initializes object , sets failstate true if bad occurs. also thinking of deleting copy constructor , assignment operator make sure user never creates copy , can initialize constructor id , printernum remain unique. but before making change thinking of asking, break other algorithms , containers available inside standard namespace? might using assignment operators , copy constructors , happen if delete these explicitly - // no copy a(const a&) = delete; // no assign a& operator=(const a&) = delete; if not po...

java - Changing binary to decimal using created constants (not parseINT() ) and declaring and initializing each of the 8 bits of the number -

assignment i have been working on forever now. required create constants declare , initiate each multiplying each it's place value (128,64,32,16,8,4,2,1) i know integer.parseint(binary....) job cannot use it. followed have far, on right track? know need each of separated user input values , have them multiplied place values added create decimal life of me cannot figure out how through loop or defining each variable import java.util.scanner; import java.util.arrays; import java.util.list; import java.util.arraylist; import java.lang.integer; import javax.swing.jcombobox; public class binary { public static void main(string [] args) { scanner keyboard = new scanner (system.in); system.out.println("enter binary number please"); integer[] digits = getdigits(keyboard.nextint()); system.out.println(arrays.tostring(digits)); }//end bracket method main public static integer[] getdigits(int num) { list <integer> digits = n...

node.js - ACL troubles with loopback.io -

i'm evaluating loopback.io developing api portion of new project, , i'm having problems setting correct acl entries. what wish accomplish given auth token, endpoints should return objects owned user. example, request /shows?access_token=xxxxxx should return objects owned user. below shows.json file, , user model named podcaster. appreciated. { "name": "show", "base": "persistedmodel", "idinjection": true, "options": { "validateupsert": true }, "properties": { "title": { "type": "string", "required": true }, "description": { "type": "string" } }, "validations": [], "relations": { "episodes": { "type": "hasmany", "model": "episode", "foreignkey": "" }, ...

node.js - Nodejs and Meteor on OpenShift -

Image
i have mobile ( ionic 2 ) chat application following implementation , uses nodejs-0.10 , mongodb 3.2.7 , meteor 1.4.1.1 . works on localhost . now need deploy openshift server . have followed following steps , created server on openshift meteor . connecting git , , can push code server. i pretty sure meteor server running on openshift , because saw effect on startup logs (via ssh). however, not sure how connect meteor server test it. the domain nodejs-easyjobs.rhcloud.com ( 54.208.77.250 ) on openshift server, can ping successfully. i using ionic 2 build mobile app. running on android , plan add ios , windows . i following this tutorial, , runs on localhost . however, not sure configured. guess localhost default, , need change different host if needs be. if check openshift server ( nodejs-easyjobs.rhcloud.com ) via ssh, can see contents of meteor bundle directory on server. git pushing code. the part don't understand is: do need configure meteor ...

c - Accidently creating gigantic file with write -

this code using: #include <stdio.h> #include <stdlib.h> void main(){ test = creat("test",0751); close(test); test = open("test",2); write(test, "123456789101112131415",21); lseek(test,-2,2); read(test,swap_array,2); write(test,swap_array,2); lseek(test,-6, 1); write(test,"xx",2); } this creates 8gb file containing instead of inserting "xx" in between numbers intend. wrong code have it? you have failed include appropriate header files. should include, @ minimum: #include <sys/types.h> #include <unistd.h> #include <fcntl.h> additionally, give access symbolic constants required make code maintainable. here working version of program: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main() { char swap_array[2]; int test = creat("test",0751); close(test); test = open("test",o_rd...

unit testing - What will be a good way to test non react components used in ReactJS? -

what way test non react components in reactjs. use enzymes limited react components. way unit test non react components. from enzyme's github page: "enzyme unopinionated regarding test runner or assertion library use, , should compatible major test runners , assertion libraries out there. documentation , examples enzyme use mocha , chai, should able extrapolate framework of choice." pretty sure can test sort of javascript enzyme, don't use constructs built enzyme made enzyme, or better use assertion libraries need non-react components. edit: caveats might run into, there solutions them https://github.com/airbnb/enzyme/issues/278

android - How to pass three string from for loop -

i have made program 'item','qty','rate' have them 3 in string array need them upload in mysql values reapeating several times in database. here code: string items[] = itemsf.split("\n"); string qtys[] = qtyv.split("\n") string rates[] = ratef.split("\n"); (final string r : rates) { (final string : items) { toast.maketext(billgenerating.this, it, toast.length_short).show(); (final string qt : qtys) { toast.maketext(billgenerating.this, qt, toast.length_short).show(); class addbilldetails extends asynctask<void, void, string> { progressdialog loading; @override protected void onpreexecute() { super.onpreexecute(); loading = progressdialog.show(billgenerating.this, "adding...", "wait...", false, false); ...

javascript - Display raw api data with knockout -

this should simple , although i'm new ko don't seem able result. i want add function view model call , display api has html text in like: <p class="class">this text</p> the view/page should call text using ko , display this: <span data-bind="text: mytext"></span> i've been using $.getjson requests inside function. need simplest way this. stackers. you mean ajax call loads text? you need set view model, apply bindings, , @ last set result of ajax call. remember set bind data-bind='html: document.viewmodel = { mytext: ko.observable() }; ko.applybindingstodescendants(document.viewmodel, document.getelementbyid("content")); //make ajax call , handle result //$.getjson('/some/url', function(data){` //document.viewmodel.mytext(data); document.viewmodel.mytext('<p class="class">this text</p>'); //}); <script src="https://cdnjs...

c# - How to populate my base Customer with EF -

see class structure first. public class customerbase { public int customerid { get; set; } public string firstname { get; set; } public string lastname { get; set; } public string address1 { get; set; } public string address2 { get; set; } public string phone { get; set; } public string fax { get; set; } } public class customer : customerbase { public virtual list<addresses> addresses { get; set; } } public class addresses { [key] public int addressid { get; set; } public string address1 { get; set; } public string address2 { get; set; } public bool isdefault { get; set; } public virtual list<contacts> contacts { get; set; } public int customerid { get; set; } public virtual customer customer { get; set; } } public class contacts { [key] public int contactid { get; set; } public string phone { get; set; } public string fax { get; set; } public bool isdefault { get; set; } ...

Webstorm Markdown editor tools all disabled? -

Image
i'm using webstorm 2016.2.2 build #ws-162.1628.41. when open .md file see bunch of tools disabled. how can enable them? apparently webstorm comes with @ point had installed trial version of plugin called markdown navigator vladsch.com . i uninstalled , couple basic buttons , side-by-side preview.

angular - Extend a components change detection in Angular2 -

i have list object, this class list { private urls: string[] = []; public getnames(): observable<string[]> { // fetch `this.urls` , extract names } public addurl(url: string) { this.urls.push(url); } public hash(): string { // generate hash out of `this.urls` } } it has urls, , can provide names found on these urls now need component displays these names: @component({ selector: 'lister', template: '<p *ngfor="let name of names|async">{{ name }}</p>' }) class lister implements onchanges { @input() list: list; private names: observable<string[]>; ngonchanges() { this.names = this.list.getnames(); } } so far good, works if use this <lister [list]="somelist"></lister> but doesnt refresh when somelist.addurl(...) called, due fact not change anything. a workaround introduce changes, this: class lister imple...

Docker-machine swarm; how to open ports on VM -

trying out new "swarm mode", following this . have created 3 vm's via docker-machine create --driver virtual box <name> . how open ports on them? it might work docker run -p <public-port>:<internal-port> <image> executed on node. however, since want run swarm, guess better follow guide solve routing mess here . if follow author's suggestions, need create swarm (i.e. docker host cluster) first docker-machine commands, e.g. docker-machine create --driver virtualbox swarm-1 docker-machine create --driver virtualbox swarm-2 setup swarm with eval $(docker-machine env swarm-1) docker swarm init --advertise-addr $(docker-machine ip swarm-1) join other machines (if there any) with eval $(docker-machine env swarm-2) docker swarm join \ --token <yourtoken> 192.168.99.106:2377 where found in output of docker swarm init command. then author suggests create network docker network create --driver overlay webnet and p...

How to reduce number of ticks in Axes3D object (in Matplotlib) -

Image
when plot axes3d object, number of ticks on x/y axes somehow changing (for example, 1x1 object, there 5 ticks on each axes, while 2x2 object, there 7 ticks on each axes, see below screenshots) 3d plot 1x1 object: 3d plot 2x2 object: the problem number of tick-labels lower number of ticks, therefore tick-labels moved beginning of axes. so, how can reduce/setup number of ticks? here code: my_w = 2 my_h = 2 x1_list_int = [] x2_list_int = [] y1_list_int = [[],[]] y1_list_int = [[0 x in range(my_w)] y in range(my_h)] #matrix initialization in xrange(my_w): print x1_list_int.append(i*10) x2_list_int.append(i+1) in xrange(my_w): j in xrange(my_h): y1_list_int[i][j] = (i-3)*(j-2)+20 data = np.array(y1_list_int) column_names = x2_list_int row_names = x1_list_int fig = plt.figure() ax = axes3d(fig) lx= len(data[0]) # work out matrix dimension...

amazon web services - Api Gateway access UserAgent and Ip from Custom Authorizer -

in body mapping template of apigateway resource can pass user-agent , ip of client lambda function. { "client_ip":"$util.escapejavascript($input.params('x-forwarded-for'))", "user_agent" : "$util.escapejavascript($input.params('user-agent'))" } is possible pass information before? lambda function used custom authorizer apigateway? you can't modify contents of what's being sent authorizer. available things methodarn , authorizatontoken , type .

Scrolling window without using Control key in Vim -

is possible scroll window screen without using control + u or control + d , (or control + f,b,e etc). aware can use 'j' or 'k', line line scroll. looking scroll through larger chunk of text without using control key. find little inconvenient move home row. (may thinking much.) i aware can use / search or ng move particular line. sometimes, helpful scroll through code, without specific line. i using gvim (windows). thank you. <c-u> / <c-d> scroll 'scroll' number of lines. can emulate via :execute 'normal!' &scroll . 'j' this long type, need mapping, again involve modifier key. ad-hoc scrolling, estimate amount of lines , type 30j . that said, modifier keys important in vim (even if less in emacs). maybe should consider remapping ctrl , example caps lock ?

Django Aggregate- Division with Zero Values -

i using django's aggregate query expression total values. final value division expression may feature 0 denominator. need way escape if case, returns 0. i've tried following, i've been using similar annotate expressions: from django.db.models import sum, f, floatfield, case, when def for_period(self, start_date, end_date): return self.model.objects.filter( date__range=(start_date, end_date) ).aggregate( sales=sum(f("value")), purchase_cogs=sum(f('purchase_cogs')), direct_cogs=sum(f("direct_cogs")), profit=sum(f('profit')) ).aggregate( margin=case( when(sales=0, then=0), default=(sum(f('profit')) / sum(f('value')))*100 ) ) however, doesn't work, because error says: 'dict' object has no attribute 'aggregate' what proper way handle this? this not work; because aggregate returns dict...

machine learning - Predict label image in tensorflow inception failed to load compute graph -

i've retrained inception model fits own needs , got step working : final test accuracy = 70.6% converted 2 variables const ops. ls /tmp/ | grep output output_graph.pb output_labels.txt i know want test model , following instructions tried : bazel build tensorflow/examples/label_image:label_image && bazel-bin/tensorflow/examples/label_image/label_image --graph=/tmp/ouput_graph.pb --labels=/tmp/output_labels.txt --output_layer=final_result --image=~/images/cat/pic.jpg the build phase succeed second part of command line gives me error : e tensorflow/examples/label_image/main.cc:278] not found: failed load compute graph @ '/tmp/ouput_graph.pb' i don't know how solve this, long file exists (its size 85 mb) is there typo in command line? see ouput_graph.pb when i'd expect see output_graph.pb (with 't' in ou t put_graph.pb).

mysql - how to make a SELECT that merges duplicated Primary Keys -

i'm performing query looks this: select a.transactionid,a.customerid,b.value adjustments inner join change b on a.transactionid = b.transactionid , a.event_date = b.event_date , a.event_id = b.event_id comment 'transfer' order a.transactionid; this query brings following result: transactionid | customerid | value ------------------------------------ transfer-001 | custa | -200 transfer-001 | custb | 200 transfer-002 | custc | -150 transfer-002 | custd | 0 transfer-003 | custa | 0 transfer-003 | custc | 150 i need change query bring list ignore cases sum of value 0 same transactionid , also, group customerid , values following: transactionid | customerid_a | value_a | customerid_b | value_b ---------------------------------------------------------...

javascript - Check height, then add or remove class -

i'm making navigation responsive. when width above number should class, when it's below, class should removed: var width = $("#primary-header-nav").width(); if ( width < 770) { $('#primary-header-nav li a').addclass('box-1-9'); } else { $('#primary-header-nav li a').removeclass('box-1-9'); } however, in reality, class never assigned. regardless of width. this site if of help: http://darylkeep.com/aanbod/ try this. $(document).ready(function(){ $(function(){ $(window).on("resize", function(){ var width = $(this).width(); var links = $('#primary-header-nav li a'); if(width < 770){ links.addclass('box-1-9'); }else{ links.removeclass('box-1-9'); } }); }); });

android - Loading image in the Navigation Drawer header from custom URL -

i not using custom library make navigation view. using navigation view support design library. how able set header image custom image internet using glide or fresco. have static imageview drawer header. edit - image needs of size? you can set in xml file navigation header : <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto" android:background="@color/colorprimarydark" android:gravity="center_vertical" android:orientation="vertical" android:paddingbottom="@dimen/nav_header_margin_bottom" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop=...

c# - Store regular expressions for use throughout web application -

i have web application contains many forms textbox fields on dates , urls etc. i using <asp:regularexpressionvalidator> validate textbox content , wondered if there way centrally store expressions using in web.config file can reference them each time add <asp:regularexpressionvalidator> , rather having type out entire regex i.e. regex store string urlregex = "(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})" web form <asp:regularexpressionvalidator validationexpression=urlregex> </asp:regularexpressionvalidator> thanks in advance i typically create resources file in asp.net app_globalresources folder centralize string constants , reference string in markup. example created regexstrings.resx resource file , added key url value containing regular expression string: <asp:textbox id="urltextbox" runat="server"></asp:textbox> <asp:regularexpressionvalidator id=...