Posts

Showing posts from April, 2012

Count datetime entries for each month from datetime column in SQL Server -

i have table timestamps , want count total number of timestamps each month. have following script returning results. there simpler way this? select substring(convert(varchar(12), dt_create, 112), 0, 7) month, count(substring(convert(varchar(12), dt_create, 112), 0, 7)) signups table_name group substring(convert(varchar(12), dt_create, 112), 0, 7) order 1 output month signups ---------------- 201705 5959 201706 9782 201707 13663 201708 7385 characters values slower, may see increase in performance trying this. select year = year( dt_create ), month = month( dt_create ), signups = count( dt_create ) table_name group year( dt_create ), month( dt_create ) ;

python - What is the complexity of this recursive algorithm? -

Image
does following algorithm have complexity of o(nlogn)? the thing confuses me algorithm divides twice, not once regular o(nlogn) algorithm, , each time o(n) work. def equivalent(a, b): if isequal(a, b): return true half = int(len(a) / 2) if 2*half != len(a): return false if (equivalent(a[:half], b[:half]) , equivalent(a[half:], b[half:])): return true if (equivalent(a[:half], b[half:]) , equivalent(a[half:], b[:half])): return true return false each of 4 recursive calls equivalent reduces amount of input data factor of 2. thus, assuming a , b have same length, , isequal has linear time complexity, can construct recurrence relation overall complexity: where c constant. can solve relation repeatedly substituting , spotting pattern: what upper limit of summation, m ? stopping condition occurs when len(a) odd . may anywhere between n , 1 , depending on prime decomposition of n . in worse case scena

how to delete the nth occurrence of a character in a string bash shell -

i have string this: str="test,test,test,test,test,test" . how can delete nth comma (,) in string str , n between 1 , 5 ? can give suggestion? thank you. $ echo "$str" test,test,test,test,test,test $ sed 's/,//5' <<<"$str" #or echo "$str" |sed 's/,//5' test,test,test,test,testtest

javascript - JS append </a> to <a> -

