Posts

Showing posts from September, 2012

arrays - Converting String of Zero's and One's to binary byte Python -

i have code using convert file bytes bytes strings of 0's , 1's. with open(file, mode='rb') file: content = file.read() b = bytearray(content) number in b: data = bin(number)[2:].zfill(8) print data i output 10110100, 00000001, etc, etc should be. i want take strings of bits in output , convert them bytes, write bytes new file. i have tried following code: list = ('11111111', '11111110', '01101000', '00000000', '01101001', '00000000', '00001101', '00000000', '00001010', '00000000') def writer(stuff): blob = struct.pack('!h', int(stuff, 2)) open('test.txt', "a+b") file: file.write(blob) strings in list: writer(strings) the original text file contains word "hi" , all, when write new file output "▒▒hi"

ruby on rails - How to validate the presence of attributes when updating a record? -

i new rails , try find validation method corresponding validate presence of attribute when updating record. if attribute not present, meaning attribute not exist request body, rails should not update record. validates :description, presence: true and validates_presence_of :description doesn't seem job. there method purpose? seems quite common in every day scenarios. if say: model.update(hash_that_has_no_description_key) then you're not touching :description : sending hash without :description key update not same sending in hash :description => nil . if model valid (i.e. has description) update won't invalidate because won't touch :description . you this: if attribute not present, meaning attribute not exist request body, rails should not update record. since you're talking request body (which models shouldn't know about) should dealing logic in controller prepares incoming data update call. you check in controller ,

asp.net - Regex for Range $5,000 - $1,000,000 (with commas and dollar sign optional) -

i need creating regex number range of 4,000-1,000,000 commas , dollar sign being optional user. i'm trying annotate validation departments budget using asp.net regular expression or custom validator permits optional dollar sign , commas range $5000.00 $1,000,000 ^\$?([5-9][0-9]{3,5}|1000000)$ sadly, didn't work it's came with, appreciated! is solid choice, if notice ending more simple way being of second 1 down below ,? make shorter in length. ^(?:5,?\d{3}|[6-9],?\d{3}|[1-9]\d{1,2},?\d{3}|1,000,000|1000000)$ vs ^\$?([5-9],?\d{3}|\d{2,3}?,?\d{3}|(?:1,?000,?000))$ the second 1 lot cleaner , can tell works fully.

Python: How to convert a large zipped csv file to a dictionary? -

i had following code working convert csv file dictionary. with open(filename, encoding='utf-8') file: dictreader = csv.dictreader(file) row in dictreader: #do work these csv files arrive zipped , figured i'd attempt modify code read zipped csv files dictionary. things tricky since understand it, when opening file inside zip archive, file opened bytes rather text. had working reading entire file in, , converting text, hit large file , had memory error. updated code read file in 1 line @ time , suspect i'll have build dictionary manually, figured worth asking here. thanks pmsh.93, have working. with zipfile.zipfile(filename) zipfile: fname in zipfile.infolist(): zipfile.open(fname) file: file = io.textiowrapper(file, encoding="utf-8") row in csv.dictreader(file): #do work

jquery - movehover from Selenium on a dropdown -

below code in html <div id="pmenu_root_10" class="itemborder" style="position: absolute; left: 809px; top: 0px; width: 58px; height: 98px; z-index: 1000; background: rgb(190, 213, 231) none repeat scroll 0% 0%; cursor: default;" onmouseover="pmenu.over('root',10)" onmouseout="pmenu.out('root',10)" onclick="pmenu.click('root',10)"> <div class="lowtext" style="font-size: 11px; font-family: arial; color: #0066cc; position: absolute; left: 1px; top: 1px; width: 56px; height: 96px">reports</div> </div> i trying hover mouse selenium can select 1 of sub menu present. selenium not able element webelement ele = driver.findelement(by.xpath(".//div[@id='pmenu_root_10']/div[text()='reports']")); actions act = new actions(driver); act.movetoelement(ele).perform(); i tried using abosulte xpath given firepath .//*@id='login

ios - uipageviewcontroller disable right swipe -

