Posts

Showing posts from May, 2010

cpython - '{0}'.format() is faster than str() and '{}'.format() using IPython %timeit and otherwise using pure Python -

so it's cpython thing, not quite sure has same behaviour other implementations. but '{0}'.format() faster str() , '{}'.format() . i'm posting results python 3.5.2 , but, tried python 2.7.12 , trend same. %timeit q=['{0}'.format(i) in range(100, 100000, 100)] %timeit q=[str(i) in range(100, 100000, 100)] %timeit q=['{}'.format(i) in range(100, 100000, 100)] 1000 loops, best of 3: 231 µs per loop 1000 loops, best of 3: 298 µs per loop 1000 loops, best of 3: 434 µs per loop from docs on object.__str__(self) called str(object) , built-in functions format() , print() compute “informal” or nicely printable string representation of object. so, str() , format() call same object.__str__(self) method, difference in speed come from? update @stefanpochmann , @leon noted in comments, different results. tried run python -m timeit "..." and, right, because results are: $ python3 -m timeit "['{0}'.format(...

node.js - Microsoft Bot Framework error - InternalServerError { "Message": "An error has occurred." } -

Image
when pushed bot code azure successful. tested worked before pushing azure using node app.js i updated web.config file correct credentials var builder = require('botbuilder'); var connector = new builder.consoleconnector().listen(); var bot = new builder.universalbot(connector); bot.dialog('/', [ function (session) { builder.prompts.text(session, 'hi! name?'); }, function (session, results) { session.send('hello %s!', results.response); } ]); when @ azure logs following messages 2016-11-17t13:31:12.880 executing: 'functions.messages' - reason: 'this function programmatically called via host apis.' 2016-11-17t13:31:12.880 function started (id=22f4fffb-ad0d-4b54-b86f-dd895c098910) 2016-11-17t13:31:12.880 function completed (failure, id=22f4fffb-ad0d-4b54-b86f-dd895c098910) 2016-11-17t13:31:12.880 scripthost error has occurred 2016-11-17t13:31:12.880 error: implement me. unknown stdin file type! ...

node.js - karma test pass but npm test give error -

i use https://github.com/angularclass/angular2-webpack-starter , have foloowing problem: when i'm in project directory , run karma start then get: summary: ✔ 0 tests completed but when run: npm test i get: summary: ✔ 0 tests completed npm err! test failed. see above more details. if run: npm run test i get: summary: ✔ 0 tests completed npm err! darwin 16.1.0 npm err! argv "/usr/local/cellar/node/7.1.0/bin/node" "/usr/local/bin/npm" "run" "test" npm err! node v7.1.0 npm err! npm v4.0.2 npm err! code elifecycle npm err! angular2-webpack-starter@5.0.5 test: `karma start` npm err! exit status 1 npm err! npm err! failed @ angular2-webpack-starter@5.0.5 test script 'karma start'. npm err! make sure have latest version of node.js , npm installed. npm err! if do, problem angular2-webpack-starter package, npm err! not npm itself. npm err! tell author fails on system: npm err! karma s...

Upload a dataset to github -

i want upload dataset github (with related stuff description files , links) done in here http://hfed.github.io/ , in here http://iawe.github.io/ does know how can done? those websites, hosted github. check out: https://pages.github.com/

excel - Using a dynamic range in a Index Match formula to return the max value -

