Posts

Showing posts from June, 2011

Python - Parsing multiple lines of text from file -

i stuck on problem working on. it involves opening file reading line , comparing next 2 lines in file it. move down 1 line, ie second line in file , compare next 2 lines again. i having hard time creating loop go through these steps. so far have done write_file = input_file[:-3] + "bak" read_file = input_file open(write_file, "w") write: open(read_file,"r") read: line in read: line1 = line thank you. something like: tri_lines = [lines[i:i+3] in range(0,len(lines),3)] #then can iterate through: triplet in tri_lines: # code here, compare tri_lines[0] tri_lines[1] etc. i'll leave task of getting lines of file list. note you'll need simple validation handle cases file not have number of lines divisible 3. you can for triplet in [lines[i:i+3] in range(0,len(lines),3)]: if triplet[0] == triplet[1]: #do if triplet[0] == triplet[2]: #do though might not clear

php - laravel belongstomany with condition -

i have following model. class training extends \eloquent { // add validation rules here public static $rules = [ 'name' => 'required', 'city' => 'required', 'province' => 'required', 'budget_year' => 'required|integer', 's_date' => 'required|date', 'e_date' => 'required|date' ]; // don't forget fill array protected $fillable = [ 'name', 'city', 'province', 'budget_year', 's_date', 'e_date' ]; public function material(){ return $this->hasmany('material'); } public function budget(){ return $this->belongstomany('budget')->withpivot('amount'); } public function budgetbyid($training_id){ $this->belongstomany('budget

sql - PIVOT values from two columns to multiple columns -

table: sample id day status ms ---------------------------- 1 1 0 10 1 2 0 20 1 3 1 15 2 3 1 3 2 30 0 5 2 31 0 6 expected result: id day1 day2 day3....day30 day31 status1 status2 status3...status30 status31 --------------------------------------------------------------------------------------- 1 10 20 15 null null 0 0 1 null null 2 null null 3 5 6 null null 1 0 0 i want ms , status value each day 1 31 each id. i have used pivot below result. result: id day1 day2 day3....day30 day31 ------------------------------------- 1 10 20 15 null null 2 null null 3 5 6 query: select id ,[1] day1 ,[2] day2 ,[3] day3 . . . ,[30] day30 ,[

javascript - Append <span> tag inside of <a> tag using Jquery -

i trying append span tag inside .block-leftnav ul li .parent a , tag gets added after .parent a jquery is, adds span tag after every href tag on page. below code using acheive want: jquery(document).ready(function() { jquery('.block-leftnav ul li .parent > a').append('<span class="glyphicon arrow"></span>'); }); it simple fix, figured out myself , updated above code. had add ">" before "a" target anchor tags of particular div. thanks guys prompt response. $(document).ready(function(){ $('.block-leftnav ul li .parent a').prepend('<span class="glyphicon arrow"></span>'); });

Python - File processing ( Write Method ) -

i having trouble while writing file using python from validate_email import validate_email result=open('output1.tsv','wb') f=open('input.csv','r') y=[] result.write('email_address\temail_validation\n') in f: y.append(i.replace('\n','')) j in y: try: val=validate_email('%s'%j, verify=true) except: val = "check again" result.write('%s\t%s\n'%(j,val)) print j,val here variable x has operation , may take time process it. variable y has more count of 500 ( input file contains 700 rows ). but after run program around 120 written in output file. a more idiomatic python is emails = [l.strip() l in open('input.csv','r').readlines()] valid = [str(validate_email(addr, validate=1)) addr in emails] validated = ['\t'.join(addr_val) addr_val in zip(emails, valid)] of open('output.tsv'): of.write('email_addr

drupal - how to add fields to database using hook functions and how should i write a return function -

i added fields mobile no,landline no, using below code form created registration module. when fill fields along 2 added fields , submit them clicking save registration button.i cannot find 2 added field in database.how can make them appear in database. function search_enhance_form_alter(&$form, $form_state, $form_id) { if($form_id == 'registration form') { $form['mobile no'] = array( '#type' => 'fieldset', '#title' => t('mobile no'), '#collapsible' => true, '#weight' => 30, ); $form['mobile no']['text'] = array( '#type' => 'textfield', '#description' => t('this test see form_alter hook in action1.'), ); $form['text'] = array( '#type' => 'textfield', '#description' => t('this test see form_alter hook in action.'), '#title' => t('land line no'), '#weight'

unity3d - Have different Source Image in Unity 4.6 UI Image prefab depending on script bool property state -

i'd have 1 prefab of image. image , features same, come in 2 colors - i'll need set source image 1 of 2 images depending on actual value of bool in script attached prefab. of course, instead of using 2 images, change color of original image, or draw other way guess method largely same - done inside unity , not in code. using unity 4.6 final release. btw inheritance not possible prefabs right? i assuming refer image component in new ui , want change sprite. either assign 2 sprites in prefab: public sprite spriteon; public sprite spriteoff; public bool onoff; void start() { image imagecomponent gameobject.getcomponent<image>(); if(imagecomponent != null) onoff ? imagecomponent.sprite = spriteon : imagecomponent.spriteoff; } or change original sprite: public bool onoff; void start() { image imagecomponent gameobject.getcomponent<image>(); if(imagecomponent != null) { if(onoff) { sprite basesprite;

Python write list items to csv -

i have code suppose export list items csv file each row in file contains item in list. writer = csv.writer(open(path+"output.csv", 'wb')) item in result: writer.writerow(item) the result i'm getting quite strange (example 2 top items in list: 'past due' , 'code'): p,a,s,t, ,d,u,e c,o,d,e the results want simply: past due code any ideas ? csvwriter.writerow(row) this write row parameter writer’s file object, formatted according current dialect. for more info see csvwriter

filenet - Enabling comments in IBM Content Navigator document viewer -

Image
i trying enable layout comment button in viewer , so far try enable contentviewer.js changing disable property false keeps turning disable , make disable , how can enable ? thanks input !! try install socical collaboration add-ons object store. (via acce or fem).

wordpress - How to add discount to cart total? -

i need add discount according number of product in cart , discount apply on total of cart. there other option without use of coupons? this code should work: add_action('woocommerce_before_cart_table', 'discount_when_produts_in_cart'); function discount_when_produts_in_cart( ) { global $woocommerce; if( $woocommerce->cart->cart_contents_count > 3 ) { $coupon_code = 'maryscode'; if (!$woocommerce->cart->add_discount( sanitize_text_field( $coupon_code ))) { $woocommerce->show_messages(); } echo '<div class="woocommerce_message"><strong>you have more 3 items in cart, 10% discount has been added.'; } } the above apply coupon "maryscode" cart if there 4 or more products in customers cart. edit: add following css .coupon { display: none !important; }

authentication - What is the correct way to use Laravel basic auth with angularjs? -

here approach follow. i secure routes api this: route::group(array('prefix' => '/api/v1'), function () { route::get('dashboard', array('before' => 'basic.once', function () { return 'dashboard'; })); }); i planning use basic auth on ssl connection. i have send username , password every request. i understand need store user details on client side (angular/browser) user logs in once , allowed access protected routes until session valid. what don't understand user information store @ client end , how? the api used building mobile apps in future. what simplest thing can achieve this? the simplest way when user register (or create user), add field not standard credentials (username, password), field can token you'll generate when create user, after when user logs in send him unique token, , @ client side (angularjs) can store token example in session storage, , after need send token

asp.net - Possilble to auto open a downloaded word document downloaded in browser -

Image
the requirement sent word document browser, , automatically open on ms word can view , edit word document. the solution can found require end user click dialogue window in order open word document in office when document download browser. is way, user has click dialogue window before office can open downloaded word document? it kinds of make sense security reason not let browser automatically execute local application (word.exe) on local machine, still want confirm that. if answer yes, know how that? edit: found out have use inline instead of attachement , otherwise ask option event browsers setup properly. response.addheader("content-disposition", "inline;filename=clientquotes.docx"); after made change, browser auto open word document without asking action. if understand correctly, want change behaviour of browser automatically open downloaded files. far i'm aware pretty painless process when comes firefox , google chrome, on ie

cmd - Cannot include space in string in one line program mode for Perl on Windows? -

the command perl -ne "print "" """ anytextfile.txt running on windows latest activeperl installed (5.020) complains can't find string terminator '"' anywhere before eof @ -e line 1. . other characters or variables work expected, like perl -ne "print ""$.-$_""" anytextfile.txt i checked double quotes passed perl expected, if little weird when escape double quotes in cmd.exe. why space cannot shown in above double quoted string? using single quote work loses variables interpolation functionality. perl -ne "print \" \"" anytextfile.txt why? a lot of programs arguments means of standard argument parser used c library used compile language itself, libraries or used base. for windows, in general, "rules" argument parsing arguments delimited white space, either space or tab. a string surrounded double quotation marks interpreted single argument,

java - Algorithm seems to only work on last chunk of ArrayList -

the goal of algorithm take list of strings , abbreviate them in such way can uniquely identify word represent, homework assignment. the algorithm i've tried create problem searches substrings possible matches, although seemed trie more effective solution, couldn't seem wrap head aroud how code 1 works; being said, should still possible way well. input: ~~~~~~~~~~~ expected output: ~~~~~~~~~~~~ actual output: carbohydrate -------- carboh -------------------------------- carbohydrate cart -------------------- cart ------------------------------------ cart carburetor ------------ carbu --------------------------------- carburetor caramel --------------- cara ----------------------------------- caramel caribou --------------- cari ------------------------------------- caribou carbonic -------------- carboni -------------------------------- carbonic cartilage -------------- carti ------------------------------------ cartilage carbon ---------------- carbon ------------

javascript - Rails + JQuery: Getting to a sibling div from script -

i have rails partial renders html: <div class="content"></div> <script> // load content here , adjacent div , populate it. </script> this partial template gets embedded in main document server , several times response ajax requests. page has several instances of partial. whenever script executes want div adjacent script affected. so hoping if script, can div. use jquery , use several async scripts (this prevents me using last executed script) i adjacent div through document.currentscript , problem browsers don't support it. then, way create sort of uuid id div , access id dom? i wished div supported onload, sadly not. you can create element after <script> ( document.write ) , find .content relative it. (function(){ var id = 'id' + (new date().gettime()); document.write('<div id="'+id+'"></div>'); var elem = document.getelementbyid(id); var content = el

vba - How to open two documents and copy the text from one to another? -

i have 2 documents.(title.docx , style.docx). need replace text(with italic format) title.docx file text . tried following code. italicizes content of style.docx file instead of italicizing specific text (from title.docx) sub opendoc() documents.open filename:="c:\documents , settings\quads\desktop\title.docx", confirmconversions:=true dim char long dim x long dim count integer selection.homekey unit:=wdstory, extend:=wdmove x = activedocument.builtindocumentproperties("number of lines") = 0 x char = selection.endkey(unit:=wdline, extend:=wdmove) if (char > 0) selection.homekey unit:=wdstory, extend:=wdmove selection.movedown unit:=wdline, count:=i selection.expand wdline 'msgbox (selection.text) documents.open filename:="c:\documents , settings\quads\desktop\style.docx" selection.find.clearformatting selection.find.replacement.clearformatting selection.find.replacement.font.italic = true selection.find .text = _

c# - Manipulate Image controls in WPF -

i'm learning wpf in free time using flickr.net api. the first feature want perform search images name/description/tags. leads me play around images in wpf. this setup: - xaml <grid> <itemscontrol x:name="photolist" horizontalalignment="left" height="639" margin="10,10,0,0" verticalalignment="top" width="1060" style="{dynamicresource scrollableitemcontrolstyle}" > <itemscontrol.itemspanel> <itemspaneltemplate> <wrappanel orientation="horizontal" height="639" width="1060"/> </itemspaneltemplate> </itemscontrol.itemspanel> <itemscontrol.itemtemplate> <datatemplate datatype="{x:type sys:string}"> <image width="200" source="{binding url}" margin="0,0,5,5" mousedown="openselected

metaprogramming - Naive aspect implementation in ruby -

i trying make simplistic implementation of aop in ruby. able implement before , after advices, got stuck around advice. this target class going advised: class myclass def method puts "running method" end end this aspect class instantiate objects capable of making advices: class aspect def advise(class_name, method, type, &block) class_name.send(:alias_method, :proceed, :method) class_name.send(:define_method, :method) case type when :before yield proceed when :after proceed yield when :around yield(proceed) # * proceed old version of method end end end end (*) yield should execute block around myclass#proceed on current object when method invoked. creating target , aspect: mc = myclass.new = aspect.new() invoking method without advising it: puts mc.method advising myclass#method around: a.advise(myclass, :method, :around) |proceed| puts "first&qu

Read integer array through white space with using limit in java -

my requirement is: the first line of input consists of integer n (where n>=3) denotes size of array. in next line there n integers separated space correspond n elements in array. have used below code: scanner length = new scanner(system.in); system.out.println("please enter length of aarry:"); int n=length.nextint(); int[] numbers = new int[n]; scanner sc = new scanner(system.in); system.out.println("enter elements seperated spaces: "); string input = sc.nextline(); stringtokenizer strtoken = new stringtokenizer(input); int count = strtoken.counttokens(); //reads in numbers array system.out.println("count: " + n); int[] arr = new int[n]; for(int x = 0;x < n;x++){ arr[x] = integer.parseint((string)strtoken.nextelement()); system.out.println("values are: " + arr[x]); } but problem : above code rea

error "Not Found" while Javascript to Rails AJAX connection -

i have simple rails controller method. method works in browser , displays "ok" string. when call javascript ajax method, error "not found" displayed log javascript error method.why ? what see in browser js log is: "jqxhr: [object object]" application.js:3069 "textstatus: error" application.js:3070 "errorthrown: not found" thanks responses:) coupons_controler: def get_value() #coupon_name = params[:param1] #@coupon = coupon.get_price(coupon_name) #respond_to |format| #format.js { render :layout=>false } #render text: "17.8, true"; render text: "ok"; #end end javascript script method: function validatediscountcouponidajax( sec1, sec2 ) { if( typeof sec1 === 'undefined' || typeof sec2 === 'undefined' ){ sec1 = 2; sec2 = 3; } $.ajax({ type

jquery - Find equal row in table and add span before another -

i have 2 tables, "addfieldstoformdiv" , "addfieldstopreviewdiv" , need find "qteofoutpackspan" span in "addfieldstopreviewdiv" table (and add span beforet that) if 2 inputs in "addfieldstoformdiv" filled. so far have this: $("input[name='volym1']").each(function (index) { var $qteofouterpack = $(this); var $outerpacktype = $(this).closest("tr").find("input[name='volym2']"); var $previewtable = $("#addfieldstopreviewdiv"); var $row = $previewtable.find('tr:eq(' + index + ')'); var $packspan = $row.find("span[name='qteofoutpackspan']"); if ($qteofouterpack.val().length > 0 && $outerpacktype.val().length > 0) { $packspan.before('<span>som text</span>'); } else {alert('do else'); } }); and jsfiddle play.

Update form: Spring mvc + thymeleaf -

i'm trying create thymeleaf form update couple of attributes of backing object: @requestmapping(value = "/jobs/{id}", method = requestmethod.get) public modelandview update(@pathvariable integer id ) { modelandview mav = new modelandview("updatejob.html"); jobdescription updatejob = jobdescriptionservice.findbyid(id); mav.addobject("updatejob", updatejob); return mav; } @requestmapping(value = "/jobs/{id}", method = requestmethod.put) public string saveupdate(@pathvariable integer id, @modelattribute("updatejob") jobdescription updatejob) { jobdescriptionservice.update(updatejob); return "redirect:/jobs/" + id; } <form th:action="@{'/jobs/'+ ${updatejob.id}}" th:object="${updatejob}" th:method="put"> <table> <tr> <td><label>description</label></td> <td><input type=&qu

javascript - Regex replacing more than I want -

i want delete body element 1 class starts demo-xxx xxx can character , without fix length. so can have in body <body classs="bye demo-hello water"> i using regex /\b\s?demo-.*\b/g so: $("body")[0].classname = $("body")[0].classname.replace(/\b\s?demo-.*\b/g, ''); but removing classes after demo-xxx , such water : <body classs="bye"> you need exclude space usintg ^\s , 1 or more characters use + instead of * $("body")[0].classname =$("body")[0].classname.replace(/\b\s?demo-[^\s]+\b/g,''); demo

Time series estimation in R vs. Mathematica -

i'm fitting ima(1,1) [or arima(0,1,1)] model time series. tried using arima function in r, , estimatedprocess function in mathematica (ver. 10), , got different results. why? making different assumptions, valid in different situations? have advice on 1 should use? example. first, in r. > series <- c(-1.42377, 0.578605, -0.534659, -3.07486, -2.4468, -0.508346, -0.216464, -2.7485, -1.93354, -1.07292, -1.48064, -1.13934, -1.24597, 1.419, -1.22549, -2.44651, 1.54611, 1.80892, -0.863338, 1.21636) > arima(series, order=c(0,1,1)) call: arima(x = series, order = c(0, 1, 1)) coefficients: ma1 -0.7807 s.e. 0.1548 sigma^2 estimated 2.227: log likelihood = -35.03, aic = 74.07 now, in mathematica: series = {-1.42377, 0.578605, -0.534659, -3.07486, -2.4468, -0.508346, -0.216464, -2.7485, -1.93354, -1.07292, -1.48064, -1.13934, -1.24597, 1.419, -1.22549, -2.44651, 1.54611, 1.80892, -0.863338, 1.21636}; estimatedprocess[series, arimaprocess[{}, 1

qt - How to access the public properties of a qml page loaded through a Loader? -

aa.qml item { id: drawlinesonc property string linecolour property int linedrawingsourcetype property variant startendpointarray } main.qml loader { id: drawlineloadera source: "aa.qml" } - how access public properties of aa.qml page loaded through loader drawlineloadera ? solution follows: drawlineloadera.source = "drawlineloader.qml" if (drawlineloadera.status == loader.ready) { if (drawlineloadera.item && drawlineloadera.item.linecolour) { drawlineloadera.item.linecolour = "black" drawlineloadera.item.linedrawingsourcetype = 2 } }

r - How to efficiently merge these data.tables -

i want create data.table able check missing data. missing data in case not mean there na, entire row left out. need able see of time dependent column values missing level column. important if there lot of missing values or if spread across dataset. so have 6.000.000x5 data.table (call tablea) containing time dependent variable, id level , value n add final table. i have table (tableb) 207x2. couples id's factor columns in tablec. tablec 1.500.000x207 of each of 207 columns correspond id according tableb , rows correspond time dependent variable in tablea. these tables large , although acquired ram (totalling 8gb) computer keeps swapping away tablec , each write has called back, , gets swapped away again after. swapping consuming time. 1.6 seconds per row of tablea , tablea has 6.000.000 rows operation take more 100 days running non stop.. currently using for-loop loop on rows of tablea. doing no operation for-loop loops instantly. made one-line command looking correct

Using Excel VBA to create email in Outlook 2010 from template -

Image
i have code worked in excel/outlook 2003 on xp, i'm running windows 7 excel/outlook 2010 , receive error: run-time error '287': application-defined or object-defined error. my code based on answer in: send email excel 2007 vba using outlook template & set variables i'm creating outlook object , mailitem this: dim myolapp dim myolitem set myolapp = createobject("outlook.application") set myolitem = myolapp.createitemfromtemplate(range("oftlocation").value) 'user defined location the error appears after reference myolitem , code replacing references in .htmlbody amending .body makes no difference, same error shows. my references in vba set to: vba microsoft excel 14.0 object library ole automation microsoft office 14.0 object library microsoft forms 2.0 object library microsoft scripting runtime this isnt answer yet want collect happening in comments since feel best direction have seen far. i have test

selenium webdriver - How to do mouse over and check the element together with robotframeworks+selenium2libarary -

i'm going automation test on scenario: when hover mouse on button, there float menu. , want check logo in float menu. default, is: <div class="header fold"> <div class="logo fold"> ... when hover mouse on button, page turn to: <div class="header float-header"> <div class="logo float-header"> ... i tried command: mouse on | css=div.header-status-btn[title="restore header"] page should contain element | css=div.logo.float-header but there errors: fail : valueerror: element locator 'css=div.logo.float-header' did not match elements. seems can't locate element in floating menu in way. know how check float menu mouse over? try this: mouse on | css=div.header-status-btn[title="restore header"] # wait 60s element become visible set selenium implicit wait | 60 wait until element visible | css=div.logo.float-header

php - Validating multiple attributes within a inline validator in Yii 2 -

i'm aware can validate single attribute using inline validator such as: ['country', 'validatecountry'] public function validatecountry($attribute, $params) { if (!in_array($this->$attribute, ['usa', 'web'])) { $this->adderror($attribute, 'the country must either "usa" or "web".'); } } but how go passing in multiple attributes validator? ...or should reference them via $this within validator? instead of accessing fields directly e.g using $this->email pass additional attributes field in params , how comparevalidator works i.e ['username', 'customvalidator', 'params' => ['extrafields' => 'email']] public function customvalidator($attribute, $params) { //access extrafields using $this->{$params['extrafields']} }

angularjs - Angular ui-router doesn't change location -

i have abstract state header , content (really app has layouts, simplified code example). header has filter , want change location url dynamically click on filter category. working stopped, , don't know why... i use similar pieces of code: $stateprovider .state('root', { url: '', abstract: true, views: { '@': { templateurl: 'templates/layout.html', controller: 'layoutctrl' }, 'header@root': { templateurl: 'templates/header.html', controller: 'headerctrl' } } }) .state('root.index', { url: 'index?{filter}' }) }); (function() { 'use strict'; test.app.controller('layoutctrl', ['$scope', '$state' function($scope, $state) { $scope.params = $state.params; $scope.$on('pa

html - Remove extra height (white space in bottom of the page) -

i have website https://www.youwintube.com/ , if @ bottom of website there lot of white space. so remove went inspect element in firefox .. there style automatically set <div style="height: 871px; min-height: 487px;" id="content"> but in html template just <div id="content"> so how height automatically set , how remove . try changing in init.js this: var $sc = $('#sidebar, #content'), tid; for this: var $sc = $('#sidebar'), tid;

asp.net - When i click button in gridview it does't work -

i beginner of asp.net, making l small project having big problems, :) ... right have situation, used gridview retrieve data access database , done that, added buttons in grid view. when click on button following error comes server error in '/e shop' application. invalid postback or callback argument. event validation enabled using in configuration or <%@ page enableeventvalidation="true" %> in page. security purposes, feature verifies arguments postback or callback events originate server control rendered them. if data valid , expected, use clientscriptmanager.registerforeventvalidation method in order register postback or callback data validation. html <asp:gridview id="gridview1" runat="server" autogeneratecolumns="false" width= "100%" cellpadding="3"> <columns> <asp:templatefield> <itemtemplate> <tab

javascript - What is wrong with this code, trying a click menu? -

so there left side vertical menu. , has small options button. when clicked, should open div have various filter options. now, need appear when clicked, , disappear when either options button clicked again, or user clicks anywhere outside div. so have following code. //options filter menu animation $('#optionsmenu').hide(); //hides menu $('.optionsfilters').click(function(e){ var $this = $('#optionsmenu'); $this.show(); var left = $('#sidebar').css('width'), top = $(this).offset().top; $this.css('top', top); $this.css('left', left); }); $(':not(.optionsfilters)').click(function(e){ $('#optionsmenu').hide(); }); the html is <div id="sidebartitle"> <h2>organisation</h2> <a id="optionsfilters" class="optionsfilters">options</a> </div> <div id="optionsmenu" class="optionsfilters"&

unix - Log console output from a gradle script to file -

i want log console output gradle script log file: gradle test 2>&1 | tee -a gradle.log but gradle script prompts param user: task test << { system.console().readline("enter:").tostring() } as result, have nullpointerexception: execution failed task ':test'. cannot invoke method readline() on null object may know solution or workaround situation? what about: yes <desired input> | gradle test 2>&1 | tee -a gradle.log yes repeditively echos whatever it's argument stdout

Trying to achieve DIV jQuery UI slide effect cuts off part of div while transitioning -

i saw effect , liked it. here js fiddle link of effect http://jsfiddle.net/lookitstony/edsp4/ so try achieve same @ end not working mine. have main div called mainslidediv , main div has 2 other div "dvups_label" & "ups_rate_time" . trying achieve same effect slide effect cuts off part of div mine not working. here small js code. function transitionpage() { // hide left / show left $('.ups_label').toggle("slide", { direction: "left" }, 500); // show right / hide right $('.ups_rate_time').toggle("slide", { direction: "right" }, 500); } $(document).ready(function () { //$('#page1').click(transitionpage); //$('#page2').click(transitionpage); $('#btntst').toggle( function () { $('.ups_label').click(transitionpage);

android - how to get updated app hosted in localhost -

in project suppose host inventory.apk in localhost of network. app periodically checks whether new version inventory.apk uploaded. if new version of inventory.apk found, want ask clients of company update old version of inventory.apk in device. suggestion appreciated. thanks first of all, in opinion easiest way check new .apk files name .apk files dates. example: 27_11_2014.apk . if follow path, can name/names of apk files in directory kind of code: urlconnection conn = new url(url).openconnection(); inputstream in = conn.getinputstream(); you can use sharedpreferences keep first initialization date , compare parsed .apk file name. if file name has newer date can prompt dialog warn user update. there 1 thing cannot achieve without root permission, , automatically updating app itself. not sure if aiming kind of usage wanted warn you, apps cannot update without root permission.

c# - Calculate molecular weight based on chemical formula -

i trying write program calculate molecular weight of given molecule based on chemical formula. this code can split molecular formula "ch3oh" array {c h 3 o h} here, way use split text calculate molecular weight? string input = moleculetextbox.text; string pattern = @"([0-9]?\d*|[a-z][a-z]{0,2}?\d*)"; string[] sunstrings = regex.split(input,pattern); first of all, you'd need parse string , turn "h3" "hhh", etc. might this: var x = "ch3oh".replace(/([a-z])([2-9])/gi, function(_,c,n) { return new array(1+parseint(n)).join(c); }); first group being matched character, , second group being number of repetitions. you have string looks "chhhoh" . can split line array 1 character @ each index, .split('') , , map each value molecular mass. need define sort of lookup table. i'm using reduce take care of mapping , addition in 1 go: var mass = { c: 12.011, h: 1.008, o: 15.999 }; var weight =

php - Public file just for current session -

i have folder multiple pdf files name of each session number created want user (unauthenticated) can download pdf file corresponding session, without access other files (because folder files public). how can fix this? note: users not authenticated first, when "corresponding session", mean "to session"? the first thing prevent directory listing, directory pdfs sitting obviously. can done .htaccess file containing single line: deny all next, , assumption talking their session, can write simple html link download pdf, such as download pdf <a href="/public/path/to/download.php">here</a>. where download.php server-side proxy service script, such as <?php define('pdf_repository', '/path/to/dir'); if (session_id() && file_exists(pdf_repository . '/' . session_id() . ".pdf")) { readfile(pdf_repository . '/' . session_id() . ".pdf"); } ?> here expl

mysql - How do I import a single database from a .sql file that contains multiple databases -

how import single database backup file has multiple databases on it? the main issue file 921mb can't open in notepad or of ide's have. if that, sql need , manually copy phpmyadmin. it if import straight backup file. i guess can't work mysql -u root -p --database1 database1 < backup.sql can help? thanks i had problem data loading scripts. scripts in form: insert table(a,b,c) values((a0,b0,c0),(a1,b1,c1),...(a50000,b50000,c50000)); and contained 5 several dozen of these hyper-long statements. format wasn't recognizable system wanted import data into. needed form: insert table(a,b,c) values(a0,b0,c0); insert table(a,b,c) values(a1,b1,c1); ... insert table(a,b,c) values(a50000,b50000,c50000); even smaller scripts several mb , took hour load text editor. making these changes in standard text editor out of question. wrote quick little java app read in first format , created text file consisting of second format. largest scripts took less 20 s

jquery - Call a method from Servlet (Servlet MVC) using ajax call? -

the current jsp page called using below url request: device/loan and when calling jquery.get url user/xyz instead of calling http://http://localhost:8080/springmvctest/user/xyz calling http://localhost:8080/springmvctest/device/user/xyz below javascript code: $('#loanedto').blur(function () { console.log("inside" + $('#loanedto').val().length); if ($('#loanedto').val().length > 1) { $.getjson("http://localhost:8080/springmvctest/user/badgeid", { "loginid": $('#loanedto').val() }, function (result) { if (result === 'no record found') { alert('no record found.'); } else { $('#xyz').val(result); } }); } }); sorry english. you should not put absolute url ajax call relative one: $.getjson("user/badgeid")

c# - caching a page with data from database asp.net -

i have main page categories of items. categories of items come database. data not changes frequently. want cache page , after 1 month or so, data should updated fresh data coming db. know in asp.net there output cache , data cache. how can achieve above functionalities? i know there <%@ outputcache %> that can used caching page. any information provide useful me looking expert opinion. i know it's broad topic, useful thing, should not flagged. one of best approach can use of advanced feature of asp.net output caching sqlcachedependency class, output caching direct sql server. you can configure sql server , asp.net cache page requests, reducing server workload, until data on page depends has been updated in sql server. sql cache dependency useful data remains comparatively static. http://msdn.microsoft.com/en-us/library/e3w8402y(v=vs.100).aspx you need follow steps : first, need enable cache notification sql server, : aspnet_regsql.exe -s &l

Accessing boolValue in a NSNumber var with optional chaining (in Swift) -

i have nsmanagedobject subclass optional instance variable @nsmanaged var condition: nsnumber? // refers optional boolean value in data model i'd when condition variable exists , contains 'true'. of course, can this: if let cond = condition { if cond.boolvalue { // } } however, hoped possible same thing little bit more compact optional chaining. this: if condition?.boolvalue { // } but produces compiler error: optional type '$t4??' cannot used boolean; test '!= nil' instead the compact way solve problem this: if condition != nil && condition!.boolvalue { // } is there no way access boolean value optional chaining, or missing here? you can compare boolean value: if condition == true { ... } some test cases: var testzero: nsnumber? = 0 var testone: nsnumber? = 1 var testtrue: nsnumber? = true var testnil: nsnumber? = nil var testinteger: nsnumber? = 10 if testzero == true { // not true } if

javascript - Admin section for website? -

i'm wondering if following thing possible: an 'admin' section on website in administrators can input link image or video (for example youtube or google) causing html code on website edited in way. for example: admin x logs in. admin x wants change video on index.html. admin x puts embed code in input field , presses send. website handles request , updates website may see it. does know if feasible? i thinking may possible using mix of jquery, javascript , php, i'm not sure this. first of all, creating admin section require build/use sort of authentication system , way save admin user info , password hash. can save user information sort of database, , login using username/password form page should run under https login credentials don't transmitted on network. this type of problem describe solved using content management system (cms). there lot of known cms's both open source or proprietary, , people swear of them. it's important try

java - jQuery inside SpriingMVC Form -

i've got trouble creating form using springmvc jquery; here index.jsp: <%@ page language="java" contenttype="text/html; charset=iso-8859-1" pageencoding="iso-8859-1"%> <%@taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> <%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <title>title page</title> <link type="text/css" rel="stylesheet" href="../css/style.css"></link> <script type="text/javascript" src="../js/jquery-2.1.1.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.ajax({ datatype:'json',