Posts

Showing posts from June, 2010

Java networking | Streams are working only 1 time -

this question exact duplicate of: java networking, strange error 1 answer im working on little chat program , have huge problem , can not solve it. dont know mistake be, me code right. really need help. have 2 threads in server, 1 thread accepting clients , other streams. , thread streams not working right. sends 1 time message client , multiple clients not working. , there strange problem. can send 1 message back, if put joptionpane-message called "sockets empty" in else statement, without doesnt work. here stream thread code: private static runnable streamthread = new runnable() { public void run() { while(true) { if(!(socketlist.isempty())) { for(int = 0; < socketlist.size(); i++) { try { string

Can I select three IDs with a shorter jQuery script? -

i believe there better way selecting these 3 ids dropdown-list (id 115, 116 , 117): jquery(document).ready(function($) { var usednames = {}; $("select[name='item_meta[115]'] > option").each(function () { if(usednames[this.text]) { $(this).remove(); } else { usednames[this.text] = this.value; } }); var usednames = {}; $("select[name='item_meta[116]'] > option").each(function () { if(usednames[this.text]) { $(this).remove(); } else { usednames[this.text] = this.value; } }); var usednames = {}; $("select[name='item_meta[117]'] > option").each(function () { if(usednames[this.text]) { $(this).remove(); } else { usednames[this.text] = this.value; } }); }); can make code shorter, , have ids selected under first variable? you can use at

database - Laravel 4 saving image with Dropzone -

i'm trying save images dropzone.js in laravel 4 project. this code: $fileinput = input::file('file'); if(input::hasfile('file')) { $filename = hash::make($fileinput->getclientoriginalname()); $path = public_path().'/images/'; $filetype = $fileinput->guessextension(); $filesize = $fileinput->getclientsize()/1024; $file = new image; $file->nombre = $filename; $file->ruta = $path; $file->tipo = $filetype; $file->size = $filesize; $file->user_id = sentry::getuser()->id; if($fileinput->move($path, $filename.'.'.$fileinput->guessextension())) { $file->save(); } } i'm obtaining next error message: {"error":{"type":"symfony\\component\\debug\\exception\\fatalerrorexception","message":"call und

Asp.net vNext web app authentication -

i'm trying rewrite old mvc1 application vnext app in vs2014. application authenticates against company's active directory. here's bit of background clarify confusion coming from. i wrote 1 app in mvc4 authenticates following way: 1. vs template had account login post action isvalid method 2. wrote membership provider , registered through web.config 3. when run application isvalid calling override authentication now i'm in vnext , here's see 1. same account , login method except there's signinmanager , user manager passed it. i'm yet see it's coming exactly. suspect it's through startup.cs 2. see isvalid replaced passwordsigninasync think need override login user. here's question how make passwordsigninasync authenticate our ad? can go solo , ignore framework make work i'm sure there's easy way , i'm missing understanding of how plumbing works in vnext. appreciate in right direction. it sounds have default implementa

Spring Web Flow Request Mapping not working -

i trying test spring web flow , cannot access flow basing on mapping i'm using. i'm sure must missing simple, here setup... web.xml: <servlet> <servlet-name>accommodations</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>accommodations</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <context-param> <param-name>contextconfiglocation</param-name> <param-value> /web-inf/datasource-config.xml /web-inf/security-config.xml /web-inf/webflow-config.xml /web-inf/aop-config.xml </param-value> </context-param> webflow configuration: <flow:flow-registry id="flowregistry" base

algorithm - Minimization of the Unbounded Knapsack with Dynamic Programming -

i curious if possible modify (or use) dp algorithm of unbounded knapsack problem minimize total value of items in knapsack while making total weight at least minimum constraint c. a bottom-up dp algorithm maximization version of ukp: let w = set of weights (0-indexed) , v = set of values (0-indexed) dp[i][j] = max{ dp[i-1][j], dp[i][j - w[i-1]] + v[i-1] } = 0,...,n , j = 0,...,c given dp[0][j] = 0 , dp[i][0] = 0 n = amount of items , c = maximum weight dp[n][c] = maximum value of items knapsack capacity of c can make minimization ukp ? if not, can offer solution or technique solve problem this? thanks, dan you'll have new recurrence dp[i][j] ( j <= 0) = 0 dp[i][j] (i = 0, j > 0) = infinity dp[i][j] (i > 0, j > 0) = min{ dp[i-1][j], dp[i-1][j - w[i-1]] + v[i-1] }, which gives, each i , j , minimum value of items 0..i-1 make weight @ least j . infinity should sufficiently large value such legitimate value smaller infi

javascript - Creating many random arrays for use as elements in another array -

consider: var main = [] now want generate many (289 exact) arrays elements in main one. each of these arrays have like: var subobject = {x:"a", y:"b", terrain:"c", note:"d"} generating values no problem, , can put values in defined subobject = {} , push() , can't figure out how iterate script each time creates new object , push() var main . the naming of subobject unimportant, i'm looking solution inwhich can pull specific information such as: main[0].x // x value of subarray in 0 location in main main[5].note// note value of subarray in 5 location in main (would make difference if every array had same name? since never access subobject directly (after being pushed main), through main[x].yyy or have via main[x].subarray[y] ?) for (var = 0; < 289; i++) { main.push({x: getrandomx(), y: getrandomy(), terrain: getterrain(), note: ""}); } as long create new objects {} before push them array ok.

android - Arraylist display selected listview to textview -

i'm noob in android. i've got code someone's blog. he made simple database query , populate arraylist in listview. how value each selected item in listview text view in new activity? here's arraylist code: public arraylist<arraylist<object>> rowtable() { arraylist<arraylist<object>> fillarray = new arraylist<arraylist<object>>(); cursor cur; try { cur = db.query(table_test, new string[] { row_id, row_name, row_class }, null, null, null, null, null); cur.movetofirst(); if (!cur.isafterlast()) { { arraylist<object> filllist = new arraylist<object>(); datalist.add(cur.getlong(0)); datalist.add(cur.getstring(1)); datalist.add(cur.getstring(2)); dataarray.add(filllist); } while (cur.movetonext()); } } catch (exception e) { // todo auto-gen

android - Email app crashes if a photo is not available for attachment -

my app has option take photo, later attached email. works fine. the problem is, crashes if there's no photo taken. idea how can fix this? here's button code, in case comes handy somehow. button sendmail = (button) findviewbyid(r.id.sendemail); sendmail.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub intent emailintent = new intent(intent.action_send); emailintent.putextra(intent.extra_email, new string[]{"somemail@mail.com"}); emailintent.putextra(intent.extra_subject, "subject"); emailintent.putextra(intent.extra_text, "body"); emailintent.settype("message/rfc822"); emailintent.putextra(intent.extra_stream, imageuri); startactivity(intent.createchooser(emailintent, "choose email client")); } });

c++ - Need objects of inheriting classes to be visible before classes are defined -

usually declare , define base class , same inheriting class before declaring objects of inheriting class. unfortunately for visibility reasons need declare objects before inheriting class defines (although after base class defined). i though make forward declaration inheriting class if this: class baseclass { //content }; class inheritingclass; it not recognise inheriting if this. class baseclass { //content }; class inheritingclass: public baseclass; the compiler expects me finish definition. possible make situation describing work? i tried in compiler. can declare class identical base, , use type checking, , derive when define it. presumably subcategory of base class looking for. however, won't exact type. if you're not looking partition hierarchy, still think base class should using, since looking for. class base {int unused;}; class base_specific : public base {}; class actual : public base_specific { public: actual (int i) : m(i

tfs2012 - Visual Studio extensions keep disappearing -

i no means visual studio expert. have done searching on topic , cannot find me. i'm working on vs 2010 web application. using tfs 2012 source control. wouldn't suprised if causing issue make special mention of it. the issue i'm having every morning after open project have go tools / extension manager , search online , add jscript editor extensions . when open project next day it's gone , have add again. (i think right in middle of coding - javascript window changes size , loses formatting) an extension stays every day regardless nuget package manager , it's not removing every extension. i suspect when latest tfs it's overwriting solution or project contains reference extension haven't been able verify this. can tell me why extensions removed? these local user setting or contained in project file? taking step back, real problem complete lack of integration between c# , javascript in web programming world. need can on javascript side.

haskell - Simplifying a GADT with Uniplate -

i'm trying answer this stackoverflow question, using uniplate suggested , the solution i've come far pretty ugly. this seems common issue, wanted know if there more elegant solution. basically, we've got gadt resolves either expression int or expression bool (ignoring codataif = if (b true) codataif codataif ): data expression :: int -> expression int b :: bool -> expression bool add :: expression int -> expression int -> expression int mul :: expression int -> expression int -> expression int eq :: expression int -> expression int -> expression bool , :: expression bool -> expression bool -> expression bool or :: expression bool -> expression bool -> expression bool if :: expression bool -> expression -> expression -> expression and (in version of problem) want able evaluate expression tree bottom-up using simple operation combine leaves new leaf: step :: expression -

javascript - PhantomJS copy file with overwrite -

reading document : copy(source, destination) currently, way cope check fs.exist('myfile') , manual delete prior copy: var fs = require('fs'); var filename = 'myfile-backup.txt'; if (fs.exists(filename)) { fs.remove(filename); } fs.copy('myfile.txt', filename); phantom.exit(); i don't know if there better way overwrite file. checking existing file may have potential problem when can't remove file. need more error handling approach. seems common task, know solution people come with. i have written small extension fs module. if try overwrite file fs.copy throw exception can catch error handling removing existing file. i added optional maxtrials argument if there problem file created every time in between copy trial , remove . var fs = require('fs'); fs.overwrite = function(source, destination, maxtrials){ var overwritten = false; var trials = 0; maxtrials = parseint(maxtrials) maxtrials =

Swift Optionals and Forced Unwrapping -

i having hard time understanding optionals , forced unwrapping in swift language. have read book , chapters several times cannot understand it. is there difference between following two: totalamounttextfield?.text.toint() totalamounttextfield!.text.toint() also, when declaring iboutlets why make optional field this: @iboutlet var nametextfield :uitextfield? if don't use "?" @ end gives errors. totalamounttextfield?.text.toint() equivalent func foo() -> int? { // give optional int if let field = totalamounttextfield { return field.text.toint() } else { return nil // return nil if totalamounttextfield nil } } foo() it should used if totalamounttextfield can nil totalamounttextfield!.text.toint() equivalent func foo() -> int { // give int if let field = totalamounttextfield { return field.text.toint() } else { crash() // crash if totalamounttextfield nil } } foo() it should

mongoid - Collection ID length in MongoDB -

i new mongodb , stack overflow. i want know why on mongodb collection id of 24 hex characters? importance of that? why default _id 24 character hex string? the default unique identifier generated primary key ( _id ) mongodb document objectid . 12 byte binary value represented 24 character hex string, , 1 of standard field types supported mongodb bson specification . the 12 bytes of objectid constructed using: a 4 byte value representing seconds since unix epoch a 3 byte machine identifier a 2 byte process id a 3 byte counter (starting random value) what importance of objectid? objectids (or similar identifiers generated according guid formula) allow unique identifiers independently generated in distributed system. the ability independently generate unique id becomes important scale multiple application servers (or perhaps multiple database nodes in sharded cluster ). not want have central coordination bottleneck sequence counter (eg. might have auto-in

javascript - Adding event listeners to dom dynamically -

i have created small script having objective calculate body mass index (bmi) based on input values. script looks this: var config = { "imc": { "weight": { "selector": "#weight", "triggers": [ "click", "focusout", "keyup" ] }, "height": { "selector": "#height", "triggers": [ "click", "focusout", "keyup" ] }, "result": { "selector": "#imc", "triggers": [ "click", "focusout" ] } } }; $.each( config.imc, function( name, attributes ) { console.log('adding events dom elements

sql - specifying a parameter instead of explicit value in process task -

Image
i have process task: i'm wondering whether it's possible pass it: $package::targetlocation thank guidance,. you should able expressions tab, create new expression against arguments property , assign user variable.

Sales commision not calculating in Java -

i running simple problem driving me insane. trying calculate commission of sales , add salary when run code gives me commission of $0 , compensation of $0. here code have far: package compensationcalculator; import java.text.numberformat; public class compensationcalculator { private double salary = 75000; private double sales; private double commission; private double compensation; public compensationcalculator() { this.salary = 75000.00; } public void setsales(double sales) { this.sales = sales; } public double getcommission() { this.commission = (sales * 0.2); return commission; } public double getcompensation() { this.compensation = (salary + commission); return compensation; } public string tostring() { numberformat fmt = numberformat.getcurrencyinstance(); return ("annual salary: " + fmt.format(salary) + "\n"

Android Video Strange Behaviour on amazon TV -

i developing android video app,in playing video in loop continuously. playing video using video view api ,this app working fine on kindle fire tablets when play app on amazon tv, video view stop playing video after time null uri exception, , tried play video media player , surface view on amazon tv getting same problem,after time video stop , last image shown, body have idea why behavior ??? i think because of eclipse problem have downgrade sdk or test on other system.

java - Improving application performance with large queries -

i looking using caching improving website performance , thought of implementing in application. i have scenario executing large query list of orders based on order status , customer/supplier. there can other filters selected @ runtime user. query complex lot of joins amongst tables. can implement caching memcached/redis in anyway improve performance in area storing orders object in cache order id key , order object value when created , write logic fetch list or orders runtime filters applied or need run query fetching orders? also there simple queries orders object ordernumber. can cache these avoid db query? please let me know of possible solution improving site performance. thanks in advance :)

html - change background color every 5 press with php only -

i need make button php. fifth time when pressed should change background color random 1 , keep of every 5 presses. after 5 press background color should change again , keep until next 5 press here code <?php session_start(); $_session['counter'] = isset($_session['counter']) ? $_session['counter'] : 0; if($_post['sub']) { $_session['counter']++; echo "<br/>"; echo $culoare; echo "<body bgcolor='<?phpecho $culoare;?>'></body>"; } ?> </head> <body > <form action='' method="post"> <input type="submit" name="sub" value="click" /> <input type="hidden" name="counter" value="<?php print $_post['counter']; ?>" /> </form> </body> what problem? have code. when form submitted, value of counter in hidden field. if value not equal 5, increme

r - Time series with multiple periods and non negative values -

when read time series in ts object , put period: tr <- ts(data[,4],frequency=) . works 2 different periods , decomposes show (downward) trend, seasonality , error. how know correct period. when use ets or stlf function in forecast package on above ts object, summary shows: model information: ets(a,n,n) why that? have seasonal+trend component here? what can deal negative values when training set non-negative , negative values make no sense. what correct period depends on data generating process. instance, if looking @ monthly data driven consumer habits, then, if presume consumer behavior fluctuates based on changing circumstances throughout year, since data monthly, 12 frequency select. important keep in mind periodicity multiplicative. if, instance, 12 , 24 work, i'd go 12. if have quarterly data, maybe 4 frequency select. alternatively, if looking @ physical process, temperature in engine, , have millisecond data, maybe appropriate period number of

svn - Does SubGit require an own GIT installation -

the question simple: i have external svn-repository (foreign network) , want establish local network git-environment. subgit can synchronize svn to-be-done git-server, need know if need install own git-server or subgit "include" git-server-installation? so subgit "converter" like: svn<->subgit<->git (master repo) or subgit git-server like: svn<->subgit (=master repo) (no git required) thanks help! subgit doesn't include git server, should install server on own. note, subgit uses 'pre-receive' , 'post-receive' git hooks, should use server runs these hooks when pushes commits server (nearly servers that, except gerrit --- there's issue that). example can use atlassian stash server , subgit plugin it. so subgit rather svn<->subgit (=master repo), need no git repository on server. set access repository local network.

Rails Facebook-omniauth, Devise - Why can't I use environment variables? -

i had omniauth devise working in app, moved facebook credentials environment variables, , i've checked in console make sure defined. started seeing show in server logs: (facebook) callback phase initiated. facebook) authentication failure! invalid_credentials: oauth2::error, : {"error":{"message":"error validating client secret.","type":"oauthexception","code":1}} when try have test users authenticate facebook. i've checked app_id , app_secret. both set , match credentials in fb developer dashboard. i tried deleting facebook app , creating brand new 1 (updated id , secret). i tried create new users hadn't authed omniauth yet, no luck. lastly, tried reverting hardcoded facebook credentials. worked! why can't use environment variables these credentials? i'm using heroku, , double checked make sure set. used initializer in local environment, , correctly set there well. here's implementati

Show cursor at particular position on Edittext android -

i developing application in using multi-line edittext width , height both match_parent takes whole screen size. if user clicks or touches on particular position of edittext , cursor should visible @ particular position , user can start typing particular position. i had search google , developers.android type of property in edittext class didn't find it. you can use edittext1.setselection(index) position caret specific position want be. the index position want place caret based of character array of string.

How to git svn clone full history despite svn copy -

in company switch svn git. svn use big, doesn't have svn layout , on every version split made svn copy. svn repository structur: svnserver.company.de product xy majorversionnumber 1 majorversionnumber 2 majorversionnumber 3 minorversionnumber 3.0.0 minorversionnumber 3.0.1 minorversionnumber ... majorversionnumber 4 .... product zw what want or expecting git do: git svn clone clone files 1 subfolder / copy full history of these files (like tortoise unchecking "stop on copy/rename"). what git doing: git svn clone --prefix=origin/ --username=spe --authors-file=authors.txt https://svnserver.company.de/repos/product/majorversionnumber/master/source product -> clone files 1 subfolder / copy history until copy has taken place. the question: has git equivalent svns "stop on copy/rename" or how clone full history despite svn copy? what have found far: git-svn - import full history work-around failing "git svn clone&qu

utf 8 - putty not printing utf-8 characters on serial connection -

i using serial connection access serial port of beagleboard. rootfs on beagleboard using busybox. have set encoding=utf-8 in putty. when paste chinese characters on screen converted "?" ls showing correctly. example paste ls 技术笔记 on screen. linux#> ls ???? 技术笔记 i wonder why chinese characters converted "??" on copy pasting in putty window. when connect other linux machine using putty via ssh, there no problem , characters displayed correctly on putty window. edit 1: copy pasting 1st character, 技, putty generates correct utf-8 code , send serial port. added printk @ tty layer print hexadecimal character received tty layer. linux#> [ 0][ 220.604000] e68a [ 0][ 220.608000] 80?d -/bin/sh: 技: not found e6 8a 80 utf-8 code corresponding 技. *nix: ... install locale locale-gen dpkg-reconfigure locales putty > settings > window > font settings > font > change...

ios - Assigning nil to generic optionals in Swift -

i've created simple generic grid data structure in swift follows. creates array of optionals type t? , initialises array with nil. when try explicitly set 1 grid element nil compiler complains don't understand. struct grid<t> { let columns: int, rows: int var grid: [t?] init(columns: int, rows: int) { self.rows = rows self.columns = columns grid = array(count: rows * columns, repeatedvalue: nil) } func test() { grid[0] = nil } } compiler's outcry when test() function added: grid.swift:26:13: '@lvalue $t7' not identical 't?' the error message misleading. test() method modifies value of property in structure, therefore have mark "mutating": struct grid<t> { // ... mutating func test() { grid[0] = nil } } see modifying value types within instance methods in swift book: modifying value types within instance methods structures ,

Average Row [SQL] -

actually i'm bit confused should wrote in subject. the point this, want average speed01,speed02,speed03 , speed04 : select table01.test_no, table01.speed01, table01.speed02, table01.speed03, table01.speed04, i want create new column consists of average -->> avg(table01.speed01, table01.speed02, table01.speed03,table01.speed04) "average" i have tried this, did not work. from table01 so, contain of speed column exist speed02 don't have number others have numbers. speed04 data missing , others exist, 1 data (example: speed01) have data. lets depends on sensor ability catch speed of test material. it big if can find solution. i'm newbie here. thank ^^ avg sql aggregate function, therefore not applicable. math. average sum divided count: (speed01 + speed02 + speed03 +speed04)/4 to deal missing values, use nullif or coalesce: (coalesce(speed01, 0) + coalesce(speed02, 0) + coalesce(speed03, 0) + coalesce(spee

Spring Beginner - No such field error -

i new spring. developing 1 sample project using spring. getting following exception when provide value in beans.xml. please provide solution. beans.xml: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="helloworld" class="com.dhr.spring.beans.helloworld"> <property name="message" value="d" /> </bean> </beans> helloworld.java: public class helloworld { private string message; public void setmessage(string message){ this.message = message; } public void getmessage(){ system.out.println("your message : " + message); } } mainapp: public class mainapp { public static void main(

c++ - TLE for large inputs. How to run my code within the time limit? -

problem link- http://www.spoj.com/problems/lastdig/ summary-given 2 non negative integers , b, print last digit of a^b. i tried using algorithm find modular exponentiation using less memory space( http://en.wikipedia.org/wiki/modular_exponentiation#memory-efficient_method ) getting tle(time limit exceeding) error solution. changes should make run code in within 1 second? note 10 test cases need run within 1 second. my solution: #include<iostream> #include<vector> #include<cstring> #include<cmath> #include<algorithm> #include<cstdlib> typedef long long ll; using namespace std; int me(ll a, ll b) { ll c=1; int e=0; while(e<b) { c=(c*a)%10; e++; } return c; } int main() { int t; ll a, b; vector <int> ldigit(31); cin>>t; for(int i=0;i<t;i++) { cin>>a>>b; if(b>=99999) ldigit[i]=me(a, b); else {

internet explorer - CSS Blurry text in IE -

i using following give text blurry effect: html: <h1 class="blur">blurry text here</h1> css: .blur { text-shadow: 0 0 2px #333333; filter: progid:dximagetransform.microsoft.chroma(color=#333333), progid:dximagetransform.microsoft.motionblur(strength=0, direction=0), progid:dximagetransform.microsoft.blur(pixelradius=2); color: transparent; } here jsfiddle preview. it works in ff, chrome , more or less in ie8, when testing in ie11, text invisible. i know due color: transparent; , if change color: rgba(0,0,0, 0.5); , blur hardly visible. i never thought have find fix ie11 opposed ie8, know of work around this? ie10 , higher reads text-shadow text-shadow: xpx xpx #colour; in other words, put syntax incorrectly. see here more info on correct usage text-shadow. you put: .blur { text-shadow: 0 0 2px #333333; filter: progid:dximagetransform.microsoft.chroma(color=#333333), progid:d

r - finding non-identical entries across a row -

i have 2380 rows data.frame looks this: > nstudentid1 nstudentid2 nstudentid3 1 80501010 80501010 80501010 2 80501022 80501022 80501022 3 80501005 80501005 80501005 4 80501003 80501003 80501003 5 80501026 80501026 80501026 6 80501025 80501025 80501025 as can see variables subject id's. each subject got 3 id's cross-validation. usually want find duplicated entries within coulmn, did. now check if each subject (row) has exactley same id number across 3 id variables. i ran general check: all(student1$nstudentid1 == student1$nstudentid2) all(student1$nstudentid1 == student1$nstudentid3) all(student1$nstudentid2 == student1$nstudentid3) and got false answer. how find non-identical row numbers? any advice help use condition filter : condition <- student1$nstudentid1 == student1$nstudentid2 & student1$nstudentid1 == student1$nstudentid3 & student1$nstudentid

angularjs - angular bootstrap dropdown in a table cell -

Image
i'm trying put angular bootstrap dropdown in table. dropdown gets cut off @ end of cell. in image, 'another option' gets cut off. if used normal select/option, (the dropdown floats on table , isn't constrained cell size. can same effect achieved bootstrap dropdown? unless attach code , there not can you.. if helps - link working example of bootstrap dropdown button in table row http://plnkr.co/edit/x4b7javthmzddxwfhdnt?p=preview

javascript - Using requestAnimationFrame as a Timer -

this multi-player "guess word" turn-based game working on. i have page supposed count down given number. if word-guess submitted before time limit, signalr hub method called. if 0 reached, different signalr hub method called. in both cases, hub method sends message out relevant clients (in group). someone recommended, instead of js timer, can use requestanimationframe updates every 17 milliseconds. so here requestanimationframe code have in play.aspx file... function turntimeron() { //called server code startup script var timerstep = '<%=application(session("gameid") & "_timelimit")%>'; timerstep = number(timerstep); var startt = date.now(); var timedifference = 0; var countdown = document.getelementbyid('secondsleft'); requestanimationframe(function anim() { requestanimationframe(anim); startt = startt || date.now(); countdown.innerhtml

php - CakePHP 2.x - Database Switching On The Fly (For The Whole App) -

background: have admin system, needs connect , edit multiple databases. database structures 100% similar each other, data varies. what have tried: i'v tried use $this->model->setdatasource('db_variable_here'); in controllers change database on fly. problem this, related data seems still default database. example: imagine this: user habtm post , if want post different database, , use $this->post->setdatasource('db_variable_here'); achieve this, seems still related user default database, , not same 1 got post from. i'm guessing due fact change database on model post , fixed doing $this->model->setdatasource('db_variable_here'); each related model. my question: possible change datasource every model in app on fly? ex. like: $this->setdatasource('datasource_name') ? or have manually related models? you try making own getdatasouce method in appmodel. you can see cakephp 1 here: https://github.com/cak

android - Show a fragment on a Dialog Fragment or Popupwindow from a FragmentActivity -

hi have code emojiicons want show if user clicks on emoji logo. cant make toggle between keyboard alternative doing this. //r.layout.popup_item <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:emojicon="http://schemas.android.com/apk/res-auto" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" tools:context="com.rockerhieu.emojicon.example.mainactivity$placeholderfragment" > <com.rockerhieu.emojicon.emojicontextview android:id="@+id/txtemojicon" android:layout_width="fill_parent" android:layout_height="wrap_content"/> <com.rockerhieu.emojicon.emojiconedittext android:id="@+id/editemojicon" android:layout_width="fill_parent" androi

msbuild - Processing batch items in parallel -

i have itemgroup, , want process items in parallel (using custom task or .exe). i write task/exe accept entire itemgroup , process items in parallel internally. however, want parallelism work in conjunction msbuild's /maxcpucount param, since otherwise might end over-parallelizing. this thread says there's no way. my testing shows msbuild's /maxcpucount works building different projects , not items (see code below) how can process items itemgroup in parallel? there way author custom task work in parallel in conjunction msbuild's parallel support? <project toolsversion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <target name="build" > <!-- runs once - guess msbuild detects it's same project --> <!--<msbuild projects="$(msbuildprojectfullpath);$(msbuildprojectfullpath)" targets="wait3000" buildinparallel="true" />--> <!--

sql - Hidden condition to all possible queries -

i'd hide selecting objects not rewriting sql queries more simple way. so, i'd add rule (or else) database particular table. e.g. if delete user website execute next: update user_common set is_deleted='t' user_id=1234 and there no need rewrite existing queries users, condition hidden: select first_name, second_name user_common coins>200 the select above executed hidden condition, e.g.: select first_name, second_name user_common coins>200 , is_deleted!='t' how make working? you can accomplish want view. create view v_table select uc.* user_common uc is_deleted <> 't'; the key references table need change view. 1 way renaming table , creating view same name: alter table user_common base_user_common; create view user_common select uc.* user_common uc is_deleted <> 't';

c++ - Registry functions not working under some circumstances -

i need programmatically disable windows error reporting in c++ application. this, want edit windows registry , write 2 values it. the following code works on 32 bit windows 7 machine: #include <stdio.h> #include <windows.h> void disablewer() { hkey key; printf("%d\n", regopenkey(hkey_local_machine, text("software\\microsoft\\windows\\windows error reporting\\"), &key)); dword val = 1; printf("%d\n", regsetvalueex(key, text("disable"), 0, reg_dword, (const byte*)&val, sizeof(val))); regclosekey(key); } int main() { disablewer(); printf("%d\n", getlasterror()); getchar(); } both functions succeed (return error_success), getlasterror() prints 0, , required value set in registry. on vps program output same, registry isn't modified - nothing happens. can set value manually using regedit, presume it's not privilege related problem. vps

c# - Format of Convert.ToDateTime(string) method -

when execute convert.todatetime('08/01/2014') how convert 1-aug-2014 (ignore format) , not 8-jan-2014? as far saw, there no mention of format string parameter being passed on method. first of all, convert.todatetime("08/01/2014") not convert.todatetime('08/01/2014') . strings represents double quotes, not single quotes. convert.todatetime(string) method uses currentculture iformatprovider default. here how it's implemented ; public static datetime todatetime(string value) { if (value == null) return new datetime(0); return datetime.parse(value, cultureinfo.currentculture); } and datetime.parse(string, iformatprovider) implemented as; public static datetime parse(string s, iformatprovider provider) { return (datetimeparse.parse(s, datetimeformatinfo.getinstance(provider), datetimestyles.none)); } from documentation ; if value not null, return value result of invoking datetime.parse method on valu

c++ - Initialisation of char array to string value, are the uninitialised indices set to null? -

if have following: char test[10] = "#"; is test[1] through test[9] guaranteed \0 ? or test[1] guaranteed \0 ? this definition char test[10] = "#"; is equivalent to char test[10] = { '#', '\0' }; that 2 elements of array initialized explicitly initializers. other elements of array 0 initialized implicitly set tto '\0' according c++ standard (section 8.5.2 character arrays) 3 if there fewer initializers there array elements, each element not explicitly initialized shall zero-initialized (8.5).

Python process a csv file to remove unicode characters greater than 3 bytes -

i'm using python 2.7.5 , trying take existing csv file , process remove unicode characters greater 3 bytes. (sending mechanical turk, , it's amazon restriction.) i've tried use top (amazing) answer in question ( how filter (or replace) unicode characters take more 3 bytes in utf-8? ). assume can iterate through csv row-by-row, , wherever spot unicode characters of >3 bytes, replace them replacement character. # -*- coding: utf-8 -*- import csv import re re_pattern = re.compile(u'[^\u0000-\ud7ff\ue000-\uffff]', re.unicode) ifile = open('sourcefile.csv', 'ru') reader = csv.reader(ifile, dialect=csv.excel_tab) ofile = open('outputfile.csv', 'wb') writer = csv.writer(ofile, delimiter=',', quotechar='"', quoting=csv.quote_all) #skip header row next(reader, none) row in reader: writer.writerow([re_pattern.sub(u'\ufffd', unicode(c).encode('utf8')) c in row]) ifile.close() ofile.clos

Android studio add external project to build.gradle -

i have sample project, following setup: /root + pure java lib + android test lib + android test project where ' test project ' dependent on ' test lib ', , last depends on ' pure java lib ' compiling project , launching setup works fine. i'm thinking importing previous eclipse workspace , work android studio, problem project setup different, , keep way. for example if use previous example: /root + android test lib + android test project /some other folder (another repository example) + pure java lib i've tried many configurations, didn't find way reference project outside scope of parent folder (' root ' in example case). in many platforms/modules can use '..' move in folders didn't work me, perhaps i've used wrong. does know how can achieved gradle? update i'll try more generic: /c:/ /project + module 1 - pure java + module 2 - android test lib + module 3 - android tes

QML - Move to top bottom of flickable -

how tell flickable move bottom of current page. qml - move top #top not provide answer this. you need calculate , set contenty. e.g: flickable { width: 200; height: 200 contentwidth: image.width; contentheight: image.height image { id: image; source: "file:///path/tobigimagefile" } contenty : contentheight-height }

derby - How to resolve java.lang.ClassNotFoundException: DerbyLogSetting -

i dealing derby perform database related functions in java project. java project command line project. accomplish this, have added derby.jar libs folder of project, though on running application netbeans, getting error : mon aug 18 17:32:23 ist 2014 thread[awt-eventqueue-0,6,main] java.lang.classnotfoundexception: derbylogsetting ---------------------------------------------------------------- mon aug 18 17:32:23 ist 2014: booting derby version apache software foundation - apache derby - 10.8.1.2 - (1095077): instance a816c00e-0147-e8ff-2d32-000003436058 on database directory my_database_path\database_path class loader sun.misc.launcher$appclassloader@430e468f loaded file:/my_project_path/derby.jar java.vendor=oracle corporation java.runtime.version=1.7.0_45-b18 user.dir=my_project_path derby.system.home=null derby.stream.error.method=derbylogsetting.disablederbylogfile database class loader started - derby.database.classpath='' same happening when running exe of pr

python - Construct DatetimeIndex if you only have year -

i have data of structure country year pop 606 algeria 1966 12339.140 730 algeria 1968 13146.267 793 algeria 1969 13528.304 856 algeria 1970 13931.846 924 algeria 1971 14335.388 now want create first-differences per country based on year (difference per year). if weren't interval concern, i'd along lines of df.sort(['country', 'year']).set_index(['country', 'year']).diff() instead, guess have convert year to_datetime() first. there simple way create datetime column contains years only? , there different more natural approach create differences on time? you do df.set_index(df.year.map(lambda x: datetime.datetime(x, 1, 1))) that uses concept of left-open intervals. another possibility is df.set_index(df.year.map(pd.period)) both return equally well-defined indexes, in latter case might output of df.diff() better since states year.

java - Read property of an annotation in another -

if declare attribute class way: @order(value=1) @input(name="login") private string login; and definition @input this: @retention(retentionpolicy.runtime) @target(elementtype.field) public @interface input { string type() default "text"; string name(); string pattern() default ""; string tag() default "<custom:input ordem=''/>"; } is there way read property value @order , use property tag @input ? one of ways of reading metadata such annotations,fields , classes reflection.you can use reflection read meta -data of annotation too. this work if @order annotation has runtimepolicy of runtime @retention(retentionpolicy.runtime) note :- annotations class objects.each annotation special type of interface , interfaces treated java.lang.class objects. field loginvariaable = .../// login attribute class object using reflection order order = loginvariaable.getannotation(order.class) int or

angularjs - Can't get sbt-mocha to see Angular webjar mocks library properly -

i can't angular mocks or angular recognized in sbt-web / sbt-mocha project. i writing sample based on sbt-web play http://typesafe.com/activator/template/play-2.3-highlights highlights sample. killed other plugins left sbt-mocha one. i declared dependencies in librarydependencies: librarydependencies ++= seq( "org.webjars" % "jquery" % "2.1.0-2", "org.webjars" % "angularjs" % "1.3.0-beta.18", "org.webjars" % "angular-ui-router" % "0.2.10-1", "org.webjars" % "squirejs" % "0.1.0" % "test", "org.webjars" % "chai" % "1.9.1" % "test" ) i wrote angular app constant , dropped in assets/javascripts app.js: angular.module('myapp', []) .constant('pi', math.pi); next, wrote test: (function() { 'use strict'; describe('angular spec', function() { befor

javascript - JS string split using regex confusion -

hi trying split string using regex results different expect. var text = 'p$blank$a$blank$l$blank$a$blank$c$blank$e$blank$'; > text.split(/(\$blank\$).\1/g); ["p", "$blank$", "l", "$blank$", "c", "$blank$", ""] what want ["p", "$blank$a$blank$",l, "$blank$a$blank$", "c", "$blank$e$blank$"] this the docs suggest: if separator regular expression contains capturing parentheses, each time separator matched, results (including undefined results) of capturing parentheses spliced output array. the capturing parentheses include first $blank$ , that's gets included in array. if want whole split string included, you'll need: text.split(/(\$blank\$.\$blank\$)/) ["p", "$blank$a$blank$", "l", "$blank$a$blank$", "c", "$blank$e$blank$", ""] the empty string

Print multipaged WPF control without page breaking on a line of data C# -

i made invoice has listview on bottom list of line items. can run on 1 page mark overloaded documentpaginator class allow me print multiple pages. however, cuts page in middle of line of listview. found article uses bitmap of wpf control, checks color of pixels of line determine if there whitespace or data (code below). when make control bitmap though, spacing , line height different when print wpf control xps or printer. other ideas out there on how intelligently break pages or bitmap match xps? private void getgoodcut() { int goodcut = _lastcut; int lastnumber = 0; int numbercount = 1; // @ most, take 32 pixel lines find white space (int = 0; < 32; i++) { int number = rowpixelwhitecount(_bitmap, goodcut); goodcut--; if (number == lastnumber) { numbercount++; // white space count between lv lines 12 if (numbercount == 12)