Posts

Showing posts from April, 2012

Does F# use lazy evaluation by default? -

does f# have lazy evaluation? f# not lazy-by-default (a la haskell). explicit laziness available. see lazy computations on msdn.

java - When using Maven, how can I separate variables for local/dev/production? -

i'd have single maven build produce artifact can used on local machine, our dev environment, staging environment, or production. since we're talking production, means db credentials can't in artifact anywhere. this spring app we're using maven resource filtering , profiles ( local , dev , stage , prod ) filter properties in application.properties file , other files (email templates, etc). have build separate artifact each environment. we have been able db passwords out of pom using @propertysource annotation still seems we're missing must common problem. i've been able find similar questions answers seem have problem or 2 - common of having sensitive properties production in artifact.

python - Report on custom parameters without forking Locust -

i'm measuring performance of various components of app , i'd statistics using locust load testing framework. currently, there's way measure average response time using built-in locust method . is possible statistics on custom parameter (which part of server response) , add reports without forking locust? perhaps monkey-patching options available?

printf - String not printing fully C -

note: homework, want know why messed print, not finished program. #include <stdio.h> char get_band( int band_number, char band_color[] ); void get_resistance( int resist, int power ); int main() { int resist; int power; get_resistance(resist, power ); } void get_resistance( int resist, int power ) { int band_number; char band_color[3]; char color[3]; get_band( band_number, band_color ); printf("%s", band_color); } char get_band( int band_number, char band_color[] ) { int x; x=0; while (x < 3) { printf("which band select? (1-3)\ndo not select 1 have selected prior!\t"); scanf("%d", &band_number); if (band_number = 1) { printf("what color assign here?\t"); scanf("%s", &band_color[0]); x++; } else if (band_number = 2) { printf(...

php - Laravel 5.1 working with redis -