i cannot append </a> <a> (the second part isn't linked together) can use concatenation showed below. how solve instead of using concatenation? <!doctype html> <html> <head> <meta charset="utf-8"> <title>i'm template</title> </head> <body> <div id="a"></div> <script src="http://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgfzhoseeamdoygbf13fyquitwlaqgxvsngt4=" crossorigin="anonymous"></script> <script> var b = '<a href="#">%data%', c = ' - %data%</a>', d = '1'; // concatenation $("#a").append(b.replace('%data%', d) + c.replace('%data%', d)); $("#a").append('<br>'); // append $("#a").append(b.replace('%data%', d)

Which Java XML Parsing method to use when rewriting an XML file? -

edited little clarity. i'm writing java application takes xml file , rewrites if information in file needs updated. example of xml file below: <!doctype book public "mydtd.dtd" [ <!entity % ent system "entities.ent"> %ent; ]> <book id="exdoc" label="beta" lang="en"> <title>example document</title> <bookinfo> <authorgroup> <author> <firstname>george</firstname> <surname>washington</surname> </author> <author> <firstname>barbara</firstname> <surname>bush</surname> </author> </authorgroup> <pubsnumber>e12345</pubsnumber> <releaseinfo/> <pubdate>march 2016</pubdate> <copyright> <year>2012, 2016</year> <holder>comp

reactjs - React transition group - reload same component but swap contents after exit -

so, i've got csstransitiongroup around router switch , has route containing component currentproject inside (among couple others). the transitions working fine, switch. however, if route changed 1 matching currentproject matching currentproject (i.e, different project), enter/exit transition , new project loaded around same time, can see title , content swap on during transition. is there way react-transition-group 'exit' transition, wait content load, then 'enter' transition? are putting location={history.location} param switch tag? necessary holding content in leaving component...

html - How can I style my blockquotes to look like this? -

Image
i'm having trouble finding way add yellow blockquotes quote without indenting/adding unwanted line height. here's i'm trying achieve: here's i've tried: .contentquote { font-family: 'roboto slab', serif; font-size: 20px; } .quote { line-height: color: #003b49; font-size: 2.9em; } <h1 class="contentquote"><span class="quote">&ldquo;</span>in circles, when talk people firm best thinker in (value-based care) area , firm couples actual execution, talk premier...<span class="quote">&rdquo;</span></h1> here's keep getting: any appreciated! you have 3 problems code. first, have accidentally combined line-height , color line-height: color: . don't specify line-height in sample code, i'm guessing line-height typo. if you're using line-height , you'll need separate these out, using semicolon. second, forgot inclu

javascript - Predictive text search box -

i looking predictive search box performs example provided codpen below. how edit code instead of predicting word 'california', have array of strings predicts for? additionally possible make once word complete, script attempts predict next word being typed? https://codepen.io/sivarp18/pen/ewbmx $("#search").keyup(function(){ $("#background-input").val(''); var city = "california"; var searchtext = $("#search").val(); console.log(searchtext.tolowercase()); if(searchtext === "") $("#background-input").val(''); else if(city.indexof(searchtext.tolowercase())==0) { var currentlength = searchtext.length; $("#background-input").val(searchtext+""+city.substring(currentlength)); } }); #search-div { position: relative; } #background-input { position: absolute; color: #999999; height:25px; width:250px; }

c# - What do the square brackets mean, when it is after a string, and not an array? -

what square brackets mean, when after string, , not array? (e.g. str[5] in following example) string str; console.write("input string : "); str = console.readline(); console.writeline( (str.length < 6 && str.equals("hello")) || (str.startswith("hello") && str[5] == ' ') ); same thing means anywhere else. string is array (or @ least has indexer)... of char s. for example, have string: var x = "hello, cruel world." then can index char : var y = x[1]; at point y character 'e' .

android - Branch init between slash and main activity -

my app launches splashactivity followed mainactivity . run branch.initsession in splashactivity it's taking 1.5 seconds return listener delays launch of mainactivity . reduce time. my ideas are: run branch.initsession in mainactivity instead. run branch.initsession in splashactivity , launch mainactivity , pass branch mainactivity using eventbus processing. does have recommendations on how solve issue? cheers, duane. amruta branch here. by default, branch delay install call 1.5 seconds. delay install call in order capture install referrer string passed through google play, increases attribution , deferred deep linking accuracy. not delay other call, , install call occurs first time user opens app. if receive referrer string before 1.5 seconds, fire call, meaning delay 1.5 seconds, not guaranteed take long. if you’d optimize first install call, paste following code in application class, , not delay first install call. public final class custom

clojure - Execute a vector of functions doesn't work when fns are passes as params -

this code doesn't work indended: (((fn [& fns] (fn [& params] (reduce #(%2 %1) params fns))) rest reverse) [1 2 3 4]) ;; => () instead of (3 2 1) is there way fix change inside #(%2 %1) ? i think question equivalent to: how convert (#<core$rest>) (rest) ? note: process solve http://www.4clojure.com/problem/58 i've seen other solutions curious specific implementation. try using [params] rather [& params] , so: (fn [params] (reduce #(%2 %1) params fns)) the [& params] argument taking collection [1 2 3 4] , wrapping again, in list , giving ([1 2 3 4]) seed reduce function. if wanted change inside #(%2 %1) need unwrap ([1 2 3 4]) , first time. see if first returned collection, (coll? (first %1)) , , call (first %1) , otherwise leave %1 is. seems convoluted , won't work other input data though.

python - Airflow tasks in queue but never scheduled -

with airflow 1.8.1, using localexecutor max_active_runs_per_dag=16 , called loop dynamic create tasks (~100) pythonoperators. time tasks completed without issues. however, still possible task queue status scheduler seems forget it, can clear task , able rerun queued task , worked, know how avoid stuck in queue.

Looking for quality search engines -

do 1 happen know quality search engines out there? bad depend on such low quality, biased , anti-ethical engine such google, , seems competitors clones working within exact same scope. duckduckgo, claims privacy-concerned search engine, on other hand garbage, not have functional image/video search capabilities. the search engine advanced capabilities have ever seen yandex, it's gorgeous reverse image search. i'd more variety, differente engines tend index different portions of web. if stack overflow not place such question, please recommend or redirect me make such kinds of question technology , internet, seems pretty hard find such kinds of contents, foruns , discussions nowadays. thanks

html - Applying CSS to the Child component is not working -

Image
i have inner component shown below(i.e. presentation ) . edit-playlist.html <ion-grid no-padding> <ion-row> <ion-col col-3> delete </ion-col> <ion-col col-6> <presentation [data]="d"></presentation> </ion-col> <ion-col col-3> text desc </ion-col> </ion-row> </ion-grid> edit-playlist.scss (here have tried override child's css within parent) page-edit-playlist { .content { presentation .presentation .span-icon { right: calc(100%-55%); } } } presentation.html <div class="presentation"> <span class="span-icon"><ion-icon [name]="data.icon"></ion-icon></span> <span class="bottom-text">{{data.text}}</span> <img [src]=&qu

oracle - PL/SQL equivalent of SELECT statement -

what pl/sql equivalent of sql query: select * table(owner.package.get_exam('123456789')); this function trying call: function get_exam(id in varchar2) return ab_assign_v1 cursor c_exams(cid varchar2) select t_api_exam_v1( sei.person_id, --unique id l.description --loc description ) my_view sei join loc l on sei.loc_code = l.loc_code v_collection ab_assign_v1; begin open c_exams(id); fetch c_exams bulk collect v_collection; close c_exams; return v_collection; exception when others error_a1.raise_error(sqlcode, sqlerrm); end get_exam; hope helps. declare lv <collection_name>; begin lv:= owner.package.get_exam('123456789'); dbms_output.put_line(lv.count); end; /

ruby on rails - Summernote gem on active admin -

i'm trying use summernode gem on activeadmin form have code in post.rb file activeadmin.register post permit_params :user_id, :title, :body, :featured_image controller def find_resource scoped_collection.friendly.find(params[:id]) rescue activerecord::recordnotfound scoped_collection.find(params[:id]) end end form |f| f.inputs 'blog post' f.input :title f.input :featured_image f.input :body, input_html: { 'data-provider' => "summernote"} f.input :user_id, as: :hidden, input_html: {value: current_admin_user.id} end f.actions end end but not working.

How can I tell gradle-ssh-plugin not to prepend identifier to beginning of output lines? -

Image
i'm using gradle-ssh-plugin execute gradle scripts me on remote host (amazon-linux server running in aws). my gradle script looks like: remotes{ bastion { host = 'bastion.example.com' user = "ec2-user" identity = file("${homedir}/.keypairs/bastion.pem") } } ssh.settings{ knownhosts = allowanyhosts } task sshtest{ dolast{ ssh.run{ session(remotes.bastion){ execute "./gradlew doterraformstuff" } } } } this works fine. here's view of output (the colors terraform tool, executable gradle script invoking): the issue have how plugin prepends bastion#12| each line. "12" number goes each execution (i assume it's kind of plugin state survives invocation because of gradle daemon architecture). the question is: i'd know if there's way tell gradle-ssh-plugin not prepend remote identifier output - i'd see output of commands without prefix stuff.

pip - where to create ansible hosts file in virtualenv? -

i installed ansible pip virtualenv, didn't find hosts file. i have 1 /etc/ansible/hosts , related global install of ansible on system. you can create inventory file anywhere like. just point ansible via -i /path/to/inventory parameter or setting: [defaults] inventory = /path/to/inventory in local ansible.cfg file. ansible searches config file here (in order): ansible_config (an environment variable) ansible.cfg (in current directory) .ansible.cfg (in home directory) /etc/ansible/ansible.cfg

android - Cordova build failed -

i have installed cordova when run $ cordova build in terminal, shows following error. please me out. build failed total time: 8.645 secs error: /home/borsha/hello/platforms/android/gradlew: command failed exit code 1 error output: /home/borsha/hello/android-sdk-linux/build-tools/26.0.1/aapt: 1: /home/borsha/hello/android-sdk-linux/build-tools/26.0.1/aapt: syntax error: ")" unexpected failure: build failed exception. what went wrong: execution failed task ':cordovalib:processdebugresources'. com.android.ide.common.process.processexception: failed execute aapt try: run --stacktrace option stack trace. run --info or --debug option more log output. update build failed total time: 2.799 secs error: /home/borsha/hello/platforms/android/gradlew: command failed exit code 1 error output: /home/borsha/hello/android-sdk-linux/build-tools/25.0.0/aapt: 3: /home/borsha/hello/android-sdk-linux/build-tools/25.0.0/aapt:

jenkins - For Loop to call multiple variables from properties file -

i have properties file call inside jenkins pipeline script multiple variables. buildcounter = n buildname1 = name 1 buildname2 = name 2 ... buildnamen = name n i call properties file with: def props = readproperties file: path now want create loop print buildnames for (i = 0; < buildjobcounterint; i++){ tmp = 'buildname' + i+1 println props.tmp } but of course not working. ne last println call searching variable called tmp in properties file. there way perform or wrong? edit: this .properties file: buildjobcounter = 1 buildname1 = 'win32' buildpath1 = '_build/mbe3_win32' buildname2 = 'empty' buildpath2 = 'empty' testjobcounter = '0' testname1 = 'empty' testpath1 = 'empty' testname2 = 'empty' testpath2 = 'empty' in jenkins pipeline want have possibility check ammount of build/testjobs , automatically calle jobs (each buildname , buildpath freestyle j

scala - XML values gets shifted -

i'm constructing xml below format: <mainentity a={object.value} b={object.value0.ornull} c={object.value1.ornull} d={object.value2.ornull}></mainentity> input before construction: 1) read data nosql db, 2) convert object , construct entity 3) write file. question: in very rare scenario's, see mainentity has 4 attributes. get's populated of time correctly. in scenarios, value of "b" attribute spilled "c" attribute , "c" gets populated in "d" , on!!!! if try reproduce same, doesn't happen. eg: expected: <mainentity a="abc" b="def" c="123" d="abc"></mainentity> in scenarios: <mainentity a="abc" b="d" c="ef" d="123"></mainentity> has encountered this? can throw lights on this?

php - Override function and skip part of the original funtion -

my problem follows. want create override existing method , disable or skip part of code original 1 being executed. inside class extends abstract class, have added same method. can't create new method solve problem, because method different on multiple versions of specific cms system. the part want disable or skip creating override, same in of different versions though. i went through php manual , found pecl apd function override_function. pecl can't used though, because not using plugin i'm trying create, has pecl extention installed php. this have far: public function validateorder($id_cart, $id_order_state, $amount_paid, $payment_method = 'unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, shop $shop = null) { //this part has disabled if (validate::isemail($this->context->customer->email)) { mail::send(

html5 - get image blob after using sanitizer angular2 -

i'm using angular2 dom sanitizer read image file. want upload file firebase storage. however, unable find way convert sanitized image blob or can uploaded. readimage2(inputvalue: any): observable<any> { var file:file = inputvalue.files[0]; return this.ng2imgmaxservice.compress([file], this.maximagesize).mergemap( (result) => { const compressedimage = window.url.createobjecturl(result); const compressedimagetrusted=this.sanitizer.bypasssecuritytrusturl(compressedimage); return observable.create((observer) => { observer.next({imageurl: compressedimagetrusted}); }) }) } in code, want upload compressedimagetrusted file firebase storage. file has type safeurlimpl which i'm not sure how convert can upload firebase storage. appreciated.

c++ - Is there a design patter that can deal with method call dependencies? -

my problem this: when design c++ class, in cases, methods can called after other methods have been called, or after data member has been prepared. i found quite hard deal when there data member dependencies not obvious, , class needs extended support more features , functionalities. error-prone. execution speed of code not important in case, code clarity/maintainability/sensibility more important. if method2 called after method1 class has state. want keep state consistent , methods change/use state should not damage state. so need incapsulation. incapsulation not how make field private , create setfield() method change state. right answer: object change state. if have setters every single field have unprotected object , control consistent state has leaked. in practice, re-desing code data set during previous steps only. in case don't worry checking "is data prepared?" each time method2 called. to avoid untimely calls there several approaches.

sql server - How to use result output columns as objects in MSSQL -

what i'm trying achieve finding out how long retention database backup has using datediff function. in order use datediff need compare, data result, because don't know being anywhere else. why result ? i found out command gives me info need accomplish task (backupfinishdate, expirationdate): restore headeronly disk = 'x:\backups\backuptest.bak' i'm pretty sure i'm not allowed create temp tables in production servers, if 1 option, i'm afraid can't use that. ps! if there's better way find out retentiondays of backup, i'd happily use that. if possible in powershell, better. well, seemed answered own question powershell hint.. gave myself :p solution was: $bkp_start = invoke-sqlcmd -serverinstance myserver -query "restore headeronly disk = 'x:\backups\backuptest.bak'" | select-object -expandproperty backupfinishdate $bkp_end = invoke-sqlcmd -serverinstance myserver -query "restore headeronly disk = &#

mysql subquery limit alternative -

i want select distinct last 200 record. have wrote query this select distinct(server_ip) resource_monitor server_ip in (select server_ip resource_monitor order id desc limit 0, 200 ) but show me error this version of mysql doesn't yet support 'limit & in/all/any/some subquery' what alternative of query? select distinct t1.server_ip (select server_ip resource_monitor order id desc limit 200) t1;

Can I get my bcrypt password in plain form through coding? -

i using bcrypt encryptign password , save db , need give access admin can check password possible in plain form . bcrypt.gensalt(saltrounds, function(err, salt) { bcrypt.hash(myplaintextpassword, salt, function(err, hash) { // store hash in password db. }); }); https://www.npmjs.com/package/bcrypt can bcrypted password in plain form through coding. https://en.wikipedia.org/wiki/bcrypt bcrypt password hashing function designed niels provos , david mazières, based on blowfish cipher, , presented @ usenix in 1999. hashing functions one-way, no, cannot plain text password, , if could, encryption system useless password storage anyway.

mysql - how to assign a mysqli query result value to a php variable? -

<?php $con=mysqli_connect("localhost","user","pass","db"); // check connection if (mysqli_connect_errno()){ echo "failed connect mysql: " . mysqli_connect_error(); } // perform queries $result = mysqli_query($con,"select count(*)\n" . "from information_schema.columns\n" . "where table_name = \'customerstable\'"); $something = mysqli_fetch_assoc($result); echo $something; mysqli_close($con); ?> i want code echo value of something, number of columns in table. don't see printed. doing wrong? your query wrong. below:- <?php $con=mysqli_connect("localhost","user","pass","db"); if (mysqli_connect_errno()){ echo "failed connect mysql: " . mysqli_connect_error(); } $result = mysqli_query($c

sql - Calculate percentage rows over some specific value -

is there oracle function me calculate percentage of rows accepts condition example table: workerid salary departmentid 10001 2000.00 1 10002 2500.00 2 10004 3000.00 1 10005 3500.00 1 i know percentage of workers have salary on 2100.00 per each department you use ratio_to_report : select departmentid, 100 * sum(rr) total_percentage (select t.*, ratio_to_report(1) on (partition departmentid) rr your_tab t) s salary > 2100 group departmentid; dbfiddle demo output: departmentid total_percentage 1 66.66 2 100

c++ - Shortest way to obtain a sublist of a sorted list of values lying in a certain interval -

today asking myself might shortest possible code obtain values in sorted vector std::vector<double> , greater or equal a , smaller or equal b . my first approach following: #include <vector> #include <algorithm> #include <iterator> #include <iostream> // returns values in sortedvalues being greater equal start , smaller equal end; std::vector<double> cutvalues(const std::vector<double>& sortedvalues, double start, double end) { std::vector<double> ret; auto startiter=std::lower_bound(sortedvalues.begin(), sortedvalues.end(), start); auto stopiter = std::upper_bound(sortedvalues.begin(), sortedvalues.end(), end); std::copy(startiter, stopiter, std::back_inserter(ret)); return ret; } int main(int argc, char **args) { { auto ret = cutvalues({ 0.1,0.2,0.3 }, 0.1, 0.3); std::copy(ret.begin(), ret.end(), std::ostream_iterator<double>(std::cout, ",")); std::cout <

html5 - Bootstrap clickable col -

i have 4 column within row, want link. solution? @ snippet below. <section id="projectresources"> <div class="container"> <a class="row" href="#"> <div class="col-sm-3"> <div class="project-resources"> <h4>bacon ipsum dolor amet capicola hamburger chicken short ribs jerky ball tip pancetta chuck </h4> <span class="glyphicon glyphicon-search" aria-hidden="true"></span> </div> </div> </a> </div> </section> you can this: jsfiddle.net <section id="projectresources"> <div class="container"> <div class="row"> <a class="col-sm-3" href="#"> <div class="project-resources">

r - How to fill the black grid with big values in spplot -

Image
i want know how fill color in black grids of following figure 1. value of blank grid greater 100. can fill color in blank grids, legend not symmetric. how modify? lot! here scripts: a<-spplot(nc.data,sp.layout = list("sp.lines", as(china, "spatiallines")), main="all",col.regions = cols(100), @ = seq(-120, 120, 20), + colorkey = list( + right = list( # see ?levelplot in package trellis, argument colorkey: + fun = draw.colorkey, + args = list( + key = list( + @ = seq(-100, 100, 20), # colour breaks + col = bpy.colors(11), # colours + labels = c("\u2264 -100", "-50" ,"0" , "50" , "\u2265 100") + ) + ) + ) + ), + + scales=list(draw = true),par.settings=lis

javascript - Filtering in Vue, nested array -

im trying create computed function can filter out object "alarms", so i've created computed function, called filteredalarms, , in loop im doing v-for loop: <li class="event-log__item timeline__item" v-for="(item, key) in filteredalarms" :key="key"> and in filter im trying following: let filteredalarms = object.keys(this.eventlog).foreach(key => { this.eventlog[key].filter(item => { return item.type.indexof("alarm") > -1 }); }); return filteredalarms unfortunately, doesn't work - im getting error: typeerror: this.eventlog.filter not function what doing wrong? :) the object im trying filter similar 1 below: "system_events": { "1013": [{ "id": 25899, "timestamp": "2017-08-15t21:26:42z", "type": "alarm", "code": 190, "title": "", "desc

c# - Create table inside aspx file -

i want create button line in page. should code below in html. <tr> <td></td> <td></td> </tr> however, using c# , aspx file. here aspx interface code: <%@ page language="c#" async="true" autoeventwireup="true" codefile="translator2.aspx.cs" masterpagefile="~/site.master" inherits="translator2" %> <asp:content runat="server" id="bodycontent" contentplaceholderid="maincontent"> <html></html> <div class="form-group"> <asp:label runat="server" associatedcontrolid="english" id="enlabel" cssclass="col-md-2 control-label">english</asp:label> <div class="col-md-10"> <asp:textbox height="79px" textmode="multiline" width="452px" runat="

c++ - Getting capture date of heic image -

i using nokiatech heif api (github.com/nokiatech/heif) process heic files produced ios betas. i able tiles , metadata rotation , dimensions, unable locate capture date of image. found timestamp functions complain "forced fps not set meta context" leads me think these functions related tracks , not items. any appreciated. edit: so there typo in documentation getreferencedtoitemlistbytype (and getreferencedfromitemlistbytype), says takes "cdcs" referencetype parameter. ofcource "cdsc" (content describe). so metadata blob stil image of can following: reader.getitemlistbytype(contextid, "grid", griditemids); imagefilereaderinterface::idvector cdscitemids; reader.getreferencedtoitemlistbytype(contextid, griditemids.at(0), "cdsc", cdscitemids); imagefilereaderinterface::datavector data; reader.getitemdata(contextid, cdscitemids.at(0), data); then need decode exif. can use exiftool cli or api exiv2.

How to get the exact number of characters in a MS Word document using IronPython -

i'm using word.wdstatistic.wdstatisticcharacterswithspaces object of microsoft.office.interop.word total number of characters in word document. however, got different results in term of total characters declared inside word application, when open , checked manually. here code: import clr import sys clr.addreference("microsoft.office.interop.word") import microsoft.office.interop.word word def count_characters(docfile): word_application = word.applicationclass() word_application.visible = false document = word_application.documents.open(docfile) ranges = document.content ranges.select() total_characters = ranges.computestatistics(word.wdstatistic.wdstatisticcharacterswithspaces) document.close() word_application.quit() return total_characters if __name__ == '__main__': if len(sys.argv) > 1: docfile = sys.argv[1] number = count_characters(docfile) print(number)

ios - How to save a generic custom object to UserDefaults? -

this generic class: open class smstate<t: hashable>: nsobject, nscoding { open var value: t open var didenter: ( (_ state: smstate<t>) -> void)? open var didexit: ( (_ state: smstate<t>) -> void)? public init(_ value: t) { self.value = value } convenience required public init(coder decoder: nscoder) { let value = decoder.decodeobject(forkey: "value") as! t self.init(value) } public func encode(with acoder: nscoder) { acoder.encode(value, forkey: "value") } } then want this: let stateencodedata = nskeyedarchiver.archiveddata(withrootobject: currentstate) userdefaults.standard.set(stateencodedata, forkey: "state") in case currentstate of type smstate<someenum>. but when call nskeyedarchiver.archiveddata , xcode (9 beta 5) shows message in purple saying: attempting archive generic swift class 'stepup.smstate<stepup.routinevie

Search for data block in ElasticSearch -

i have been working elasticsearch new me. logging status messages on external pc send database (this out of reach). collect data giving start , end time make query. challenge me data before query, if make search 17-08-2017 18-08-2017 want see logging happend day before on last hour, cause if change starting date day before query date gives me many results, ideal data block of 200 log rules dynamically changes on scrolling through data. hope question understandable! not sure if current query relevant, please ask me if want :) greetings, bram you need use scan method available under helpers module. gives cursor(iterator) loop on response. helpers.scan(es, query={ "query": { "range": { "date_field": { "gte": "17-08-2017", "lte": "18-08-2017" } } } }, index="my-index", doc_type=&qu

how to get leetcode ranking with goquery -

i want leetcode ranking, know html , javascript little. after lot of try, output. aquayi's ranking ranking: {[{ pc.ranking }]} source package main import ( "fmt" "log" "github.com/puerkitobio/goquery" ) func showranking(username string) { url := fmt.sprintf("https://leetcode.com/%s", username) doc, err := goquery.newdocument(url) if err != nil { log.fatal(err) } ranking, _ := doc.find("div.panel-body").find("span.ranking").attr("data-content") fmt.printf("%s's ranking %v", username, ranking) } func main() { showranking("aquayi") } please me finish code, thank much. func getranking(username string) string { url := fmt.sprintf("https://leetcode.com/%s/", username) fmt.println(url) data := getraw(url) // or way raw html page down str := string(data) := strings.index(str, "ng-init

php - Prestashop custom route module no work -

i try have rewrite url prestashop module. want http://shop.dev/perso/id_customer?token=sdfgh5678terzs so have module file rootofps/modules/hfn_front/hfn_front.php <?php if (!defined('_ps_version_')) exit; class hfn_front extends module { public function __construct() { $this->name = 'hfn_front'; $this->tab = 'others'; $this->version = '1.0.0'; $this->author = 'johan vivien'; $this->need_instance = 0; $this->secure_key = tools::encrypt($this->name); $this->ps_versions_compliancy = array('min' => '1.6.1', 'max' => _ps_version_); $this->bootstrap = true; $this->ps_versions_compliancy['min'] = '1.5.0.1'; parent::__construct(); $this->displayname = $this->l('hfn front'); $this->description = $this->l('test d\'un module d

rest - Nifi:Stopping processor without restApi and wait/notify processor -

i want stop proceesor when fails have generated flowfile related json content: { "status": { "runstatus": "stopped" }, "component": { "state": "stopped", "id": "ea5db028-015d-1000-5ad5-80fd006dda92" } , "id": "ea5db028-015d-1000-5ad5-80fd006dda92", "revision": { "version": 46, "clientid": "ef592126-015d-1000-bf4f-93c7cf7eedc0" } } and have related groovy code in executescript processor : import org.apache.commons.io.ioutils import java.nio.charset.* def flowfile = session.get(); if (flowfile == null) { return; } def slurper = new groovy.json.jsonslurper() def attrs = [:] map<string,string> session.read(flowfile, { inputstream -> def text = ioutils.tostring(inputstream, standardcharsets.utf_8) text=flowfile.getattribute(&#

amazon web services - Custom redirection rules on S3 returns 403 when using CloudFront -

i have custom redirection rule bucket on s3: <routingrules> <routingrule> <condition> <keyprefixequals/> <httperrorcodereturnedequals>404</httperrorcodereturnedequals> </condition> <redirect> <protocol>https</protocol> <hostname>example2.com</hostname> <replacekeyprefixwith>services/create?key=</replacekeyprefixwith> <httpredirectcode>307</httpredirectcode> </redirect> </routingrule> </routingrules> and bucket has proper policy: { "version": "2008-10-17", "statement": [ { "sid": "publicreadforgetbucketobjects", "effect": "allow", "principal": { "aws": "*" }, "action": "s3:getobject", "

rest - Token error when sending Wechat message with Python -

i have wechat subscribe page, , set in https://admin.wechat.com/ token webhook url of server myserver.com/wechat/webhook my server python code authenticates wechat server signature check, nonce , timestamp , i'm able receive messages wechat webhook. but can't send messages server wechat, i'm using following code , token set in admin console previously, , following previous docs: http://admin.wechat.com/wiki/index.php?title=customer_service_messages # parse received wechat message message = xmltodict.parse(message) content = message['xml']['content'] fromuser = message['xml']['fromusername'] touser = message['xml']['tousername'] createdtime = message['xml']['createtime'] # reply message post_data = { "touser": fromuser, "msgtype": "text", "text": { "content": "thanks message" } } api_url = 'https://api.wechat.com/

eclipse - JAVA For Loop running out of memory when running though image files -

i loading 100 fits images of 3000x2000 pixels , converting pixel values each image matrix , rescaling matrix , adding each 1 set. but running out of memory in heap. set of int matrices shouldn't take memory should it? (the heap 2gb believe, @ least eclipse uses 2gb before giving error.) so thinking each new fits object being stored in memory after each loop. isn't needed again after loop finishes don't know why case. is there way without running out of memory? there different number of fits files each time program run. public set<int[][]> rescalefitslist(file[] fitsfilelist){ set<int[][]> rescaledfitsset = new hashset(); for(file fits: fitsfilelist){ fits f = new fits(fits); double bscale = f.gethdu(0).getbscale; double blinear = f.gethdu(0).getblinear; short[][] counts = (short[][])f.gethdu(0).getkernel(); int[][] rescaledfits = new int[counts.length][counts[0].length]; for(int =0,

javascript - Error: Datepicker: value not recognized as a date object by DateAdapter -

from yesterday i'm struggling problem angular material 2 datepicker, before last npm install working , get: error error: datepicker: value not recognized date object dateadapter. holidayrequestcomponent.html:21 21st line <input starts <md-input-container [formgroup]="daterangeform"> <input mdinput name="date_from" [mddatepicker]="from" placeholder="start date" formcontrolname="holidaydatacontrol" [ngmodel]="date_from" > <md-datepicker-toggle mdsuffix [for]="from"></md-datepicker-toggle> </md-input-container> <md-datepicker #from></md-datepicker> my component.ts: import {component, oninit, inject } '@angular/core'; import {md_dialog_data, mddialog } '@angular/material'; import {formbuilder, formcontrol, formgroup, ngform, validators} '@angular/forms'; import {observable} 'rxjs/observable'; @comp

image - jquery - picture element swap in ie 11 -

hi using piece of jquery swap background images via picture element depending on viewport width. works in mst browser except ie 11. does have idea why? appreciated. in advance. function setimgbackground(){ $('.banner-item').each( function(){ var $this = $(this); var picture = $this.find('picture').get(0); var src = picture.getelementsbytagname('img')[0].currentsrc; $(this).css({ 'background-image':'url('+src+')' }); }); } <ul class="bannercontainer"> <li class="banner-item full about"> <picture> <!--[if ie 9]></video><![endif]--> <source srcset="https://via.placeholder.com/1664x412? text=desktop_1664x412" media="(min-width: 960px)"> <source srcset="https://via.placeholder.com/768x500?text=tablet_768x500" media="(min-width: 768px)"> <source srcset="https://via.placeholder.com/414x500?te

php - how to update product information outside from Magento -

i want programmatically update product information, such quantity, price, etc. (from outside of magento source directory.) how can that? magento pretty easy bootstrap. if want standalone script can access functions, add following @ top of php file : define('magento', realpath(dirname(__file__))); require_once magento . '/../app/mage.php'; //or whatever location mage.php file mage::app(mage_core_model_store::admin_code); //initialization store possible after can load models. update products suggest 2 ways. regular 1 : mage::getmodel('catalog/product')->setstoreid($mystoreid)->load($myproductid) ->setprice(50) ->save(); or api model usage : $api = mage::getmodel('catalog/product_api_v2'); $api->update($productid, $productdata, $store, $identifiertype);

new() keyword in the base declaration statement in C# -

this question has answer here: what “where t : class, new()” mean? 11 answers i wonder below new() keyword. new() in base declaration statement along idisposable c : dbcontext , idisposedtracker. but wonder new() expression. anonymous base class declaration? but notice couple of arrow marked next new(). curly brackets owned public class repositorybase, not new(). what new() here? namespace personrepository { public class repositorybase<c> : idisposable c : dbcontext, idisposedtracker, new() ->{ public repositorybase() { datacontext.database.createifnotexists(); } private c _datacontext; public virtual c datacontext { { if (_datacontext == null || _datacontext.isdisposed) { _datacontext = new c();

after effects - Element3D - Sand Timer -

i have create sand timer money pouring through rather actual sand. did think relatively easy, pop 3d model in e3d (done, works fine) , have money particles inside. however, i'm getting little unstuck - there way generate particles , have them flow down correctly inside 3d object? i bodge honest, however, rather try , have particles moving down correctly. if has suggestions love hear them , give them go - have searched web possible solutions, think little obscure

java - Unable to import project in eclipse: "Impossible to find or load the main class" -

i've imported this project on eclipse workspace. after time spent find correct jar dependencies, i've tried run project, says me it's impossible find or load main class. to import project, downloaded , imported on eclipse using file -> import. there problems dependencies (there classes eclipse couldn't find), downloaded jars of these dependencies , included in project. this code of mainclass : package com.yeokhengmeng.docstopdfconverter; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import org.kohsuke.args4j.cmdlineexception; import org.kohsuke.args4j.cmdlineparser; import org.kohsuke.args4j.option; public class mainclass{ public static final string version_string = "\ndocs pdf converter version 1.7 (8 dec 2013)\n\nthe mit license (mit)\ncopyright (c) 2013-2014 yeo kheng meng"