i have got following formula return maximum value/its area data: =index($1:$1,0,match(max(2:2),2:2,0)) |col | col b | col c | etc. 1 | | area 1 | area 2 | 2 |topic1 | 50.57 | 60.36 | 3 |topic2 | 467.8 | 636.8 | etc. in case formula return 60.36 / area 2 depending on row used in index function. however, there no guarantee of topics present want use dynamic row reference rather fixing @ e.g. 2:2 - i.e. instead of 2:2 topic1, find maximum value in row , return either area or value (i'll need both). i've tried using like =index($1:$1,0,match(max(match("topic1",a:a):match("topic1",a:a)),(match("topic1",a:a):match("topic1",a:a)),0)) without success. i suspect i'm missing obvious appreciated. thanks in advance. edit: sort of answered own question. in case helps else reorganized data in better format (each row: topic1|area1|value) , used =maxifs(c:c,a:a,f1) return value , =index(b:b,match(maxifs(c:c,a:a,a1),c...

css - Control the dashed border stroke length and distance between strokes -

Image
is possible control length , distance between dashed border strokes in css? this example below displays differently between browsers: div { border: dashed 4px #000; padding: 20px; display: inline-block; } <div>i have dashed border!</div> big differences: ie 11 / firefox / chrome are there methods can provide greater control of dashed borders appearance? css render browser specific , don't know fine tuning on it, should work images recommended ham. reference: http://www.w3.org/tr/css2/box.html#border-style-properties

normalization - Normalizing data in python 3 -

i creating 20 points python using gaussian distribution shown below: xpoints1 = np.random.normal(2,1,20) ypoints1 = np.random.normal(3,1,20) xpoints2 = np.random.normal(10,1,20) ypoints2 = np.random.normal(8,1,20) these points later used in order logistic regression , need normalize data feature scaling , not sure whether have done correctly . normalization done below subtracting mean , dividing standard deviation : for in range(0,len(xpoints1)): xpoints1[i] = (xpoints1[i]-2)/1 ypoints1[i] = (ypoints1[i] - 3) / 1 xpoints2[i] = (xpoints2[i] - 10) / 1 ypoints2[i] = (ypoints2[i] - 8) / 1

asp.net - Dynamically creating array of objects in view -

i outputting data query , placing input box each 1 on view. this partial view inside 1 of forms. @model ienumerable<project.models.vehicletypeseat> @using pagedlist.mvc; <link href="~/content/pagedlist.css" rel="stylesheet" type="text/css" /> @{ int counter = 0; } <p> </p> <table> <tr> <th> <div class="editor-field"> crew </div> </th> <th> description </th> </tr> @{ @for (var item in model) { <tr> <input type="hidden" name="raceseats.index" value="@(counter)" /> <td> @html.dropdownlist(item.crewid, null, "--select crew member--", htmlattributes: new { @class = "form-control", @name ...

java - NullPointerException when stubbing a test method call with Mockito -

i have these 2 lines in unit test: defaultmessagelistenercontainer defaultmessagelistenercontainer = mockito.mock(defaultmessagelistenercontainer.class); when(defaultmessagelistenercontainer.isrunning()).thenreturn(true); stack trace: java.lang.nullpointerexception @ org.springframework.jms.listener.abstractjmslisteningcontainer.isrunning(abstractjmslisteningcontainer.java:347) @ xxxxxxxxxxxxxx.messageprocessorcontrollertest.testping(messageprocessorcontrollertest.java:109) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:497) @ org.testng.internal.methodinvocationhelper.invokemethod(methodinvocationhelper.java:85) @ org.testng.internal.invoker.invokemethod(invoker.java:639) @ org.testng.internal.invoker.invoketestmet...

android - Change volume of an alarm -

i want set volume alarm. use code nothing seems happen volume, logs show value of volume i'd set. should change volume? my code: final mediaplayer mediaplayer = mediaplayer.create(this, ringtonemanager.getactualdefaultringtoneuri(this,ringtonemanager.type_alarm)); final audiomanager audio = (audiomanager) getsystemservice(context.audio_service); final int currentvolume = audio.getstreamvolume(audiomanager.stream_alarm); log.e("point_1", "volume " + currentvolume); audio.setstreamvolume(audiomanager.stream_alarm,0,0); mediaplayer.start(); new timer().schedule(new timertask() { @override public void run() { mediaplayer.stop(); log.e("point_1", "volume_after " + audio.getstreamvolume(audiomanager.stream_alarm)); } }, 5000); thanks. use code audiomanager audiomanager = (audiomanager)getsystemservice(c...

javascript - AngularJS 1 form validation in the loop -

i have problem angulare code. have made small form structure ng reapet . when removed 1 of element every element down of them not show "not valid" message . of them work fine down of remove not showing info not given false of data-ng-show="zhf.w{{key}}.$error.pattern" why ng show not taked false. <form name="zhf" class="form-horizontal"> <div data-ng-repeat="(key, i) in vm.items.info | limitto: (vm.numberofdays)"> <div class="col-sm-3"> <input type="text" class="form-control" id="w{{key}}" name="w{{key}}" ng-model="vm.item[key].w" placeholder="0" ng-pattern="/^[0-9]{1,10}([,.][0-9]{1,2})?$/" required> <p style="color: #a94442" class="text-danger" data-ng-show="zhf.w{{key}}.$error.pattern"> <span>not valid number!</span> </p> </div> ...

python - multiprocessing timing inconsistency -

i have 100 processes. each process contains 10 inputs(logic expressions) , task of each process find fastest heuristic algorithm solving each of logic inputs(i have 5 heuristic algorithms). when run each process separately results different when run of processes in parallel (using python p1.py & python p2.py &….. ). example, when run processes separately input 1 (in p1) finds first heuristic algorithms fastest method when in parallel same input finds 5th heuristic algorithms faster! reason cpu switch between parallel processes , messes timing not give right time each heuristic algorithm spends solve input? solution? can decreasing number of processes half reduce false result? (i run program on server) the operating system has schedule processes on smaller amount of cpus. in order so, runs 1 process on each cpu small amount of time. after that, operating system schedules processes out let other processes run in order give process fair share of running time. each...

gremlin - How to remove an edge and add a new edge between two vertices? -

i'm trying drop edge , add new edge between 2 vertices. how do in tinkerpop3? def user = g.v().has("userid", 'iamuser42').has("tenantid", 'testtenant').haslabel('user'); user.oute("is_invited_to_join").where(otherv().has("groupid", 'test123')).drop(); def group = g.v().has("groupid", 'test123').has("tenantid", 'testtenant').haslabel('group').next(); user.addedge("is_member_of", group); this error on gremlin shell: no signature of method: org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.defaultgraphtraversal.addedge() applicable argument types: (java.lang.string, com.thinkaurelius.titan.graphdb.vertices.cachevertex) values: [is_member_of, v[8224]] thank you. the gremlin console tutorial discusses issue bit. not iterating traversal. consider following: gremlin> graph = tinkerfactory.createmodern() ==>tinkergraph[vertices:...

How to write ints with specific amount of bits in Java -

Image
so want write in file integers with, example, 10 bits each in little endian format. shouldn't aligned byte. following image may understand scructure. i looked @ bytebuffer (i'm coding in java) doesn't seem this. this not possible default. java doesn't have bit type, closest going byte or boolean. can make util class 10 booleans (as bits) in whatever order like, other that, java not hold functionality.

javascript - Angular 2 Service Singleton Scoping Problems -

i have angular 2 service can't seem working correctly. reason scoping on this isn't expect be. i'm using fat arrows, should keep things scoped correctly i'm not sure wheels falling off. the service declare const trello: any; import { injectable } '@angular/core'; import { http, response } '@angular/http'; @injectable() export class trelloservice { key: string = 'test'; token: string = 'test'; boards: = []; constructor(private http: http) { console.log('initializing trelloservice. should see me once.'); } getopenboards(): promise<void> { // 'this' null here. no scope @ all??? const url = `https://api.trello.com/1/member/me/boards?key=${this.key}&token=${this.token}`; return this.http.get(url) .topromise() .then((response: response) => { debugger; this.boards = response.json(); ...

I get the CI_DB_mysqli_driver::row_array() in Codeigniter -

i ci_db_mysqli_driver::row_array() error when trying display cell value. this model function list_get($id){ $this->load->database(); $query = $this->db-> select('*') ->from('lists') ->join('list_items', 'list_items.items_list_id = lists.list_id') ->where('items_list_id', $id); return $query->row_array(); } the error appears when try echo view <?echo $query['list_by'];?>

javascript - Passing a variable to an angular 1.x component that is in a Angular Material Dialog -

i trying pass object component inside angular material dialog. the function use display dialog is: ctrl.opencampaignsplitdialog = function(ev, split){ $mddialog.show({ template: '<campaign-split-dialog split="$ctrl.split"></campaign-split-dialog>', parent: angular.element(document.body), targetevent: ev, clickoutsidetoclose:true, fullscreen: $scope.customfullscreen // -xs, -sm breakpoints. }).then(function(split) { ctrl.addcampaignsplit(split); }, function() { $scope.status = 'you cancelled dialog.'; }); }; this correctly opens dialog. this code component: angular .module('app') .component('campaignsplitdialog', { templateurl: 'app/components/campaignsplitdialog/campaignsplitdialog.html', controller: campaignsplitdialogcntrlr, bindings:{ split: '<...

windows - Python: How to get domain\username for logged in user -

in python how logged in username in domain\username format. following username: import getpass import os; print(os.getlogin()) print(getpass.getuser()) here go : import os domain = os.environ['userdomain'] print(domain) (but see doest give fqdn, netbios name)

c# - Validate file type by base64 string -

i writing web api accepts file base64 string , converts 2 dimentional array. 1 of requirements verify file of type excepted , should done validating file base64 string. example validation pdf. how xlsx & csv? if (file.take(7).sequenceequal(pdf)) { mime = "application/pdf"; }

angular - Changing styles/css in Angular2 with JS changes styles for a moment and then reverts back to its previous styles -

so i'm using following js change styles elements in angular 2. when load view height set moment maxheight = 100, after few millisecs reverts styles on stylesheets. has clues might happening can styles changed directly js in angular? let projectmatchers = document.getelementsbyclassname("th-project-matcher"); let rowmatchers = document.getelementsbyclassname("th-row-matcher"); let maxheight = 100; rowmatchers[i].style.height = maxheight + "px"; projectmatchers[i].style.height = maxheight + "px"; ok think styles applying javscript overwritten change events of angular 2 , used ngstyle apply styles directly div , works without problems: <div class="my-class" [ngstyle]="matchheight(i)"></div> this matchheight(): public matchheight(index: number): string { return { height: "250px", }; }

Rewrite url segments to get parameters nginx -

i'm trying few hours solve problem, shouldn't of headache. i need correct code nginx server acomplish this. i have url this: https://www.example.com/share/userid/file/ and want rewrite to: https://www.example.com/share/?id=userid&key=file/ i've tried several solutions here in stackoverflow none of them have worked. i've tried this: rewrite ^/share/(.*)/(.*)$ /share/index.php?id=$1&key=$2 ; that works if place index.php file there, can't cause /share/ permalink, not actual folder (wordpress). if this: rewrite ^/share/(.*)/(.*)$ /share/?id=$1&key=$2 ; i 404 nginx error. it seems ^/share/(. )/(. )$ not triggering rewrite, must wrong although i'm looking @ nginx rewrite docs , looks ok. any ideas? tried try_files no success. thank you update: ok works rewrite ^(/share/)([0-9]+)/(.*)/$ https://$server_name/share/?id=$2&key=$3 last; however reason if doesn't work: rewrite ^(/share/)([0-9]+)/(.*)/$ /share/?id=$2...

c# - Dynamically Create Controls in MVVM -

i pretty new wpf. trying create controls dynamically in mvvm controls not rendered on view. want number of label , textbox created on view. below code: model code public class mymodel { public string keyname { get; set; } public string keyvalue { get; set; } } modelview code public class myviewmodel { private observablecollection<mymodel> propertieslist = new observablecollection<mymodel>(); public customwriterviewmodel() { getmyproperties() } public observablecollection<mymodel> properties { { return propertieslist; } } private void getmyproperties() { mymodel m = new mymodel(); m.keyname = "test key"; m.keyvalue = "test value"; mymodel.add(m); } } view code(which user control) <grid> <itemscontrol itemssource="{binding properties}"> <itemscontro...

Difference between git@github.com:... and https://github.com/...? -

i've attempted building project had various dependencies declared github links. links mixture of links public github repositories , private github enterprise repositories of company. some of links in format https://github.com/project/repo.git and in format git@github.com:project/repo.git what difference between such formats , format intended used purpose? git can operate on variety of different protocols http(s) https://github.com/project/repo.git it uses port 443 (or 80 http), allows both read , write access, password auth (like on github allows anonymous read access asks paasword write).and firewall friendly (it not require infra configuration). ssh git@github.com:project/repo.git it uses port 22, allows both read , write access, requires ssh keys auth if give git public ssh key, ssh protocol use private key authentication git, not need provide username password. with ssh not asked provide password each time use git push command ssh protocol use...

c# - Regex.Escape() unrecognized exception -

i have following code in c# : string str = @"\hello ali how you? fine? hello , hi"; console.writeline(regex.matches(regex.escape(str), @"\hello").count); i following error: {"parsing \"\hello\" - unrecognized escape sequence \h."} i need know when \ + (some names) exists in code. have used @ not using escape sequence characters still mentioned error. can not understand why happens! escape sequences used independently in both strings and regular expressions different meanings. when prefix string literal @ telling compiler interpret string literally without escape sequences. regular expression engine again sees "\h" , tries interpret escape sequence. basically need apply both string literal @ and regex.escape function make \h interpreted literal both parsers: console.writeline(regex.matches(str, regex.escape(@"\hello")).count);

WKWebView can't carry cookie for 302 redirect -

i set cookie in request header before call loadrequest() function load page. use document.cookie() set cookie wkuserscript according [ wkwebview cookies . however, find if 302 redirection occurs, request may fail loss of cookie. example, request of http://a redirect http://b , set cookie request of http://a operating request head , using wkuserscript, these 2 ways can not set cookie request of http://b , 302 request of http://b may fail. situation occurs in ios8 more ios9. have workaround? note sure, first response may contain "set-cookie" header. hence, have use provided cookie in second request. may it's missing.

typeahead.js - Typeahead showing the wrong suggestion -

i have never used typeahead or bloodhound before, got working using local data. reason, when try use remote data. suggestions dont work intended. code: var names = new bloodhound({ datumtokenizer: bloodhound.tokenizers.whitespace, querytokenizer: bloodhound.tokenizers.whitespace, remote: { url: '@url.action("getautonames","customer")' } }); names.initialize(); $("#customername") .typeahead({ hint: false, highlight: true, minlength: 1 }, { name: 'customernames', displaykey: 'name', source: names, limit:1 }); i have 5 json objects returning remote. these obj...

android - jaudiotagger POPULARIMETER tag -

i migrating app using org.blinkenlights.jid3 jaudiotagger. have implemented of mp3 tags struggling popm tag. trying read popm gettting frame. appears correct method code recongnises 3 methods (long irating = popmframe.getrating(); long cnt = popmframe.getcounter(); string mail = popmframe.getemailtouser()). what should put in brackets framebodypopm popmframe = id3v24tag.getframe( );. using jid3 achieved result follows: try { id3v2_3_0tag id3v2_3_0tag = (org.blinkenlights.jid3.v2.id3v2_3_0tag) mediafile.getid3v2tag(); if (null != id3v2_3_0tag) { (int = 0; < id3v2_3_0tag.getpopmframes().length; i++) { if (id3v2_3_0tag.getpopmframes()[i] != null) { rating = id3v2_3_0tag.getpopmframes()[i].getpopularity(); break; } } } rating = rating / 50; } catch (id3ex...

python - SVM with SKLearn & OpenCV -

i trying predict emotion shown on image using svm. when run code warning below , prediction not shown: deprecationwarning: passing 1d arrays data deprecated in 0.17 , willraise valueerror in 0.19. reshape data either using x.reshape(-1, 1) if data has single feature or x.reshape(1, -1) if contains single sample. deprecationwarning) here code training , testing: emotions = ["anger", "neutral"] def make_sets(emotions): training_data = [] training_labels = [] emotion in emotions: training = glob.glob("try here\\%s\\*" %emotion) item in training: image = cv2.imread(item) gray = cv2.cvtcolor(image, cv2.color_bgr2gray) training_data.append(gray.ravel()) training_labels.append(emotions.index(emotion)) return training_data, training_labels x,y = make_sets(emotions) new_x = np.asarray(x) new_x.flatten() new_y = np.asarray(y) clf = svm.svc(kernel='linea...

swift - Move visible images in StackView closer to leading space -

i have horizontal scrollview of 20 (110 * 130 point) uiviews contained within stackview. each uiview contains image. when uiviews hidden uiview width maintained @ 110points. however, spaces left hidden uiview should be. i have been practicing stackview of 3 uiviews , hiding center uiview. leaves space in middle... 3rd uiview move 2nd uiview position (middle) , perform subsequent uiviews later on. does know how go doing this? possible? i hoping accomplish uicollectionview, however, don't think can drag image uicollectionview uiview drag , drop image uicollectionview uiview? a storyboard isn't meant these complex user interactions, recommend programmatically create stack view , set constraints programmatically well. let's change elements' heights in code easily. might started: add views in uistackview programmatically

c# - How to stop Windows CryptoAPI to add private key to public-only cert upon decryption -

i'm trying test s/mime decryption cryptdecryptmessage function in decryption mode keeps working if certificate in personal store public-only (while private key needed decryption). magically, certificate turns private+public certificate after function called. initially, had full certificate in personal store , working fine. then, had test happen if tried decrypt having public-key cert. exported public key, removed cert store , imported public key alone. can't testing because windows somehow adds private key cert. perhaps, there internal cache of private keys or activated when cryptoapi needs private key. disable feature if possible or somehow tell system don't want use cryptoapi calls. the same occurs outlook (as internally uses same cryptoapi functions). i added excerpt sources (cannot create self-contained sample turns out complex) decryption part should ok. double checked private key appears in certificate @ moment when cryptdecryptmessage executed, not before o...

bash - Parse configuration remote configuration file -

i want read in remote configuration file in bash script; locally following works fine: while ifs="=" read -r name value; declare "$name=$value" done < "$cfg" i tried same using ssh , cat : ssh "$hostname" "cat $remote_cfg" | while ifs="=" read -r name value; declare "$name=$value" echo $name $value done but variables declared in scope of while loop, how can bring them outer scope? thanks in advance! i have figured things out (source: http://mywiki.wooledge.org/bashfaq/024 ). process substitution works: while ifs="=" read -r name value; declare "$name=$value" done < <(ssh "$hostname" "cat ~/.cuttleline.cfg")

Compressing videos and uploading in php -

hello have built web application allows users upload videos, trying compress videos before uploading them save bandwidth. please how go these? e.g, in pictures compression gd library in video searched post on youtube , stack overflow, none answers question these code. note:these code works trying compress video before upload in php. in advance.. i looked @ post server-side video conversion , compression not looking because have never worked ffmpeg <?php include "connect.php"; ?> <?php if ((isset($_post['videoname'])) && (isset($_post['aboutvideo'])) && (isset($_post['timestart'])) && (isset($_post['timestop'])) && (isset($_post['streamersid']))){ $videoname=$_post['videoname']; $aboutvideo=$_post['aboutvideo']; $timestart=$_post['timestart']; $timestop=$_post['timestop']; $streamersid=$_post['streamersid']; $streamerstype=$_pos...

android - Tap Gesture Gesture Recognizer in ListView not working -

Image
i have in viewmodel: public class myclass: inotifypropertychanged { public event propertychangedeventhandler propertychanged; int taps = 0; icommand tapcommand; public myclass() { tapcommand = new command(ontapped); } public icommand tapcommand { { return tapcommand; } } void ontapped(object s) { taps++; debug.writeline("parameter: " + s); } } and in xaml: <image source="delete.jpg" heightrequest="20" widthrequest="20"> <image.gesturerecognizers> <tapgesturerecognizer command="{binding tapcommand}" commandparameter="image1" /> </image.gesturerecognizers> </image> but when image clicked nothing appears in output log. i'm missing ? note 1: i've followed guide here note 2: i'm debugging on android device update 1: full xaml here ...

java - Invoke request to localhost immediately after servlet container startup -

i'm looking have java web application call @ localhost url after servlet container (be tomcat, jetty, ...) begins accepting requests. i'm using java spring framework believe that's "side issue" since it's servlet container's status need aware of. as understand it, spring initializes application context beans first, maps urls , initializes dispatcherservlet handle handling/filtering of requests. i'm looking find "moment" when can safely use resttemplate call server itself. i've tried seems "too early" has resulted in java.net.connectexception: connection refused --except when invoke manually web browser via controller endpoint--which succeeds. i've tried using: javax.servlet.servletcontextlistener per how invoke method on servlet or controller after web container has started org.springframework.context.applicationlistener<contextrefreshedevent> a hacky custom servlet's init method "load-on-s...

c++ - Removing back pointers with the use of explicit instantiation declarations causes std::bad_weak_ptr exception -

i have developed code compiles correctly, fails @ (debug) runtime. using vs2015. background: building advanced message engine. make programmatic addition of new messages maintainable, in production code took time craft initial messages using explicit initialization declaration c++ construct. works , makes crafting of new messages cookie-cutter, not mention reducing maintenance of messaging guts nothing. here skeleton code functionality: #include <memory> template< typename d_t > struct h // prototype explicit initialization declarations (eid) { h( d_t& d ) : x { d } {} d_t& x; }; template< typename d_t > struct b // base class derived objects d1 , d2 { b( d_t& d ) : d { d } {} d_t& d; // kind of backptr initialized when eids contructed // actual eids , b h< d_t > { d }; h< d_t > b { d }; }; struct d1 : public b< d1 > { d1() : b( *this ) {} void func1() {} }; struct d2 : public b< d2 > { d2() : ...

php - Carbon::now() - only month -

i couldn't find anywhere in documentation how show current year or month carbon? when write this: carbon\carbon::now('m'); it gives me whole time stamp, need month like date('m'); but must carbon! how can achieve this? $now = carbon::now(); echo $now->year; echo $now->month; echo $now->weekofyear;

java - Spring Social Signin - Got anonymousUser after SignInAdapter -

everything works anonymoususer security context. social signin works, (new) user (and implicitly) signed through custom connectionsignup, signinadapter called, sets new auth in context, status 302 when protected page called , got redirected login page. log reports principal=anonymoususer, type=authorization_failure, data={type=org.springframework.security.access.accessdeniedexception, message=access denied}] . this signin adapter @service public class springsecuritysigninadapter implements signinadapter { @autowired private userdetailsservice userdetailsservice; @override public string signin(string localuserid, connection<?> connection, nativewebrequest request) { userdetails userdetails = userdetailsservice.loaduserbyusername(localuserid); usernamepasswordauthenticationtoken authentication = new usernamepasswordauthenticationtoken(userdetails, userdetails.getpassword(), userdetails.getauthorities()); securitycontextholder.getconte...

mysql - Cache Data from Cloud to Client Desktop Application -

which db technology better caching data cloud clients' computer. financial desktop application queue data needed , stored on cloud, new information sent cloud. need desktop application store locally user registering , both cloud , clients' applications must have same information @ times. user not tech savvy , should able install app , start using it. users don't want rely on heavily on matter. would recommend installing on every client's laptop sql server, mysql, sqlite or there technology used app. i have considered using xml , json files, since information, though financial, not data intensive. @ least now.

c# - Grab the first to fourth characters from string and change it to other character in Gridview -

i have gridview numbers of columns. in 1 of columns, have users' contact number, want mask first 4 number . there way it? for example: 123456 i want have last 2 numbers visible. thus, output be xxxx56 is there way? <asp:gridview id="gvattendance" runat="server" autogeneratecolumns="false" cssclass="table table-bordered table-hover table-striped gvv"> <columns> <asp:boundfield datafield="usercn" headertext="contact number" /> </columns> </asp:gridview> the easiest way can think of creating function returns anonymized string inside gridview itemtemplate. <asp:templatefield> <itemtemplate> <%# anonymizestring(eval("usercn").tostring()) %> </itemtemplate> </asp:templatefield> and function public string anonymizestring(string input) { if (!string.isnullorempty(input) && input.length...

c - My IF program is incorrect -

the problem having output '-1' regardless of enter. the rules must follow are: outputs -1 if input number less zero; outputs 0 if input number zero; outputs 1 if input number greater zero. code below: #include <stdio.h> int main () { int number; printf("please enter number: "); scanf("%i", &number); if("number > 0") { printf ("-1"); } else if ("number == 0") { printf("0"); } else if ("number < 0") { printf("1"); } } in these if-else statements if("number > 0") { printf ("-1"); } else if ("number == 0") { printf("0"); } else if ("number < 0") { printf("1"); } there used string literals example "number > 0" condition expressions. string literals used in expressions converted pointers first character , unequal 0. tthus first condition in if-else statements yields true . i think ...

asp.net mvc - Searching always returns empty list in MVC? -

i'm trying implement filtering in page contains data, page shows 3 different entities: branches , items , categories , used view model: public class warehousedata { public ienumerable<item> items { get; set; } public ienumerable<category> categories { get; set; } public ienumerable<branch> branches { get; set; } } in controller: public actionresult index(string sort, string search) { var warhouse = new warehousedata(); warhouse.items = db.items.include(c => c.categories).tolist(); warhouse.branches = db.branches; viewbag.search = search; warhouse.branches = db.branches.tolist(); switch (sort) { case "q_asc": warhouse.items = warhouse.items.orderby(c => c.quantity).tolist(); viewbag.sort = "q_desc"; break; case ...

vs extensibility - Adding a custom editor for a custom binary type (zip) -

it looks can't tell vs want custom editor .myext type. if file text file, works fine. however, wanted file .zip structured content, i.e. manifest.json file , other files inside it. i did original tests manifest.json , everythign worked, i'm able create custom editor (although had problems opening json editor default). however, switching .zip file renamed .myext breaks everything. tried override editor chooser implementing ivseditorfactorychooser still doesn't work. how can tell vs support new extension even if it's not text file ? thanks leads.

salt stack - Using SaltStack's State Modules to Accept Newly Added Repo's Package Signing Key -

problem on standalone minion, salt.states.pkgrepo.managed being used add non standard software repo. problem that's occurring, when following sudo zypper update runs, key has not been (auto) accepted system, preventing packages being updated or installed , next state fails. to reiterate exact state used mysuse.sls : suse-gis-repo: pkgrepo.managed: - name: application_geo - humanname: applications related earth (gis, mapping, geodesy, gps, astronomy) (opensuse_leap_42.1) - baseurl: http://download.opensuse.org/repositories/application:/geo/opensuse_leap_42.1/ - gpgcheck: 1 - gpgkey: http://download.opensuse.org/repositories/application:/geo/opensuse_leap_42.1//repodata/repomd.xml.key the problem when next phase of state runs: packages_uptodate: pkg.uptodate: - refresh: true it fails because of required manual intervention shown below: new repository or package signing key received: repository: application_geo key name: a...

ios - xamarin forms zxing forms scanner crash -

i'm using zxing.mobile.forms package scanner app i'm building. when code runs var scannerpage = new zxingscannerpage(); await navigation.pushasync(scannerpage); the error reads: got sigsegv while executing native code. indicates fatal error in mono runtime or 1 of native libraries used application. the iphone emulator exits app home screen , theres no visible error message being displayed, output code above things try figuring out error surround method action in try catch braces in visual studio go tools---> options---> xamarin ---> , set xamarin diagnostics diagnostics possible quick fix update xamarin form nuget package latest & greatest in pcl project , ios project un-installed previous build ios device & after following step above re-run

Two Dimensional Array C# -

i input user - "99211,99212,99213_1,99214,99215_3" , store in string as string cpt = "99211,99212,99213_1,99214,99215_3"; cptarray = cpt.split(','); i got output cptarray[0] = "99211" cptarray[1] = "99212" cptarray[2] = "99213_1" cptarray[3] = "99214" cptarray[4] = "99215_3" but output be: cptarray[0][0] = "99211","" cptarray[1][0] = "99212","" cptarray[2][0] = "99213","1" cptarray[3][0] = "99214","" cptarray[4][0] = "99215","3" if need output above can use 2d array, correct approach? according syntax provided: cptarray[0][0] ... cptarray[4][0] you want jagged array, not 2d one; can construct array of linq : var cptarray = cpt .split(',') .select(number => number.split('_')) .select(items => items.length == 1 ? new string[] {items[0], "...

python - Django reverse OneToOneField lookup in unicode method -

i have schedule , event models this. class schedule(models.model): jan = models.floatfield(default=2.0) feb = models.floatfield(default=2.0) def __str__(self): return 'some boring value' class event(models.model): name = models.charfield(max_length=20) schedule = models.onetoonefield(schedule, null=true, on_delete=models.cascade) def __str__(self): return self.name in admin view, want add schedule in eventadmin class in collapsed fashion this. class scheduleadmin(admin.modeladmin): fieldsets = [ ('schedule', {'fields': ['jan','feb']}), ] class eventadmin(admin.modeladmin): fieldsets = [ ('event', {'fields': ['name',]}), ('add schedule', {'fields': ['jan','feb'], 'classes': ['collapse']}), ] so when add schedule event, want schedule str method return related event.name field in admin for...

Why, in some situation does "git checkout origin/branch" result in "detached at <SHA>" instead of "detached at origin/master"? -

i'm working on large enough repo, multiple submodules. ensure we're in correct state during ci process, init submodules, $ git submodule init $ git submodule sync $ git submodule update --force which prints out like, synchronizing submodule url 'android/public' synchronizing submodule url 'ios/public' ... submodule path 'android/public': checked out 'asdf1234' submodule path 'ios/public': checked out 'bsdf2345' if go through , check out few different branches, if run $ platform in android ios $ $ (cd $platform/public; git fetch --all; git checkout origin/master) $ done and check folders git branch , (head detached @ origin/master) . if redo submodule initialisation @ top, , run $ platform in android ios $ $ (cd $platform/public; git fetch --all; git reset --hard origin/master; git checkout origin/master) $ done and check these again git branch , show (head detached @ <some sha>) . this kind of l...