here routes.php route::get('hello1',function(){ redis::publish('test-channel', json_encode(['foo' => 'bar'])); }); here app.js var app = require('express')(); var http = require('http').server(app); var io = require('socket.io')(http); var redis = require('ioredis'); var redis = new redis(); app.get('/', function(req, res){ res.sendfile(__dirname + '/index.html'); }); redis.subscribe('test-channel', function () { console.log('redis: test-channel subscribed'); }); redis.on('message', function(channel, message) { console.log('redis: message on ' + channel + ' received!'); console.log(message); message = json.parse(message); io.emit(channel, message.payload) }); io.on('connection', function(socket){ console.log('a user connected'); socket.on('disconnect', function(){ console.log('u...

java - Unable to configure Springs external jar in jboss 7 module. -

added module dependency in jboss-deploymentstructure xml jbossdeploymentstructure.xml used inside spring application <jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1"> <deployment> <exclusions></exclusions> <dependencies> <module name="com.ondot.cm.commons.commons" /> <module name="com.ondot.cm.properties" /> </dependencies> </deployment>

c# - SignalR Incorrect Content-Type from javascript call -

when make call signalr (cross-domain) server javascript fails call telling oops. 500 internal server error system.invalidoperationexception incorrect content-type: @ microsoft.aspnet.http.features.internal.formfeature.d__12.movenext() @ system.runtime.compilerservices.taskawaiter.throwfornonsuccess(task task) @ system.runtime.compilerservices.taskawaiter.handlenonsuccessanddebuggernotification(task task) @ system.runtime.compilerservices.configuredtaskawaitable.configuredtaskawaiter.getresult() @ microsoft.aspnet.signalr.taskawaiterhelper.preservecultureawaiter.getresult() @ microsoft.aspnet.signalr.transports.longpollingtransport.d__28.movenext() @ system.runtime.compilerservices.taskawaiter.throwfornonsuccess(task task) @ system.runtime.compilerservices.taskawaiter.handlenonsuccessanddebuggernotification(task task) @ system.runtime.compilerservices.configuredtaskawaitable.configuredtaskawaiter.getresult() @ microsoft.aspnet.signalr.ta...

inference - Inferencing in embedded triples of Marklogic -

i have following 2 documents. 1 document has data: <content> <sem:triples xmlns:sem="http://marklogic.com/semantics"> <sem:triple> <sem:subject>http://sector#basic_materials</sem:subject> <sem:predicate>http://relationship#istrbceconomicsectorof</sem:predicate> <sem:object>http://company#cst_mining_group_limited</sem:object> </sem:triple> </sem:triples> <analystname>henrik christiansson</analystname> <documentformat>pdf</documentformat> </content> and document has following data: <content> <sem:triples xmlns:sem="http://marklogic.com/semantics"> <sem:triple> <sem:triple> <sem:subject>http://sector#energy_-_fossil_fuels</sem:subject> <sem:predicate>http://relationship#istrbceconomicsectorof</sem:predicate> <sem:object>http://company#bodycote...

How to add background color for different dates of calendar using jquery? -

$('#calendar').fullcalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicweek,basicday' }, defaultview: 'month', dayrender: function (date, cell) { var today = new date(); if (date.getdate() === today.getdate()) { cell.css("background-color", "red"); } } });

bash - Passing pipe output to Test command -

i'm confused test command syntax. goal check if file exists, file path formed sed command. so, try, example: echo '~/test111' | sed s/111/222/g | test -f && echo "found" || echo "not found" but command returns "found". doing wrong? with currenty approach, saying: test -f && echo "yes" || echo "no" since test -f returns true default, getting "yes": $ test -f $ echo $? 0 the correct syntax test -f "string" : so want say: string=$(echo '~/test111'|sed 's/111/222/g') test -f "$string" && echo "found" || echo "not found" which can compacted into: test -f "$(echo '~/test111'|sed 's/111/222/g')" && echo "found" || echo "not found" but looses readability. and can use xargs perform given action in name given previous pipe: echo '~/test111'|...

find by xpath only in child of element with c# selenium -

i have code : readonlycollection<iwebelement> questions = driver.findelements(by.xpath("//fieldset[@data-seleniumrp='question']")); foreach (iwebelement question in questions) { readonlycollection<iwebelement> repdispo = question.findelements(by.xpath("//input[@data-selenium-positionquestion]")); } my collection "questions" have 11 elements, right ! each "question" normaly have 4 elements ... code , have 44 results ( elements in page ) in "repdispo" ... how childrend element , not element ? i suspect problem in xpath inside foreach loop. need add . @ beginning of // axis make relative current question element : ".//input[@data-selenium-positionquestion]"

c++ - Cannot register regsvr32 a DLL with Boost on it -

i'm trying regsvr32 activex dll boost on it, far can build dll fine. however issue regsvr32 keeps on failing. possible workaround can found here: http://binglongx.com/tag/regsvr32/ if try add boost_all_dyn_link gives error "mixing dll boost library static runtime bad idea..." remove there's no such error. when removed, dll can built fine. now question how able regsvr32 activex dll boost on it? have tried , made work?

javascript - Fancybox modifiy. How to modify fancybox to stop at last item on each gallery? (gallery 1 gallery 2 etc) -

this question has answer here: how create separate fancybox galleries on same page? 1 answer i'm using fancybox plugin photo gallery. have multiple galleries more items (photos) , want know how stop slideshow when hits last item on each gallery. fancybox.js not modified. thanks you need add option loop: false when calling in fancybox. you can read more options in the fancybox docs

.htaccess - Rewriteurl in htaccess -

in site need rewrite url i'm not capable define rewriterule , rewritecond conditions: http://www.stiloweb.it/component/search/?keyword= keywords &searchwordsugg=&option=com_virtuemart&page=shop.browse&view=category should become http://www.stiloweb.it/component/virtuemart/?keyword= keywords &search=true&view=category&option=com_virtuemart&virtuemart_category_id=0 i'm hoping help. thanks try adding rule top of htacess file om document root: rewritecond %{query_string} ^keyword=([^&]+)&searchwordsugg=&option=com_virtuemart&page=shop.browse&view=category$ rewriterule ^component/search/$ /componet/virtuemart/?keyword=%1&search=true&view=category&option=com_virtuemart&virtuemart_category_id=0 [l,r]

Typescript: declare return type to be dependent on argument value? -

i have following function call: this.get('barcode').scan(); is possible define function in way return type determined value of function argument. in case 'get' returns barcode class if called 'barcode' , mqtt class if called 'mqtt'. yes, can use overload on strings this. example: interface barcodescanner { scan(): number; } interface accelerometer { getacceleration(): number; } class myclass { get(name: 'accelerometer'): accelerometer; get(name: 'barcode'): barcodescanner; get(name: string): any; // fallback string signature get(name: string): { // implementation signature, not visible /* ... */ return undefined; } something() { let x = this.get('barcode'); x.scan(); // ok let y = this.get('accelerometer'); y.getacceleration(); // ok } }

gradle android ndk build -

i'm trying build cocos2dx c++ project on android using gradle (previously ant ). want have 2 gradle tasks: 1) build c++ , java. found solution task buildcpp(type: exec) { commandline ... // command } tasks.withtype(javacompile) { compiletask -> compiletask.dependson buildcpp } 2) build java without cpp. how? note. ant can define 2 targets: <!-- build --> <target name="buildall" description="build all: ndkbuild -> javac" depends="setdebugflagtrue, ndkbuild, buildjavasigned"/> <!-- build java --> <target name="buildjavasigned" description="javac" depends="setdebugflagfalse, clean, release"/> how can gradle? seems ant more flexible gradle.. hmm... think may want have more flexible solution, honest. gradle's usage of ndk not best , there ways add more flexibility native builds without losing other benefits of using gra...

c# - File reading/writing speed -

in ntfs, reading/writing speed of file(with known path) influenced number of files in same folder? es: var data = system.io.file.readallbytes(aknownpath); locating file takes more time per each file in directory. reading opened file constant.

java - How to make my URL to only be "localhost:8080/*"? -

i'm starting out giving spring mvc have no idea i'm doing. therefore, started following series of tutorials on youtube. i've followed them step step differing in i'm using sts instead of og eclipse set project tut can't see why matter. towards end make index.jsp page, restart server, , navigate localhost:8080/index.html , "problem" begins. have use localhost:8080/test/index.html in order avoid 404 error. i think answer obvious i'm not clear why mine's different tut's though followed it, names aside, exactly. how make url localhost:8080/* ? don't want /test/ included. beginning of pom.xml: <modelversion>4.0.0</modelversion> <groupid>my.name.spring.test</groupid> <artifactid>blog-aggregator</artifactid> <version>0.0.1-snapshot</version> <packaging>war</packaging> web.xml: <?xml version="1.0" encoding="utf-8"?> <web-app xm...

security - Single quote character in query string causes SQL injection -

i wondering if adding single quote mark embedded query string parameter in hard coded sql query cause sql injection error? can see after @docnum parameter using both percent , single quote characters. somewhere in code causing error. if use single percent character % instead of both % , single quote character %' unlike in stringbuilder appended line below stop error occurring? sb.append("and docnumtcn thumbsdown @docnum%' " ); if i'm correct here, suspect you're trying document number can like another. perhaps you're trying achieve this: sb.append("and docnumtcn '%' + @docnum + '%' ") the confusing part thumbsdown field you've got in there.

if statement - C# Error with 'continue' -

i'm trying use if statement bool make if code runs once not run again. here code using. int random = program._random.next(0, 133); if (random < 33) { bool done = false; if(done) { continue; // error shown statement } console.writeline("not done!"); done = true; } the error visual studio displaying is: "no enclosing loop out of break or continue". depending on class/method requirements, possibly reverse logic: if (!done) { console.writeline("not done!"); done = true; }

sql - Select command for cloudera impala to convert hexadecimal to ip address -

i need select statement format cloudera impala convert hexadecimal ip address. suppose hexadecimal number given (as shown below). how convert impala select statement like:- a.59.fc.6 you in hive using split split string , conv convert base 16 base 10; unfortunately although impala support conv , doesn't seem impala has split udf built in, if you're stuck impala might have write own :( hive code : select concat( cast(conv(split(ipcolumn,'[.]')[0],16,10) string), '.', cast(conv(split(ipcolumn,'[.]')[1],16,10) string), '.', cast(conv(split(ipcolumn,'[.]')[2],16,10) string), '.', cast(conv(split(ipcolumn,'[.]')[3],16,10) string) ) mytable;

How to make a scopebar in UISearchController always visible in Ios swift? -

i want implement functionality in uisearchcontroller , scopebar , don't want scope bar hidden. want visible , functional. currently, visible on first view load , hides after search filter applied. then, going forward, becomes visible on click of search bar. if want scope bar visible, may want hook separate uisegmentedcontrol , not use scope bar @ not have mess around uisearchcontroller's default behavior. also, this question may guide answer.

PyMongo inserting BSON document to MongoDB -

i insert new document mongodb collection. my first input string shown here: { "date" : isodate("2013-10-06t18:11:26.329z"), "engines" : {}, "expiration_date" : isodate("2013-10-06t18:11:36.329z"), "file_name" : "elad.elad", "scan_status" : "test", "task_id" : "4ce4ae9e-ef0a-476a-8189-92a5bfe328bd" } i'm creating bson.bson object string: b=bson.bson(doc) i'm trying insert collection in mongodb: collection.insert(b) but following error: typeerror: 'str' object not support item assignment does know problem here? you can directly convert string bson, either require json.loads or bson.encode method. you can use following code : import datetime pymongo import mongoclient db = mongoclient().test collection = db.some doc = { "date" : datetime.datetime.strptime("2013-10-06t18:11:26.329z"...

php - Insert checkboxes into database -

** update ** i have updated code still no joy in getting join table update i have 3 tables: docs doc_id doc_name doc_content cat cat_id cat_name cat_color cat_icon cat_doc_join id cat_id doc_id i have ability create , insert data docs table, inserts doc_name , doc_content table fine. have introduced categories new_doc.php form shows array of categories available can selected via checkbox. stands unsure on how amend insert query take id of doc creating , id of selected checkboxes have selected , go on not insert docs table insert row(s) doc_cat_join table if 1 or more categories had been selected: here script handles insert: <?php require ('../../db_con.php'); error_reporting(e_all); ini_set('display_errors', '1'); // form validation & submission if ($_server['request_method'] == 'post') { $errors = array(); // begin errors array // check first name if (empty($_post['doc_na...

Can Pebble app launch its companion app programmatically? -

the pebble mobile app attempt keep app running long pebble watchapp running. however, under circumstances, phone may kill pebble app , app. if occurs, pebble mobile app automatically restarted (and javascript code it). as pebble's documentation mentioned here , official pebble app launched automatically while connected pebble watch running js extended app. my question can launch companion app programmatically pebble watch? , how? couldn't find clues on developer website . note: pebblekit android , pebblekit ios cannot used if pebble project contains pebblekit js file. remove javascript files in pebble project ensure communication android , ios companion apps. according documentation here , can't integrate js extension pebblekit ios/android, that's why it's important ask question. nope, unfortunately isn't possible. maybe in future possible passing around deep links.

Python Tkinter show image acessed on a listbox -

i'm trying make python script shows image acessed on listbox. code got on internet works: import tkinter tk pil import imagetk, image window = tk.tk() path = 'img\\2015722_univ_sqs_sm.jpg' img = imagetk.photoimage(image.open(path)) panel = tk.label(window, image = img) panel.pack(side = "bottom", fill = "both", expand = "yes") window.mainloop() but when tried adapt listbox stopped working. from tkinter import * pil import imagetk, image import glob files = glob.glob('img\\*.jpg') class app: def __init__(self, root): self.l = listbox(root, width = 50, height = 15) self.l.pack() self.l.bind('<<listboxselect>>', self.lol) self.c = label(root) self.c.pack() f in files: self.l.insert(end, f) def lol(self, evt): path = files[self.l.curselection()[0]] img = imagetk.photoimage(image.open(path)) self.c.image = img ...

javascript - TypeError: d.$$minErr is not a function in angular-route.min.js -

i got error: "typeerror: d.$$minerr not function". seems problem angular-route. my code: index.htm: <!doctype html> <html ng-app="myapp" lang="en"> <head> <script src="js/angular.min.js"></script> <script src="js/angular-route.min.js"></script> <script src="app.js"></script> <meta charset="utf-8"/> </head> <body> <search-result></search-result> </body> </html> app.js var myapp = angular.module('myapp', ['ngroute']); myapp.config(function($routeprovider){ $routeprovider .when('/', { templateurl: 'pages/main.html', controller: 'maincontroller' }) }); // controllers myapp.directive('searchresult', function() { return { restrict: 'aecm', templateur...

gpu - Nvidia OpenCL hangs on blocking buffer access -

i have opencl program copies bunch of values input buffer, processes these values, , copies results back. // map input data buffer, has cl_mem_alloc_host_ptr cl_float* data = clenqueuemapbuffer(queue, data_buffer, cl_true, cl_map_write, 0, data_size, 0, null, null, null); // set input values for(size_t = 0; < n; ++i) data[i] = values[i]; // unmap input buffer clenqueueunmapmemobject(queue, data_buffer, data, 0, null, null); // run kernels ... // map results buffer, has cl_mem_alloc_host_ptr cl_float* results = clenqueuemapbuffer(queue, results_buffer, cl_true, cl_map_read, 0, results_size, 0, null, null, null); // processing ... // unmap results buffer clenqueueunmapmemobject(queue, results_buffer, results, 0, null, null); (in real code, check errors etc.) this works great on amd , intel architectures (both cpu , gpu). on nvidia gpus, code incredibly slow. program takes takes 10 seconds run (5 seconds host, 5 seconds device) run more 2 , half minutes on nvidia ca...

php - Let me know solution because something wrong in my codeigniter model -

error number: 1054 unknown column 'array' in 'where clause' select `cat_name` (`cat_manager`) `parent_id` = array if using codeigniter why don't use codiegniter active record library make sql queries writing them plain sql. $select = $this->db->select('cat_name') ->from('cat_manager') ->where_in('parent_id', $yourarray); $result = $this->db->get()->result_array();

python 2.7 - Using the pymc3 likelihood/posterior outside of pymc3: how? -

for comparison purposes, want utilize posterior density function outside of pymc3. for research project, want find out how pymc3 performing compared own custom made code. such, need compare our own in-house samplers , likelihood functions. i think figured out how call internal pymc3 posterior, feels awkward, , want know if there better way. right hand-transforming variables, whereas should able pass pymc parameter dictionary , posterior density. possible in straightforward manner? thanks lot! demo code: import numpy np import pymc3 pm import scipy.stats st # simple data, sigma = 4. want estimate sigma sigma_inject = 4.0 data = np.random.randn(10) * sigma_inject # prior interval sigma a, b = 0.0, 20.0 # build pymc model pm.model() model: sigma = pm.uniform('sigma', a, b) # prior uniform between 0.0 , 20.0 likelihood = pm.normal('data', 0.0, sd=sigma, observed=data) # write own likelihood def logpost_self(sig, data): loglik = np.sum(st.n...

ios - How to disable one specific constraint for a size class? -

say have view width 1/2 of superview in portrait, , 1/3 of superview in landscape, thought set different multipliers constraint, size class doesn't have feature. then found solution in following post, says have disable , enable constraints different size classes. changing multiplier of constraint based on size class i don't know how it. find way of clearing constraints. don't want rebuild constraints again. want change 1 constraint. if delete constraint in current size class, deleted in other size classes. there way can disable constraint 1 specific size class? use isactive property. as documentation says the active state of constraint. can activate or deactivate constraint changing property. note active constraints affect calculated layout. if try activate constraint items have no common ancestor, exception thrown. newly created constraints, active property no default. activating or deactivating constraint calls addconstraint: , remov...

javascript - Twitter Bootstrap top menu unknown component slides down -

Image
i'm using twitter bootstrap , i'm having problem top-bar menu. when choose item dropdowns, events fired correctly, javascript ok, there visual (a div probably?) slides down , disappears. looks this: i'm not twitter bootstrap expert, expect i've got invalid html put there. entire html code available here: https://github.com/pateketrueke/json-schema-faker/blob/gh-pages/src/index.html , important part this: <body> <!-- fixed navbar --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> [...] <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"...

powershell - Allow switch parameter only when another switch is present -

i have function 2 switches, 1 being required if other present. currently, if second switch run itself, nothing happens, fine, think can better. set second parameter can present if first also. have tried making first 1 required, technically works, doesn't give result expecting (ambiguous param set error). here param statement: [cmdletbinding(defaultparametersetname='notransfermdrive')] param( [parameter(mandatory=$true, valuefrompipeline=$true, valuefrompipelinebypropertyname=$true)] [string]$username, [switch]$removefromallgroups, [switch]$noconfirmationprompt, [parameter(parametersetname='transfermdrive')] [switch]$transfermdrive, [parameter(parametersetname='transfermdrive', mandatory=$true)] [string]$oldserver, [parameter(parametersetname='transfermdrive', mandatory=$true)] [string]$newserver ) i modified param statement this: [cmdletbinding(defaultparametersetname='notransfermdrive...

concurrency - How to implement a java equivalent for WaitForMultipleObjects windows API? -

we need have cleanup thread cleanup repeatedly. cleanup triggered after specified time period or after specified event in windows have: dword winapi waitformultipleobjects( _in_ dword ncount, _in_ const handle *lphandles, _in_ bool bwaitall, _in_ dword dwmilliseconds ); ...which wait specific events specified time. wait released when of specified event occurs or when time-out occurs. do have similar implementation in java? tried countdownlatch , cyclicbarrier. countdownlatch cannot reset again, couldn't use , cyclicbarrier has dependency on number of threads. looking better cyclicbarrier. timer , timertask help? one option use blockingqueue . multiple implementations provided in java.util.concurrent package. your event producers put events queue. your cleanup thread poll event, timeout, method blockingqueue.poll( long timeout, timeunit unit ) .

jquery - How to change the value of variable in a function in javascript? -

var e = 15; function change_value(e){ e = 10; } change_value(e); console.log(e); the value of e still 15. the e inside function scope different e inside global scope. just remove function parameter: var e = 15; function change_value(){ e = 10; } change_value(); console.log(e);

ruby - Create array of arrays from database query in rails -

ive got table consists of 2 fields called follower_id , followed_id. need create query creates array of each row , puts in overall array end structure looks like: "edges": [ ["1", "2"], ["1", "3"], ["3", "4"], ["3", "5"] ] so far have def self.including_relationships result={} result["edges"] relationship.all.each |relationship| result[""]= relationship.select(:follower_id.to_s,:follower_id.to_s) #the code here called once each user # user accessible 'user' variable end result end but produces: edges: [ "[4, 3, 3, 4]", "[3, 4, 3, 4]" ] you can use map build array like: relationship.all.map { |r| [r.follower_id.to_s, r.followed_id.to_s] }

node.js - EB CLI init problems... Invalid credentials ERROR: Credential must have exactly 5 slash-delimited elements -

so trying set eb cli , continually running same error. have done extensive searching , spent several hours on , feel i'm getting no where. select default region 1) us-east-1 : east (n. virginia) 2) us-west-1 : west (n. california) 3) us-west-2 : west (oregon) 4) eu-west-1 : eu (ireland) 5) eu-central-1 : eu (frankfurt) 6) ap-southeast-1 : asia pacific (singapore) 7) ap-southeast-2 : asia pacific (sydney) 8) ap-northeast-1 : asia pacific (tokyo) 9) sa-east-1 : south america (sao paulo) (default 3): 2 (note: choice here irrelevant) error: credential must have 5 slash-delimited elements, e.g. keyid/date/region/service/term, got 'https://917201257127.signin.aws.amazon.com/console/20150708/us-west-2/elasticbeanstalk/aws4_request' how edit credentials? amazon says should sort of login prompt... in advance. sam if have aws cli installed, can run aws configure otherwise, credentials stored in either ~/.aws/config or ~/.aws/credentials. you might want a...

symfony - How to setup Sylius to use Redis as Cache Backend -

according https://github.com/doctrine/doctrinecachebundle#cache-providers there several parameters necessary use redis instead of file_system cache backend. in main configuration file of sylius, there 1 area put cache settings: app/config/parameters.yml sylius.cache: type: redis (was file_system) where put rest? connection_id - redis connection service id host - redis host port - redis port thanks! you can use syntax: sylius.cache: type: redis namespace: sylius redis: host: localhost port: 6379 database: 10 sylius creates doctrine cache provider configuration.

Error while loading Native Library in Android -

Image
i trying load native libraries in android studio. project build , runs throws error when trying load .so file. my project structure is: and gradle file is: import com.android.build.gradle.tasks.packageapplication buildscript { repositories { mavencentral() } dependencies { classpath 'com.android.tools.build:gradle:1.2.3' } } apply plugin: 'com.android.application' repositories { mavencentral() } dependencies { compile 'com.nineoldandroids:library:2.4.0' compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar' compile 'com.android.support:support-v4:22.1.1' compile filetree(dir: 'libs', include: '*.jar') } android { compilesdkversion 19 buildtoolsversion '19.1.0' /* signingconfigs { release { storefile file(system.console().readline("\n\$ enter keystore path: ")) storepassword system.console().rea...

ios - Playing MPMoviePlayerController in UITableViewCell causes app to freeze and crash -

in app working with, adding mpmoveplayercontroller uitableviewcell , auto playing it. problem is, calling preparetoplay and/or play causes app freeze, cpu maxes out, ram continuously increases, , app of course crash after little while. if comment out preparetoplay , play not occur, see black box no playback controls. we create mpmovieplayercontroller in cellforrowatindexpath , store array, may have multiple videos in table, , need able play right video upon tapping 1 or stop 1 on demand. when table loaded first time, videos load , play without issue. users can add video via modal view controller presentation, reload table after adding video data source. problem arrises after users add new video. i tried storing property player in cell itself, did not resolve issue. i've tried calling stop before setting contenturl suggested elsewhere, didn't help. tried 4 different videos each different format, in case corrupt video. i'm not sure problem is. //table view...

puppet - Vagrant - 2 VMs have same IP -

im trying play around puppet. fired 2 debian instances using vagrant. vagrantfile looks this vagrant.configure("2") |config| config.vm.define "puppetagent" |puppetagent| puppetagent.vm.box = "puphpet/debian75-x64" puppetagent.vm.hostname = "puppetagent.example.com" puppetagent.vm.network "private_network",ip: "192.168.10.21" end config.vm.define "puppetmaster" |puppetmaster| puppetmaster.vm.box = "puphpet/debian75-x64" puppetmaster.vm.hostname = "puppetmaster.example.com" puppetmaster.vm.network "private_network",ip: "192.168.10.22" end however when ssh both instances, , /etc/hosts files (on both ) this: # master - instance1 127.0.0.1 localhost 127.0.1.1 puppetmaster.example.com puppetmaster # agent - instance2 127.0.0.1 localhost 127.0.1.1 puppetagent.example.com puppetagent im confused regarding this. did specify diff ip...

mysql - Merge two different sql file to one -

i have 2 .sql file mysql database same tables different rows. how can make 1 .sql file datas of other two? if files contain data (dml - selects, inserts etc.), can join them via notepad. both of files must contain same table (the same columns)!

android - HttpUrlConnection Keep Alive doesn't work correctly -

i set httpurlconnection , set system properties single keep alive connection per documentation : system.setproperty("http.keepalive", "true"); system.setproperty("http.maxconnections", "1"); android ignores these. i'm seeing connections on multiple ports @ same ip http traffic in wireshark. missing or broken on android? i've tried on android-l , android-m preview, it's broken on both. which version of android use, in versions of android, there bug socket reuse, please refer following links. https://code.google.com/p/android/issues/detail?id=38817 https://code.google.com/p/android/issues/detail?id=43132#makechanges and maybe can try remove gzip content type avoid bug.

mod rewrite - .htaccess redirect all subcategories if page is in /shop/ subcategory -

question: how can use .htaccess 301 redirect subdirectories (and subdirectories of subdirectories) in subdirectory /shop/ root and keep parameters? situation: i have webshop following structure: http://www.domain.com/shop/category1/category2/category3/product1.html?utm=code&source=web http://www.domain.com/shop/category1/product2 http://www.domain.com/shop/category1/category6/product3 we're working on new shop different structure. i'd have 301 redirect root of domain, old url follows: http://www.domain.com/shop/category1/category2/category3/product1.html?utm=code&source=web this url redirect to: http://www.domain.com/product1?utm=code&source=web i need remove /shop/, other subcategories keep parameters. try : rewriteengine on rewritecond %{the_request} /shop/cat1/cat2/cat3/product\.html\?utm=([^\&]+)&source=([^&\s]+) [nc] rewriterule ^ /product?utm=%1&source=%1 [nc,r,l]

javascript - Content-Type Ajax json missing -

i wrote php code outputs valid json, , sets content-type header application/json in dev setup. when deploy script embedded webserver works fine except it's not capable of sending content-type. it's not possible run other webserver. now have following code dynatable. though dev , embedded webserver, serve same file, , difference content-type. works dev setup, doesn't work embedded setup. i use following code load json file dynatable. document.ready( $.ajax({ url: 'phpapi.php', success: function(data){ $('#mytable').dynatable({ dataset: { records: data } }); } })); so can explain me why content-type important ajax? how can tell code manually json? without content-type returned data assumed plain text. there nothing in code tell otherwise. one way json specify return type in jquery code. add datatype: 'json' ajax configurat...

How to draw an arrow on every polyline segment on Google Maps V3 -

Image
i looking solution problem on stackoverflow since couldn't find accurate solution ended solving myself , post here, hope help. google maps provides polyline feature, based on list of coordinates can draw series of lines joining of them. you can draw polyline single arrow following code: var allcoordinates = [ new google.maps.latlng(26.291, 148.027), new google.maps.latlng(26.291, 150.027), new google.maps.latlng(22.291, 153.027), new google.maps.latlng(18.291, 153.027) ]; var polyline = new google.maps.polyline({ path: allcoordinates, strokecolor: color, strokeopacity: 1.0, strokeweight: 2, geodesic: true, icons: [{ icon: {path: google.maps.symbolpath.forward_closed_arrow}, offset: '100%' }] }); the problem here arrow drawn in last segment shown in next picture, route not straightforward , need...

Converting a C struct into Python to be sent through a socket -

i'm updating old, large piece of software written in c sends struct through socket server. updated software written in python, means need send same information in same byte layout c struct in python. i'm aware of python package struct, , use it. problem is, struct absolutely huge. give idea, here's snipet: // struct wish send typedef struct { struct st_command_header header; union { char buffer[32]; struct set_360_camera_message camera_msg; struct u_olcd_msg olcd_msg; }; } struct_to_be_set stc; // supporting structs struct st_command_header { union u_all_types len; union u_all_types cmd; union u_all_types cmd_counter; union u_all_types items; } __attribute__((packed)); struct u_olcd_msg { // on 100 lines of fields fill } // other structs necessary as understand it, struct python package requires manually pack struct, difficult given size of struct , number of union statements. ideally, i'd way u...

angularjs - Improving mobile aps client server communication efficiency and data availability in offline mode -

my question how store data once received online , still can processed after mobile device got offline and/or restarted. i'm using angularjs ionic (phonegap) building apps. question not explicitly adressing these technologies. best practices, patterns or algorythms helpful me or useful articles or key words. 1) simple challenge make app more user-friendly making functionality usable not if device online in offline mode. in case implies have make last fetched online data available later use (while device offline , after restarting device!). 2) bit more difficult reduce communication costs synchronizing server side changed data when device reconnects internet. 3) entities can produced on client side while device offline , must synchronized server too. there no potential risks of conflicts because users don't share entities write access. 4) use googles , apples push services inform devices newer entity versions, should updated on client side. polling isn't neede...

algorithm - Avoiding Possible Precision Loss with a Simple Moving Average -

suppose had basic moving average function keeping track of sum. example: queue values; double sum; double calcsma(double next) { values.push(next); sum -= values.pop(); sum += next; return sum / sma_length; } one example of how break down if our window 5 wide fed like: 2, 2, 2, 2, 2, 2, 2, 1e100, 2, 2, 2, 2, 2, 2, 2, 2 . output 2, 2, 2, 2e99, 2e99, 2e99, 2e99, 2e99, 0, 0, 0 . even if sum isn't quite dramatically off, there still quite reasonable instances small loss in precision make sum artificially increase tiny amount. on long period of time, add , become issue. does have ideas of how work around loss in precision? edit: note function designed work o(1). necessary. so, recalculating each time won't work: window large. you recalculate fresh sum on every sma_length values stop errors accumulating: queue values; double sum = 0.0; double freshsum = 0.0; int count = 0; double calcsma(double next) { values.push(next); sum -= value...

c# - How can i get the correct changes in datagridview combobox column? -

i have a datagridview in have a datagridviewcomboboxcolumn as 1 of column. this column's columntype = datagridviewcomboboxcolumn. in combo box have items admin,user,animal,human , birds. first item displayed when grid view loads admin (notice lowercase letter.). everything working fine problem arises - whenever user changing name admin admin/admin/admin etc. , clicking anywhere else in gridview column again showing admin in column when same scenario done time user presses enter or tab button , value changed. i not understanding why happened? what difference between click , enter/tab combo box? one more thing if user typing other word except "admin" , value changed on click. i think problem arises when typing uppercase letter or mixture of upper , lower case letters. same thing happened other items of combo box such animal/birds etc.

unity3d - Unity/C# Find object which have generic component -

i totally exhausted @ drag , drop components in inspector. what want find every object have component had chosen t void getallgameobjectwhichhave<t>(ref int cnt, gameobject[] f_array, gameobject transformforsearch) { foreach (transform trans in transformforsearch.transform) { getallgameobjectwhichhave<t>(ref cnt, f_array, trans.gameobject); t temp = trans.gameobject.getcomponent<t>(); if (temp != null && cnt < f_array.length) { f_array[cnt++] = trans.gameobject; } } } and used this //onawake() getallgameobjectwhichhave<rigidbody2d>(ref zeroint, enougharray, tophierarchyobj); this recursive function gets every gameobject , save them @ f_array. cannot filter , 'temp' not null. t temp = trans.gameobject.getcomponent() doesn't seem working meant. did misunderstand something? just use findobjectsoftype<t>() . (yep, generic variant exists) array ...

c++ - How to tell if a type is a subclass using type_info? -

i use c++ rtti. have type_info of class. how can tell whether class subclass of first one, if have type_info ? #include <typeinfo> class foo { public: virtual ~foo() {} }; class boo: public foo { public: virtual ~boo() {} }; class bar { public: virtual ~bar() {} }; template<class t> bool instanceof(const type_info& info) { // answer comes here!! } int main(int argc, const char* argv[]) { const type_info& fooinfo = typeid(foo); const type_info& barinfo = typeid(bar); bool booisfoo = instanceof<boo>(fooinfo); // should true bool booisbar = instanceof<boo>(barinfo); // should false return 0; } if have 2 typeinfo , b. there no general way determine if subclass of b. you may: store information (static structure filled @ runtime?) make educated guesses using type name (i.e. parsing type info string , name types accordingly). previous answers. require instantiate type somehow: type_info no...

Exception occurs reading spreadsheet after saving ExcelPackage (EPPlus) -

i manipulating data in .xlsx spreadsheet using epplus (4.0.4) , saving file, afterwards loading parts of data datatables. after call .save() method spreadsheet saved 'external table not in expected format.' exception when trying fill dataadapter. i've created console app minimise amount of code required demonstrate issue, here code: using officeopenxml; using system; using system.collections.generic; using system.data; using system.data.oledb; using system.io; using system.linq; using system.text; using system.threading.tasks; namespace epplussaveissue { class program { static void main(string[] args) { string pathtofile = "c:\\users\\peter\\documents\\test.xlsx"; fileinfo newfile = new fileinfo(pathtofile); using (var pck = new excelpackage(newfile)) { pck.save(); } string connectionstringformat = "provider=microsoft.ace.oledb.12.0;data ...

encryption - How to get unique key from android application dynamically that only my app knows about ? -

i have gone through similar questions on stackoverflow , other sites not find satisfactory answer.so asking new question detailed requirements. we building android application , need communicate application server. there handshake between application server , android app identify android application valid source , 1 server generated unique device key or auth key.this auth key stored on application. now generate auth key server idea take predefined or mutually agreed string "hello world" , encrypt strong symmetric encryption algo using key "key1".then server decrypt using same algo , same key.when server decrypts if gets "hello world" knows source infact android app. now next steps server generates auth key , encrypts same symmetric key algo , sends android app.android application decrypts , stores locally. now not want hard code symmetric algo key "key1" on application side because can decompile apk , know algo , key write automate...

javascript - Is it possible to dynamically show/hide frequently used buttons with full CKEditor.inline toolbar using maybe a "More” button? -

ckeditor provides ability display inline editor dynamically on click of textarea , set of toolbar buttons can configured show/hide possible show used buttons , hide rest of buttons "more” button/option because want provide full ckeditor toolbar of toolbar buttons used , hide simplify user interface if possible in other words, want keep buttons available in full ckeditor hide under may option called “more” config.toolbar = [ { name: 'document', groups: [ 'mode', 'document', 'doctools' ], items: [ 'source', '-', 'save', 'newpage', 'preview', 'print', '-', 'templates' ] }, { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'cut', 'copy', 'paste', 'pastetext', 'pastefromword', '-', 'undo', 'redo', 'pbckcode' ] }, { name: 'editing', groups: [ 'find',...

Wget best practices on large files -

i have text file (150gb) in size, around 2.5 billion links need download. i wondering if wget file, if wget puts entire files contents in memory, , if potentially crash machine. i interested know on best practices when downloading amount of links, example, directory downloads become unusable amount of files? what resuming, wget check top download stopped or failed, cause take long time. does keep log? log file big? log file stored in memory before saved somewhere? can disable log. basically, interested in best practice in downloading file of size. each link downloading around 250 bytes. many thanks

c# - NEST Elasticsearch query value between 2 field names -

i want convert following sql query elasticsearch nest query: select * table1 20 between minage , maxage so far nest query looks ("20" value client): var result5 = client.search<person>(b => b .filter(ff => ff .range(n => n .onfield(f => f.minage) .greater(20) ) ) .filter(ff => ff .range(n => n .onfield(f => f.maxage) .lower(???) // how specify max value fieldname? ) ); .filter(ff => ff .range(n => n .onfield(f => f.minage) .greater(x) ) && ff .range(n => n .onfield(f => f.maxage) .lower(x) ) ) in way have x -> between minage , maxage. x must greater minage , lower maxage in same time. hope helps! ...

android - Can't configure Camera2 API for a preview -

i need set preview camera, use scan qr code, using camera2 api. problem configure camera. code: //setting preview surface layout file <?xml version="1.0" encoding="utf-8"?> <surfaceview android:layout_width="250dp" android:layout_height="250dp" android:id="@+id/surfaceview" android:layout_gravity="center" android:layout_centervertical="true" android:layout_centerhorizontal="true" /> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:textappearance="?android:attr/textappearancemedium" android:text="@string/scanqr" android:id="@+id/textview" android:gravity="center_horizontal" android:layout_above="@+id/surfaceview" android:layout_centerhorizontal="true" /> in code: //after cameradevice... camerachara...