i have uipageviewcontroller 4 individual view controllers in it. want disable right swipe action first view controller , disable left swipe action fourth view controller. when app launches, want user able swipe left , not right, because swiping right, takes user fourth view controller , swiping left on fourth view controller takes user first view controller. here code. class tutorialpageviewcontroller: uipageviewcontroller, uipageviewcontrollerdatasource, uipageviewcontrollerdelegate { weak var tutorialdelegate: tutorialpageviewcontrollerdelegate? lazy var vcarr: [uiviewcontroller] = { return [self.vcinstance(name: "firstvc"), self.vcinstance(name: "secondvc"), self.vcinstance(name: "thirdvc"), self.vcinstance(name: "fourthvc")] }() private func vcinstance(name: string) -> uiviewcontroller { return uistoryboard(name: "main", bundle: nil).instanti

Trouble with parsing and "doing math" with numbers (A simple java calculator) -

i attempting take simple string statement , parse print out simple answer. so far, cannot figure out why consistently getting wrong answers. say example - plug in string "2 * 3 * 4 * 5 / 2 / 3 / 2". the expected answer 10, receive answer of 1.5 can see issue here? assume not case of order of operations (i have not got far yet). public class testingforexcel { static string tableholder = "2 * 3 * 4 * 5 / 2 / 3 / 2"; public static void main(string args[]){ string[] fracequationholder = tableholder.split(" ",tableholder.length()); // holds fractions , operator string operators = ""; double operand; double operand2; double answer = 0; for(int =0; <= (fracequationholder.length-2); i+=2){ operators = fracequationholder[i+1]; operand = double.parsedouble(fracequationholder[i]); operand2 = double.parsedouble(fracequationholder[i+2]); i

pyqt4 - python matching files from one list with files from another list based on name -

i learning python , programing in general , need assistance. i wrote python script reads 1 file, unique values, opens second file , and uses unique values makes calculation(script long upload) created gui using pyqt4 allowed user browse clicking qpushbutton , stored file path in qlineedit set file in script f1 = self.lineedit.text() , f2 = self.lineedit2.text worked however, need allow user select multiple files , match every file 1 corresponding file 2 since dependent on each other here updates made widget functions accept multiple files: def first_file_set(self): dlg = qfiledialog() files = dlg.getopenfilenames() self.listwidget.additems(list(files)) def second_file_set(self): dlg = qfiledialog() filenames = dlg.getopenfilenames() self.listwidget_2.additems(list(filenames)) def clearf(self): item in self.listwidget2.selecteditems(): self.listwidget.clear() def clears(self): item in self.listwidget.selecteditems():

c - How can I get a gstreamer pipeline by name? -

if pipeline created gstelement *pipeline = gst_pipeline_new (session_id); on server whenever user visits http://myurl.com/new?session_id=123&file_path=/vids/vid.mp4 (mp4 videos streamed rtmp server), how can use name of pipeline "123" set pipeline state not playing when user visits http://myurl.com/to_not_playin?session_id=123 ? each visit http://myurl.com/new launches gstreamer in new thread (because webserver asynchronous , want multiple users use platform) different elements/pads created , linked. there no way pipeline name generically in gstreamer, should store name -> pipeline map if need it.

Difference between '|' and '+' in bit manipulation -

i want use 00 , 01 , 10 , 11 represent a , b , c , d . assuming have string, want express substrings length 5. can express aaabb 0000000101 . now, have string s , integer mark used represent substring of s . when add b substring mark = mark<<2 | 1 question what's difference between mark = mark<<2 | 1 , mark = mark<<2 + 1 might depend on language using (please add tag next time!), typically operator precedence be: + << | so comparing (mark << 2) | 1 , mark << (2+1) . expect totally different results. if question | (bitwise or) , + (addition), encourage learn each operator does, , come more specific question. in case wondering: (mark << 2) | 1 , (mark << 2) + 1 return same result, because left-shift guarantees last bit zero.

Gnuplot calculate slope and convert to angle for label alignment -

Image
i'm working colleague's gnuplot script internal reporting do, , i'm learning lot awesome tool have dabbled in past. i'm refactoring code can change global variables drive plot, annual targets , on. have managed gnuplot resize chart automatically based on targets. easy: set yrange [0:${coursetarget}*1.2] set y2range [0:${attendancetarget}*1.2] what now, automatically adjust angle of rotation of label based on slope of arrow (e.g., arrow plots gradient of annual target of courses delivered), have no idea how 1 that. i have arrow from graph 0, graph 0 graph 1, second ${target} , slope bottom-left point on right-side of plot depending on target (fed in bash var). i've manually rotated label ('target line') 16º, right now, if chart area changes, i'll have figure out angle trial-and-error on again. so before start boning on trigonometry, thought i'd ask whether gnuplot has built-in way of taking arrow , returning gradient, calculate angle o

c - Where is local data defined inside a function stored at startup -

i understand global data stored in .bss or .data segment. if have data such structure defined inside function however, structure placed on stack when function called. where compiler store data @ startup tho before function called? know compilers generate different assembly code depending on target , calling conventions etc. , generally, wouldn't local structure have stored somewhere first compiler knows how put on stack when function called? in advance. in case of global variables (also static local): compiler accesses global variables memory parts of address , size. address placeholder (much name of variable). size implicit, depending on kind of access compiler has chosen in assembly/machine-code. linker/loader aware of size, makes sure next variable not overlapping. address placeholder gets replaced during linking (e.g embedded, static, execute-in-place) or loading (e.g. programs on pc, apps). in case of local variables: "address" value, gets wri

python - Length mismatch: Expected axis has 218 elements, new values have 230 elements -

i have been accessing pandas data frame, , error keeps popping up. cases_expand = [] case in cases_ii: output = case[-1][0] month = case[-1][1] features = [v[0] v in case[0:-1]] + [month] + [output] cases_expand.append(features) feat = ["h_", "r_", "in_umiray_", "in_angat_", "out_nia_", "out_mwss_"] cases_df2 = pd.dataframe(cases_expand) col_names = [] f in feat: if f != "out_nia_" , f != "out_mwss_": in range(batch_size): col_names.append(f+str(i+1)) else: in range(look_back + batch_size): col_names.append(f+str(i+1)) col_names += ["month", "output"] #print (col_names) cases_df2.columns = col_names print (col_names) the error is: length mismatch: expected axis has 218 elements. new values has 230 elements.

function - postgresql check session config setting availability -

i have sensor data table full of 'holes', data saved when changes on specified threshold. | time stamp | value1 | value2 | | 2012-01-01 | 1 | | | 2012-01-02 | | 2 | | 2012-01-05 | | | | 2012-01-20 | | | | 2012-03-01 | 3 | 1 | i need cross row calculations, holes in tables make impractical. solution create auxiliary function wrap related field, , use session parameter persistent variable. sth this: create function wrap_data( data1 numeric(3,1) ) ... language plpgsql if data1 <> null execute 'set session app.data1 = $1;' using data1; end if; return current_setting('app.data1')::numeric(3,1) ... it works before executing function, have initialized variables outside of function by: set session app.data1 = 11.1; or complain parameter not unrecognized. i looking function ifparameterexist(), allow me check existence of variable without raising error inside plpgsql function.

ios - How to convert base64 image embedded in XML to UIImage? -

Image
how can convert base64 data embedded in xml shown in screenshot below, uiimage? first of need parse xml. on ios there no nsxml , need use nsxmlparser instead, primitive event-driven callback parser (opposed complex tree parser use in macos). so let's define sample data: let xmlstring = "<base64binary xmlns=\"testtesttest\">" + "/9j/4aaqskzjrgabaqeasabiaad/2wbdaa0jcgskca0lcgsodg0peyavexis" + "eycchhcglikxmc4plswzoko+mzzgnywtqfdbrkxoulnsmj5ayvpqyepruk//" + "2wbdaq4odhmreyyvfszpns01t09pt09pt09pt09pt09pt09pt09pt09pt09p" + "t09pt09pt09pt09pt09pt09pt09pt0//waarcabaabwdasiaahebaxeb/8qa" + "ggaaagmbaqaaaaaaaaaaaaaaawucbayaaf/eacwqaaibawmcbaufaaaaaaaa" + "aaecawaeequsitfbbijhcrmuuyghfsnckeh/xaaxaqebaqeaaaaaaaaaaaaa" + "aaadagqa/8qahreaagicaweaaaaaaaaaaaaaaaecerihayixmv/aaawdaqac" + "eqmrad8avwmqksvifbarkkz4+g9ajejbwmiljjmzn6ozezhrqi5jyl

indexing - How to remove Scripts and Styles in content of SOLR Indexes[content field], while indexed through URL? -

whenever solr indexed collection ( configset sample_techproducts_configs ) , using url, via following command: bin/post -p 8983 -c collection https://www.mywebsite.com -recursive 3 the indexes created have field content copied text field. field have value of content of web page parsed using embedded tika parse. but, when webpage contains <script> or <style> tag <body> removed script or styles inside respective tags remains content of webpages, , shown in response solr queries. how remove these unwanted content ? do read inputstream of data_mode_web in simpleposttool (only whom content type "text/html" , remove <script> , <style> tags content , again convert content_string stream using stringtostream(string) in readpagefromurl(url u) function.

wpf - How to Binding composition based Observable Collection? -

say model looks shown below, public class organization private string _organizationname; private list<employee> _employees; private list<contractor> _contractors; public string organizationname { { return _organizationname; } set { _organizationname= value; } } public list<employee> employees { { return _employees; } set { _employees = value; } } public list<contractor> contractors { { return _contractors; } set { _contractors = value; } } } } public class employee { public string name { get; set; } public int empid { get; set; } public double salary { get; set; } } public class contractor { public string name { get; set; } public int contractorid { get; set; } public double experiancecredit { get; set; } } i have 1 vie

classification - How to add new custom category in imagenet tutorial sample in Tensorflow? -

i new tensorflow. have tried mnist example , trying out imagenet tutorial examples. have run imagenet classification example , able classification sample panda image , several others. want add new category (say traffic signs) in pretrained inception_v3 model. don't know input train image formats nor how properly. far have learned save variables checkpoint directory using saver: saver = tf.train.saver(max_to_keep=20, keep_checkpoint_every_n_hours=1) saver.save(s, ssavepathfilename) ... path = tf.train.get_checkpoint_state(checkpoint_dir) saver.restore(sess, path.model_checkpoint_path) i used above snippet save , restore mnist model. inception_v3 pretrained, i'm little confused on how use in sample code given in classify_image.py understand far that, in order train pre-trained inception_v3 custom category need create checkoint first train on images. need save images this: ls {image_path}/traffic-signs speed-breaker-sign.jpg right-turn-sign.jpg left-turn-sig

swift - Saving Alamofire request data into a variable -

i'm having troubles getting password salt vm server via alamofire . i'm making request server , should return me salt, can salt password, hash , send server. the problem not understand how save salt, alamofire receives, variable, can add password , hash that: let salted_password = user_password + salt let hash = salted_password.sha1() where user_password user entered password field , salt got alamofire salt request. here code: func getsalt(completionhandler: @escaping (dataresponse<string>, error?) -> void) { alamofire.request("http://192.168.0.201/salt", method: .post, parameters: salt_parameters).responsestring { response in switch response.result { case .success(let value): completionhandler(response dataresponse<string>, nil) case .failure(let error): completionhandler("failure", error) } } } let salt = getsalt { response, responseerror i

python - How do I print the first and last value? -

the below part code prints host ip address lies in subnet, want modify code prints starting address , last address of list how use array here print first , last value? import ipaddress print('enter subnet') # in cidr format x = input() ip= ipaddress.ip_network(x, strict = false) y in ip.hosts(): print(y) current output enter subnet 192.0.0.0/29 192.0.0.1 192.0.0.2 192.0.0.3 192.0.0.4 192.0.0.5 192.0.0.6 desired output hostmin: 192.0.0.1 hostmax: 192.0.0.6 ========================================= update: after using list able print first , last values however takes quite longer compute whenever give large subnet 192.0.0.0/8 takes longer print first , last value, for: ipv6 address calculations hangs forever, for: example: ipv6 address 2001:db8::1/96 list have 4294967294 elements since ipv6 subnet has these many ip address , hangs forever print first , last element of list list[0] , list[-1] gets first , last element respectively

c# - differential compression of multiple arrays -

i have multiple arrays have same length. contain changing data. example: var array1 = new int[] { 1, 2, 3, 4, 5, 6 }; var array2 = new int[] { 23, 2, 3, 4, 5, 6 }; var array3 = new int[] { 23, 2, 97, 4, 5, 6 }; var array4 = new int[] { 23, 2, 97, 4, 5, 81 }; var array5 = new int[] { 23, 2, 97, 4, 64, 81 }; i have several thousands of arrays, , want optimize memory footprint after creation of them. i thought use compression algorithms known video compression (some key frames , many differential frames). not able find available in c#. i need able access content of single arrays after compressed. instance, after compressed, want able say: "give me content of second array." , want numbers 23, 2, 3, 4, 5, 6 can give me hint how can compress arrays? favor compression audio or video compression key frames , differential frames.

join - Merge very large csv using pandas or awk -

i have 2 csv below (tried read them through pandas) df1 file 17gb (i read through pandas read_csv) , df2 700mb, want merge using trig_seq . python gets killed. there way through awk/join >>> df1.head() streamid seqnum timestamp_p1 trig_seq 1 1 14914503 10000000001 1 2 1491450 10000000002 1 3 1491450 10000000003 1 4 1491450 10000000004 1 5 149145 10000000005 >>> df2= pd.read_csv("/tmp/my.csv") >>> df2.head() model_id order ctime trig_seq e62 1000000 1493311414272 30021182183 e62 1000001 149199641344 30021210134 e22 1000002 1491081210880 30021227875 e62 1000003 14951949824 30021239627 e62 1000004 14927136256 30021241522 >>> r1 = pd.merge(df1,df2) killed try -

How to export mlab database to meteor application -

i have created mlab database. unable export meteor application.everytime try connect, throws error "mongoerror: failed connect server [ds035693.mlab.com:35693] on first connect".command using "export mongo_url= mongodb://<dbuser>:<dbpassword>@ds035693.mlab.com:35693/abcd" i think don't need " " around export. put in terminal export mongo_url= mongodb://<dbuser>:<dbpassword>@ds035693.mlab.com:35693/abcd replace id , password. and console.log(process.env); in startup function check if mongo_url set or not. if set. may network issue. you may forgot add database user in user tab collection in mlab. hope help

php - Try catch private method phpunit symfony -

i have following code: public function addsomething($paramdto) { try { $this->privatemethod($param); } catch(\exception $e) { return ['error' => true, 'messages' => [$e->getmessage()]]; } return ['error' => false, 'messages' => 'success']; } private function privatemethod($param) { if(!$param) { throw new \exception('errormessage'); } } i'm trying test addsomething method, catch block returns, don't want test private method. public function testaddsomethingthrowerror($paramdto) { $param = \mockery::mock('myentity'); $method = new \reflectionmethod( 'myservice', 'privatemethod' ); $method->setaccessible(true); $this->expectexception(\exception::class); $this->getmyservice() ->shouldreceive($method->invoke($param) ->withanyargs() ->andthrow(\exception::class);

javascript - Trumbowyg not formatting text (Bold, Italic, Strikethrough) -

i'm using trumbowyg wysiwyg text editor http://alex-d.github.io/trumbowyg/ the buttons i'm using bold, italic, strikethrough , insertimage. right now, button works insertimage. when select text , apply bold, italic or strikethrough, nothing. when post submitted, doesn't render bold, italic or strikethrough. plain text. keep in mind rendered post has safe template filter: {{instance.content|safe}} when remove safe , doesn't render formatting renders actual html this: <strong>text</strong> regardless of this, when making post text editor doesn't format properly: **bold text** it this: bold text the thing renders insertimage. when insert image shows immediately, , renders fine after posting. any idea why other formatting doesn't work?

Python 3.x BeautifulSoup crawling image URLs -

i try crawling image urls google image search window. but got 20 urls want more urls 20 should do? source code def get_images_links(searchterm): searchurl = "https://www.google.com/search?q={}&site=webhp&tbm=isch".format(searchterm) data = requests.get(searchurl).text soup = beautifulsoup(data, 'html.parser') img_tags = soup.find_all('img') imgs_urls = [] img in img_tags: if img['src'].startswith("http"): imgs_urls.append(img['src']) return(imgs_urls) get_images_links('black jeans')

HTML CSS hover not working -

today trying achieve animated icon, got in trouble css. upcomming code more can say: .menu { width: 100%; height: 50px; position: fixed; background-color: #35f5ca; top: 0; left: 0; } .title { font-family: "sans-serif"; position: fixed; top: 1%; left: 0; vertical-align: middle; font-size: 150%; color: white; } .icon:hover { width: 45px; height: 45px; position: fixed; right: 0px; top: 0px; opacity: 1.0; } .body {} <div class="menu"> <p1 class="title"> <b> mettu </b> <img class="icon" src="images/iconplanet.png" style="transition: 0.5s; width:40px; height:40px; position:fixed; right: 5px; top: 0.5%; opacity: 0.5;" /> </p1> </div> <div class="body"> </div> please don't correct code, , tell me did wrong. thank you! add style css, , .menu shou

TYPO3 Add new tab to fe_user -

i begin develop on typo3 version 7.6.16. use extension femanager. problem next: i want add new tab frontenduser page on backend described in link https://docs.typo3.org/typo3cms/extensions/extension_builder/developer/extendingmodels.html my goal simple: add new tab 2 fields (selected items , available items) described on link.

c# - "Resource Not Found" error on deleting document from documentdb -

i having issue deleting document form document db. code trivial , not doing fancy. getting self link of document , using self link delete giving me exception. await client.deletedocumentasync(entity.selflink, new requestoptions() { partitionkey = new partitionkey(partitionkey) }).configureawait(false); entity newly added document exists in database (i have checked existence azure portal) the exception getting: message: {"errors":["resource not found"]} activityid: 052ad225-4e04-4757-89b8-51f6ccf55f7c, request uri: https://sy3prdddc05-docdb-1.documents.azure.com:15236/apps/0ee0095b-872d-45bc-8739-67cfbd97db79/services/466a4dd1-27d3-45ca-b013-6875f06a38ab/partitions/73e5c3d8-0332-4c0c-9aec-47a3469ba958/replicas/131354346050636923p//dbs/l29haa==/colls/l29hakzfjwa=/docs/l29hakzfjwafaaaaaaaaaa== any idea?? i found issue! name of partition key specified collection pascal case not camel case! , apparently case sensitive couldn't find part

javascript - Can not add class dynamically in a tag using Jquery -

i need help.i not add class dynamically using jquery. explaining code below. $.each(obj.cid, function() { $("#ulcategory").append("<li><a href='javascript:void(0)' onclick='savesubcat("+this.id+","+this+")'>" + this.name +</li>"); }); function savesubcat(id,$this){ $($this).addclass("active"); $($this).siblings().removeclass('active'); } here need add active class on clicked anchor tag in way not happening this.please me. your first issue you're not wrapping string value in quotes in function call. second problem that, context, this object. concatenating object string isn't going work expect. to fix far better use unobtrusive delegated event handler. way this reference within handler function anyway, don't need pass it. need put id object in data attribute can read within event handler. also note this refer a element has no siblings. add cla

javascript - Highcharts - Highlight above part of column chart -

all, i have requirement want highlight above part of bars column chart. more expressive attaching image need do. image thank in advance edited : what did have given 2 series , stacked them. series: [{ name: 'background', data: [250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250], color: 'rgba(94, 143, 184, 0.5)', datalabels: { enabled: false } }, { name: 'actual', data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], color: '#ffffff', datalabels: { enabled: false } }] what looking neater solution can use 1 series , use control highchart can fill remaining part full length. there no feature this, can extend highcharts method, in case - seriestypes.column.prototype.drawpoints - harder creating non-responsive second serie

java - Spring-MVC : How to ensure multiple users will be able to call a method in sequence -

i working on spring-mvc application in have method updates contents of object. method requires lot of processing , can called multiple users updating same object. how can ensure method gets updated in sequence triggered each user, , none of user has stale data while updating. service layer method : @transactional @service private groupnotesserviceimpl implements groupnotesservice{ @override public string editnotewithmap(map<string, object> notemap) { person person = this.personservice.getcurrentlyauthenticateduser(); if ((notemap != null) && (!notemap.isempty())) { int noteid = (integer) notemap.get("id"); // how ensure below object not stale. groupnotes databasenoteobject = this.groupnotesdao.getgroupnotebyid(noteid); { // process map } // update object below : this.groupnotesdao.editgroupnote(databasenoteobject, databasenoteobject.getownedsectionid()); } dao layer method : @repository @transact

reactjs - React Router isActive doesn't work for child route -

i have following router <route path="/" component={app}> <indexroute component={home}/> <route name="events" path="/events" component={events}> <route path=":eventid" component={details}/> </route> </route> and following link: <link to={'/events'}> when browse /events/1234 , this.context.router.isactive(this.props.to, true) returns false . i tried configuration, it's same: <route path="/" component={app}> <indexroute component={home}/> <route name="events" path="/events" component={events}> <route path="/events/:eventid" component={details}/> </route> and tried <link to={'events'}> (without / ) no more success. idea how isactive true when browsing /events/1234 ?

sql - Match Two Select Statements for Comparison -

i have 2 sql views following select statements: 1. select substring(updatedcolumn,3, 9) [partialsearch] [database_name].[dbo].[table] 2. select substring(oldcolumn,3, 9) [partialsearchonlivetable] [same_database_name].[dbo].[differenttable] both these views return 1 column respectively. want compare values in first view against values in second view , return updatedcolumn data match not found. i have considered using comparison operators can't seem want since according logic, have specify conditional checking of views against each other in clause , sql not permit that. also, union/union give me result set of records. don't want. lastly, had @ combine 2 select statements date comparison , not i'm looking for. practically, view 1 returns : abcxxxxxx dokjfhxxx cmodxxxxx wuysxxxxx aaallooxx view 2 returns: xdsffsafa xxxxhjsks ajdhxxxxx cmodxxxxx xxxxxx12s skskshdki aaallooxx from output see there 2 matches. of aaallooxx cmodxxxxx that's out

asp.net mvc - C# MVC 5 The ticket cookie is cleared when the form authentication signs out -

i need access cookies user , password , set them in text boxes of login view because in view checked "remember me". logoff method public actionresult logoff() { //session.abandon(); // sign out. formsauthentication.signout(); return redirecttoaction("index", "login"); } initialization of sessions , cookies after successful login. private void initializesessionvariables(agentdto user) { // sessionmodel.agentid = user.id; response.cookies.clear(); formsauthenticationticket ticket = new formsauthenticationticket(1,user.mobilephone,datetime.now,datetime.now.adddays(30),true,"",formsauthentication.formscookiepath); // encrypt ticket. string encryptedticket = formsauthentication.encrypt(ticket); // create cookie. httpcookie authenticationcookie = new httpcookie(formsauthentication.formscookiename, encryptedticket); // name of auth cookie (it's name specified in web.config) // hashed ticket

javascript - Default Value in react-select -

i have react-select component made compatible redux-form. selectinput component this: const myselect = props => ( <select {...props} value={props.input.value} onchange={value => props.input.onchange(value)} onblur={() => props.input.onblur(props.input.value)} options={props.options} placeholder={props.placeholder} /> ); and render in component form <div classname="select-box__container"> <field id="side" name="side" component={selectinput} options={sideoptions} value="any" clearable={false} // placeholder="select side" /> </div> i've set initial values container state component has initial value , it's working. problem when render component initial value not show in selection box , it'

phpmailer - Heroku's mailgun account says temporarily disabled -

heroku's mailgun account says temporarily disabled. " business verification required". how do verification start sending mails through heroku app. you can find information here (first result google search "business verification mailgun")

powerpivot - Excel: automatically replicate number of lines -

i have huge table1 many columns. need bring on information table2 which: only has 10 columns values in these columns calculated (e.g. if/then, index/match, etc) currently "=table1[xxx]" , incorporate in needed formula, i.e. table2 has exact number of rows table1. problem: data in table1 refreshed weekly, i.e. new lines appear. how can make table2 automatically take number of lines/entries table1 has? made table2 2 times longer, results in value errors prevents me using pivot tables. think solution can done using powerpivot connections i'm stuck regards how it.

php - laravel print json without converting to htmlentities -

hi new templates , laravel. i have changed laravel delimiters [[]] , [[[]]] using blade::setcontenttags("[[", "]]"); blade::setescapedcontenttags("[[[", "]]]"); now want pass json javascript variable like var somevariable = [[json_encode($variablefromcontroller)]]; but converts json string html entities {&quot;index&quot;:200} i searched , found {{!!json_encode($variablefromcontroller)!!}} should work doing in system [[!!json_encode($variablefromcontroller)!!]] not makes impact. i know can <?php echo json_encode($variablefromcontroller) ?> last thing want try. there laravel specific thing can do? at first blade::setcontenttags("[[", "]]"); means replace {!! [[ . , blade::setescapedcontenttags("[[[", "]]]"); replacing {{ [[[ . so condition [[ json_encode($variablefromcontroller) ]] equivalent {!! json_encode($variablefromcontroller) !!}

directions for use javacc token -

i want distinguish multiple tokens. @ code. token : { < loops : < beat > | < bass > | < melody > > | < #beat : "beat" > | < #bass : "bass" > | < #melody : "melody" > } void findtype(): {token loops;} { loops = < loops > { string type = loops.image; } i want use findtype () function find type. how can return correct output when input "beat"? what want add return statement, this: string findtype(): {token loops;} { loops = < loops > { string type = loops.image; return type; } } have in mind have changed return value definition in method, void string . then, main: examplegrammar parser = new examplegrammar(system.in); while (true) { system.out.println("reading standard input..."); system.out.print("enter loop:"); try { string type = examplegrammar.findtype(); syste

python - Trouble with encode + encrypt + pad using same code for python2 and python3 -

disclaimer: understand following not suited give "security" in production environment. meant "a little bit better" using xor or rot13 on sensitive data stored on system. i put following code allow me use aes encryption sensitive values. aes requires 16 byte chunks; need padding. , want save data in text files; added base64 encoding: from __future__ import print_function crypto.cipher import aes import base64 crypto = aes.new('this key123', aes.mode_cbc, 'this iv456') bs = 16 pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs) unpad = lambda s: s[0:-ord(s[-1])] def scramble(data): return base64.b64encode(crypto.encrypt(pad(data))) def unscramble(data): return unpad(crypto.decrypt(base64.b64decode(data))) incoming = "abc" print("in: {}".format(incoming)) scrambled = scramble(incoming) print("scrambled: {}".format(scrambled)) andback= unscramble(scrambled) print("reversed : {}".f

Random numbers in web page url -

i want create static url website pages , looking methods. i check multiple websites , found there many web pages url has random number @ end. example- randomweb.com/how-to-feed-a-baby-90kfdsio what purpose of last random number when randomweb.com/how-to-feed-a-baby can valid url. can 1 suggest way give unique url webpages can take care of same url path.

javascript - Is there a way to group same type variable in Angular 2 Typescript component? -

this question has answer here: declaring multiple typescript variables same type 3 answers is there java-like way group same type variables in component? for example, have: foo1: string; foo2: string; donald3: string; is there way this? foo1, foo2, donald3: string; there no such syntax. gotta have include type each variable.

android - Click Text on Recyclerview to expand -

Image
i have recyclerview works instagram ui. want set onclick listener text below image expands when clicked , collapse when clicked again instagram app. below how looks like. so when "lorem ipsum" text clicked, should expand , show rest of text. when clicked again, should collapse. this how wrote textview in cardview.xml <textview android:id="@+id/mcarddescription" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginleft="4dp" android:layout_marginright="10dp" android:layout_marginstart="4dp" android:maxlines="2" android:text="lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod tempor incididunt ut labore et dolore magna aliqua. ut enim ad minim veniam, quis nostrud exercitation" /> really need help.thanks in advance. inside

How do I get SSRS to use a GET request instead of a POST for a XML Web Service Datasource -

i have set of ssrs reports use http://localhost:33333/soapcalls.asmx/getdata xml datasource connection strings i change them http://localhost:33333/soapcalls.asmx use shared datasource , that, need configure query's method name. i tried change dataset's query below , seen "works", web service requires request rather post request function <query> <method name="getdata" namespace="http://example.com"/> <elementpath ignorenamespaces="true">*</elementpath> </query> is possible configure query becomes equivalent querying old http://localhost:33333/soapcalls.asmx/getdata datasource?

multithreading - What's the operational difference between Parallel and Task in C#? -

i work sole application developer within database-focussed team. recently, i've been trying improve efficiency of process predecessor had prototyped. best way thread it. approach: public void dosomething() { parallel.foreach(rowcollection), (fr) => { fr.result = mycleaningoperation(); }); } which functions fine, causes errors. errors arising in third-party tool call coding. tool supposed thread safe, looks though they're arising when 2 threads try , perform same operation @ same time. so went prototype. i'd looked @ see how talk third-party tool. when examined called code, discovered predecessor had threaded using task , action , operators i'm not familiar. action<object> mycleaningoperation = (object obj) => { // invoke third-party tool. } public void main() { task[] taskcollection = new task[1]; (int = 0; < rowcollection.length; i++) { taskcollection[i] = new task(mycleaningoperation, i); }

sql - Presto check if NULL and return default (NVL analog) -

is there analog of nvl in presto? i need check if field null , return default value. i solve somehow this: select case when my_field null 0 else my_field end my_table but i'm curious if there simplify code. my driver version 0.171 the iso sql function coalesce coalesce(my_field,0) https://prestodb.io/docs/current/functions/conditional.html p.s. coalesce can used multiple arguments. return first (from left) non-null argument, or null if not found. e.g. coalesce (my_field_1,my_field_2,my_field_3,my_field_4,my_field_5)

java - HttpURLConnection send header authorization -

i struggling send requests authorization header using httpurlconnection. error code 400 returned. i successful okhttpclient requested not use dependencies. here code: public static string getrequserprofiles() throws ioexception { url url = new url(urlstring); httpurlconnection urlconnection = (httpurlconnection) url.openconnection(); urlconnection.setdooutput(true); urlconnection.setrequestmethod("get"); urlconnection.setrequestproperty("content-type", "application/" + "json"); urlconnection.setrequestproperty("authorization", "bearer " + management_token); urlconnection.connect(); if (urlconnection.getresponsecode() != 200) { throw new runtimeexception("failed : http error code : " + urlconnection.getresponsecode()); } string assembledoutput = ""; bufferedreader responsebuffer = new bufferedreader(new inputstreamreader(

cryptography - Get key parameters from imported Elliptic Curve key in ASN.1 format -

Image
i need write code gets input elliptic curve key in asn.1 format. the input byte array next: 308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b0201010420e699203ac5bcfe36402ebd0ac9e8e21cc6fad5828a61297ea747468fff4dbb20a144034200047e05188a03ea81e853b9f6ac5f20dca1a1ca828fd7cd5d92161fb2120c35eac52eab079ed01a510123057c322ddff95e239d6063055bc90858d161d71de707f8 online parser shows me next structure: to use key want need public value x , public value y , private value structure, @ least think so. not know how. i have searched information object identifier 1.2.840.10045.2.1 , object identifier 1.2.840.10045.3.1.7 . i've found this document . there no description of fields of asn.1 structure. how can required parameters imported data? it's commonly known pkcs#8 structure, "private-key information syntax specification". contains unencrypted part of pkcs#8 private key. so in pkcs#8 : privatekeyinfo ::= sequence { version vers

javascript - Send ajax data to php controller in symfony2 -

hi guys new in symfony 2 , have little confusing sending data ajax php controller in symfony 2. want create project google map create mapcontroller: <?php namespace appbundle\controller; use sensio\bundle\frameworkextrabundle\configuration\route; use symfony\bundle\frameworkbundle\controller\controller; use symfony\component\httpfoundation\response; use symfony\component\httpfoundation\request; use symfony\component\httpfoundation\jsonresponse; class mapcontroller extends controller { /** * @route("/", name="homepage") */ public function indexaction(request $request) { // replace example code whatever need return $this->render('map/map.html.twig', [ 'base_dir' => realpath($this->getparameter('kernel.root_dir').'/..').directory_separator, 'contdata' => ['lat' => '51.24591334500776', 'lng'=> '22.569673061370