Posts

Showing posts from June, 2013

c# - Creating multidimensional array at runtime -

i did research on web couldn't find advice how dynamically create multidimensional (rank >1) array (it jagged array). in other words program ask number of dimensions (rank) first, number of elements per dimension (rank) , create array. is possible? multidimensional no, no problem jagged - here simple example: using system; using system.collections.generic; public class program { public static void main() { list<list<list<int>>> myjaggedintlist = new list<list<list<int>>>(); myjaggedintlist.add(new list<list<int>>()); myjaggedintlist[0].add(new list<int>()); myjaggedintlist[0][0].add(3); console.writeline(myjaggedintlist[0][0][0].tostring()); } } each item in first list list , each item in second list list , , each item in third list int . what's problem that? play in fiddle.

mocking - phpunit mock method called in constructor -

i test config class, parsing config file , allows me various settings app. my goal mock parse() method of config class, called in constructor , set method returning in constructor. this way, prevents file_get_contents() being called (in parse() method) , enables me have config class config property set contain array of properties. but haven't succeeded doing that. here code: the config class: <?php namespace example; use symfony\component\yaml\parser; class config { private $parser; private $config; public function __construct(parser $parser, $filepath) { $this->parser = $parser; $this->config = $this->parse($filepath); } public function parse($filepath) { $fileasstring = file_get_contents($filepath); if (false === $fileasstring) { throw new \exception('cannot config file.'); } return $this->parser->parse($fileasstring); } public function get($path = null) { if ($path) { $config = $thi

php - How can I connect a value of one mySQL table to a value of another table? -

i have 2 tables in mysql database: table "animals": | animal | name | |:-----------|------------:| | cat | tom | | dog | | table "orders": | id | animal | |:-----------|------------:| | 1 | cat | | 2 | dog | at first select table "orders" following data: <?php $pdo = database::connect(); $sql = 'select * orders order id asc'; foreach ($pdo->query($sql) $row) { echo ('<td>a:'.$row['id'].'</td>'); echo ('<td>b:'.$row['animal'].'</td>'); echo ('<td>c:'.$row['animal'].'</td>'); } database::disconnect(); ?> now want check if in mysql table "animal" animal has name . if yes print @ position b name . if there no name print animal : | a:1 |

if statement - PHP Conditionals: is_null($someVariable) vs. $someVariable === 0 -

i debugged problem had root mention down here: the first conditional true; second conditional not execute; why 2nd conditional not execute? $somevariable = 0; if ( $somevariable === 0 ) var_dump('worked'); if ( is_null($somevariable) ) var_dump('worked too'); i think saw working in 'legacy' code, not sure it. from is_null docs: returns true if var null, false otherwise. the second conditional doesn't execute because $somevariable isn't null.

android - CustomListView OnItemClickListener not working -

i used local database fetch records , create custom list view using that. custom list view gets displayed perfectly. problem onitemclicklistener. doesn't on click. aim send position of clicked item activity. implemented it's not working. screenshot of list view - https://www.dropbox.com/s/pz83i162sxdv2b0/untitled.png?dl=0 here mainactivity.java : public class mainactivity extends actionbaractivity { listview lv; textview tv1,tv2,tv3; arraylist<string> a=new arraylist<string>(); string mydata,name,name1; public string[] s1 = new string[50]; public int[] img = {r.drawable.rty, r.drawable.sf, r.drawable.rty}; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); tv1=(textview)findviewbyid(r.id.textview); lv = (listview) findviewbyid(r.id.listview); new mydata().execute(); lv.setonitemclicklistener(new adapterview.onitemclicklistener() { @o

Will a C compiled .so work with a C++ application? -

if want dynamically link shared library (.so) c++ application (which built g++) using ld_preload, matter if .so generated c source file (using gcc) or c++ source file (using g++)? , why or why not? thanks helping me understand this. yes, c++ executable can linked (both statically , dynamically) c library. this deliberate. c++ abis designed backwards compatible. you have ensure declarations of functions , on of library symbols, written in c++ program, marked extern "c" denote crossing language boundary. typically, library's own shipped header files you.

c - Segmentation Fault, large arrays -

#include <stdio.h> #define n 1024 int main(){ int i, j; int a[n][n]; int b[n][n]; (i=0;i<n;i++){ a[i][i]=i; b[i][i]=i; } (i=0;i<n;i++) for(j=0;j<n;j++) { printf("%d", a[i][j]); printf("%d", b[i][j]); } return 0; } this program reason of segmentation fault, if define n 1023, program work correctly. why happens? you overflowing stack. 2 * 1024 * 1024 * sizeof(int) lot systems. the simplest solution make arrays static . static int a[n][n]; static int b[n][n]; other methods: make arrays global (this same above) use malloc in loop , of course remember free int **a = malloc(n * sizeof *a); (i = 0; < n; i++) a[i] = malloc(n * sizeof *a[i]);

hadoop - Does Spark not support arraylist when writing to elasticsearch? -

i have following structure: mylist = [{"key1":"val1"}, {"key2":"val2"}] myrdd = value_counts.map(lambda item: ('key', { 'field': somelist })) i error: 15/02/10 15:54:08 info scheduler.tasksetmanager: lost task 1.0 in stage 2.0 (tid 6) on executor ip-10-80-15-145.ec2.internal: org.apache.spark.sparkexception (data of type java.util.arraylist cannot used) [duplicate 1] rdd.saveasnewapihadoopfile( path='-', outputformatclass="org.elasticsearch.hadoop.mr.esoutputformat", keyclass="org.apache.hadoop.io.nullwritable", valueclass="org.elasticsearch.hadoop.mr.linkedmapwritable", conf={ "es.nodes" : "localhost", "es.port" : "9200", "es.resource" : "mboyd/mboydtype" }) what want document end when written es is: { field:[{"k

javascript - How to split single line into multiple lines? -

i've been looking how split single line multiple lines using d3. when user clicks single line split on click. can't find examples online on how this. can let me know if possible? thank in advance! d3: var link = svg.selectall(".link") .data(force.links()) .enter().append("line") .attr("class", "link") .style("stroke-width", function(d) { if(d.value < 76742302){ return 1; }else if(d.value < 159879796){ return 2; }else if (d.value < 354232554) { return 3; }else if (d.value < 695427312) { return 4; }else{ return 5; } }); 'svg:line' have x1, y1, x2, y2 values. you can use basic algebra calculate line equation ( http://www.coolmath.com/algebra/08-lines/12-finding-equation-two-points-01 ) and find point want split line , create 2 new line elements. if want split half

c++ - Member is inaccessible -

Image
class example{ public: friend void clone::f(example); example(){ x = 10; } private: int x; }; class clone{ public: void f(example ex){ std::cout << ex.x; } }; when write f normal function, program compiles successful. however, when write f class member, error occurs. screenshot: the error you're seeing not root-cause compilation error. artifact of different problem. you're friending member function of class compiler has no earthly clue exists yet,much less exists specific member. a friend declaration of non-member function has advantage acts prototype declaration. such not case member function. compiler must know (a) class exists, , (b) member exists. compiling original code (i use clang++ v3.6), following errors actually reported: main.cpp:6:17: use of undeclared identifier 'clone' main.cpp:17:25: 'x' private member of 'example' the former direct cause of latter. doing this inst

Django - get in template reverse related many to many field -

i have 3 models, entry model , category model, , have created intermediate model categoryentry. class entry(models.model): entry_text = models.textfield() user = models.foreignkey(user) class category(models.model): user = models.foreignkey(user) category_text = models.charfield(max_length=200) entries = models.manytomanyfield(entry, through='categoryentry') class categoryentry(models.model): category = models.foreignkey(category) entry = models.foreignkey(entry) viewed = models.booleanfield(default=false) i have created view get_queryset method this def get_queryset(self): order_by = self.request.get.get('order_by') if not order_by: order_by = '-pub_date' return entry.objects.filter(category__id=self.kwargs.get('category_id', none), category__user__id=self.request.user.id).order_by(order_by)[:].select_related('user') i have category id kwargs. problem - how every entries rel

php - If meta_data <= 50 -

i'm trying automate delivery (free above 50) message in template. i'm echo'ing normal price & discount price (if available) results in digits. i have post normal_price = 55 / discount_price = 38 i'm new php tried following: <?php $discount = (get_post_meta($post->id, 'discount_price', true)); $normal = (get_post_meta($post->id, 'normal_price', true)); if $discount = (>= 50) { echo 'under 50 euro'; } else if $normal = (>= 50) { echo 'under 50 euro'; } else { echo 'above 50 euro'; } ?> how declare $discount = post_meta 'discount_price'? i think want is: $discountprice = (get_post_meta(get_the_id(), 'discount_price', true)); $normalprice = (get_post_meta(get_the_id(), 'normal_price', true)); // note: get_the_id() work if inside loop if ( $discountprice <= 50 ) { // 50 euro or less echo '50 e

Android : Custom ArrayAdapter not working to display text -

i working on android project, want create customarray adapter first display names of restaurants server, , when user clicks on 1 of object, it's id retrieved in backend(not displayed, nothing on ui). currently, having issues not working. note please note, not android programmer, thankful if me out, please try understand, not familiar android concepts, may not understand trying , might have follow comments. if have time it, please post answer in simple manner code. sorry this, had similar problem , not experience. thanks. apologies if rude, felt important. here layout code : <?xml version="1.0" encoding="utf-8"?> <listview xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" > </listview> here restrestaurant class : public class restrestaurant { private int restaurantid

python 2.7 - Pygame with Smartboard Event Type -

i want know correct event type electronic smart white board is, @ moment following works on regular screen mouse, , mouse attached electronic white board, doesn't respond finger tap. if event.type == pygame.mousebuttondown , event.button == 1: what correct event.type smart boards when using finger tap white board. i added code , prints out event type terminal. event = pygame.event.poll() x = event.type print pygame.event.event_name(x)

sql - Multiple Case Statements to one row -

in sql server database 1 customer have many products. when casing using this: case when br.ptype# = 'le' 'y' else 'n' end [legal], case when br.ptype# = 'br' 'y' else 'n' end [br], case when br.ptype# = 'ws' 'y' else 'n' end [screen], case when br.ptype# = 'tw' 'y' else 'n' end [van] it returns: title firstname lastname email legal br screen van mr aaaa aaaa test.email@test.com n y n n mr aaaa aaaa test.email@test.com y n n n how can returned results single row legal y , br y customer has these 2 policy types? know customer has 2 insurance types specified 4 i'm searching i'd return results like: title firstname lastname email legal br screen van mr aaaa aaaa test.email@test.com y y n n thanks in advan

ios - Device token is not received from iphone -

pfinstallation *currentinstallation = [pfinstallation currentinstallation]; [currentinstallation setdevicetokenfromdata:newdevicetoken]; [currentinstallation saveinbackground]; i installed app in iphone, manually turned off notifications of app (in setting screen) , uninstalled app device... again installed app in device, notification automatically turned on device token not received.

c# - Prism Unity background view -

i'm trying work unity prism , wpf. i've done far application module in directory , load on demand. works pretty well. can navigate between module using requestnavigate. but i'm facing problem , can't find documentation on this. have module need continue execution (run in background). example, have voip module , mediaplayer module need continue execution while i'm navigate module. possible use requestnavigate , maybe thread previous view/viewmodel until become current view ? we can run in separate thread // subscribe composite presentation events var eventaggregator = servicelocator.current.getinstance<ieventaggregator>(); var navigationcompletedevent = eventaggregator.getevent<navigationcompletedevent>(); navigationcompletedevent.subscribe(onnavigationcompleted, threadoption.uithread); events can subscribed in separate thread subscriptiontoken = addedevent.subscribe(addedeventhandler, thre

python - openCV better way to draw contours -

Image
i've detected hand based on roi histograms using code provided on opencv website, , result i've obtained based on result, want draw contour, resulting image it's not 1 need future processing. what need in order have smoother contour? thanks! your image has many "holes". try morphology this c++ code, can port python. may need tweak parameters little. #include <opencv2\opencv.hpp> using namespace cv; int main() { mat3b img = imread("path_to_image"); mat1b binary; cvtcolor(img, binary, cv_bgr2gray); threshold(binary, binary, 1, 255, thresh_binary); mat1b morph; mat kernel = getstructuringelement(morph_ellipse, size(11,11)); morphologyex(binary, morph, morph_close, kernel, point(-1,-1), 3); vector<vector<point>> contours; findcontours(morph.clone(), contours, cv_retr_ccomp, cv_chain_approx_simple); /// draw contours mat3b draw = img.clone(); (int = 0; < contours.siz

php - Laravel eloquent, how to order custom sortby -

i have following code works fine: $products = product::like($search)->wherein('id', $request->input('product_ids'))->skip($offset)->take($limit)->get(array('products.*'))->sortby(function($product) use ($sort_order) { $number = (isset($sort_order[$product->id])) ? $sort_order[$product->id] : 0; return $number; }); this returns items in ascending order, how specify whether want sortby return products in ascending or descending order? //$order contains either 'asc' or 'desc' $products = product::like($search)->wherein('id', $request->input('product_ids'))->skip($offset)->take($limit)->get(array('products.*'))->sortby(function($product) use ($sort_order, $direction) { $number = (isset($sort_order[$product->id])) ? $sort_order[$product->id] : 0; return ($direction == 'asc') ? $number : -$number; });

java - Avoid hibernate session destruction between methods -

i'm writing spring boot application (spring boot 1.2.2, spring 4.1.5), rest api. i've setup spring security automatically load user, check authorization etc. upon every http request. users stored in database, use hibernate access data inside database. in short, problem is: load user object database using hibernate on every http request during prefilter. later receive object in restcontroller's params, it's no longer attached hibernate session. because of this, cannot access lazy collections inside user object without re-reading database first. the question is: there way start hibernate session during prefilter , keep until http request complete? long version, code: first of all, setup spring security it'll load user object part of authorization: security configuration: @configuration @component @enablewebmvcsecurity @enableglobalmethodsecurity(prepostenabled = true) public class securityconfig extends websecurityconfigureradapter { @autowired

mysql - Junction table - EXCEPT replacement -

Image
i have relationship seen below, employees , trainings, each employee can participate in training it's basic m:m 1:m m:1 stuff. have combo box select employee, , want 2 list boxes list completed trainings , available trainings something this: and have 2 buttons moves selected 1 list box other , changes records accordingly. i have made query list trainings employee participated in: select training.name, training.trainer, training.cost, training.type, training.[length(day)] training inner join participation on training.[training id] = participation.training (((participation.employee)=[forms]![add training 2]![cboemp])) order training.name; i have problem selecting trainings , filtering out ones have been selected in sql query above simple except work access doesn't support it. this want: select training.name, training.trainer, training.cost, training.type, training.[length(day)] training except select training.name, training.trainer, training.cost, training.ty

How dow I implement AffirmativeBased object in Spring Security 4? -

in spring 3 , constructor looked this: public affirmativebased(list<accessdecisionvoter> decisionvoters) in spring 4 , constructor adds type: public affirmativebased(list<accessdecisionvoter<? extends object>> decisionvoters) can me understand it's looking for? i facing following exception: org.springframework.beans.factory.nosuchbeandefinitionexception: no qualifying bean of type [java.util.list] found dependency [java.util.list>]: expected @ least 1 bean qualifies autowire candidate dependency. dependency annotations: {} i able fix changing property constructor argument. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:sec="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemalocation="http://www.springframework.org

c# - RestSharp is crashing with Unity3d when running on iPhone -

i'm trying attach restsharp unity3d. original restsharp mono lib works fine in editor, on device crashing callstack argumentoutofrangeexception: argument out of range. parameter name: options @ system.security.cryptography.x509certificates.x509certificatecollection.getenumerator () [0x00000] in <filename unknown>:0 @ system.text.regularexpressions.regex.validate_options (regexoptions options) [0x00000] in <filename unknown>:0 @ system.text.regularexpressions.regex..ctor (system.string pattern, regexoptions options) [0x00000] in <filename unknown>:0 @ restsharp.restclient..ctor () [0x00000] in <filename unknown>:0 @ restsharp.restclient..ctor (system.string baseurl) [0x00000] in <filename unknown>:0 that means, exception appears inside of ctor restclient(string), wrapper around default ctor. , inside of default ctor, there public restclient() { #if windows_phone this.usesynchronizationcontext = true; #endif this.conte

Is it possible to execute python script on Visual studio with Linux environment -

is possible execute python script on visual studio linux environment for example the following python code written on visual studio import os f = os.popen('date') = f.read() print "today ", usually after write code on visual studio, send python file linux machine , run python on linux environment and because cant run python code fit linux on win please advice if there alternative run python on visual studio or other editors linux environment?

python - Zoom to rectangle on polar plot -

Image
i have polar scatter plot. unable 'zoom' in on data points manipulating x , y axis limits, due nature of polar projection. how 'zoom rectangle', specifying coordinates of rectangle corners, example? plot shown below. example code: import numpy np #from matplotlib.path import path import matplotlib.pyplot plt import matplotlib.cbook cbook mpl_toolkits.axisartist.grid_helper_curvelinear import gridhelpercurvelinear mpl_toolkits.axisartist import subplot mpl_toolkits.axisartist import subplothost, \ parasiteaxesauxtrans import mpl_toolkits.axisartist.angle_helper angle_helper matplotlib.projections import polaraxes matplotlib.transforms import affine2d def polarasrect(fig): mpl_toolkits.axisartist.grid_helper_curvelinear import gridhelpercurvelinear mpl_toolkits.axisartist import subplot mpl_toolkits.axisartist import subplothost, \ parasiteaxesauxtrans import mpl_toolkits.axisartist.angle_helper angle_helper matplotlib.

javascript - On-screen keyboard resizes app when an input box is selected Apache Cordova Visual Studio? -

i trying develop app apache cordova tools visual studio , believed had finished project until started using on device , on-screen keyboard re-sized entire app when popped up. application looks way until user selects input box , on-screen keyboard pops up, makes screen shrink compensate keyboard. how can make keyboard overlaps layout present instead of re-sizing , making new one? can't seem find solutions on internet appreciated. thanks dustin - need use keyboard plug-in customize behavior. can find plug-in @ npm: https://www.npmjs.com/package/cordova-plugin-keyboard the exact line of code give want is: keyboard.shrinkview(false); cheers, kirupa

cannot compile scala test with intellij 14.1 -

the project uses scala 2.9 my scalatest dependency is: <dependency> <groupid>org.scalatest</groupid> <artifactid>scalatest_2.9.2</artifactid> </dependency> error:scalac: error: org.jetbrains.jps.incremental.scala.remote.serverexception error compiling sbt component 'compiler-interface-2.9.2-50.0' @ sbt.compiler.analyzingcompiler$$anonfun$compilesources$1$$anonfun$apply$2.apply(analyzingcompiler.scala:145) @ sbt.compiler.analyzingcompiler$$anonfun$compilesources$1$$anonfun$apply$2.apply(analyzingcompiler.scala:142) @ sbt.io$.withtemporarydirectory(io.scala:285) @ sbt.compiler.analyzingcompiler$$anonfun$compilesources$1.apply(analyzingcompiler.scala:142) @ sbt.compiler.analyzingcompiler$$anonfun$compilesources$1.apply(analyzingcompiler.scala:139) @ sbt.io$.withtemporarydirectory(io.scala:285) @ sbt.compiler.analyzingcompiler$.compilesources(analyzingcompiler.scala:139) @ sbt.comp

php - MySQL COUNT with GROUP AND JOIN -

i need select information 3 tables 1 sql query. try explain as possible. i have following 3 tables: users id | full name | category_id -------------------------- 1 | john doe | 3 2 | john doe | 5 3 | john doe | 2 4 | john doe | 3 5 | john doe | 3 categories id | name ---------------------- 2 | category name 1 3 | category name 2 5 | category name 3 registrations id | user_id ------------ 1 | 1 2 | 2 3 | 4 now want outcome of sql query html table looking like: category | number of registrations category name 2 | 3 category name 3 | 3 category name 1 | 1 so sum up, have select user_id registrations table, category_id each user users table , find category name categories table. is doable? you can try this select c.name, count(r.user_id) categories c inner join users u on u.category_id = c.id inner join registrations r on r.user_id = u.id group c.id

java - Thread VS RabbitMQ Worker resource consumption -

i using java executorservice threads send amazon emails, helps me make concurrent connection amazonses via api , sends mails @ lightning speed. amazon accepts number of connection in sec, me 50 requests in second. execute 50 threads in second , send around 1million emails daily. this working pretty good, number of mails going increased. , don't want invest more ram , processors. one of friend suggested me use rabbitmq workers instead of threads, instead of 50 threads, ll having 50 workers job. so before changing code test resource management, want know there huge difference in consumption? when execute threads, java consumes 20-30% of memory. if used workers low or high? or alternative option this? here thread email sending function: @override public void run() { destination destination = new destination().withtoaddresses(new string[] { this.to }); content subject = new content().withdata(subject); content textbody = new content().withdata(body); body

Apache poi xwpf table alignment -

i creating table in apache poi in xwpf using below code : xwpftable table = doc.createtable(countrows1+1,4); table.getcttbl().gettblpr().unsettblborders(); table.setinsidehborder(xwpftable.xwpfbordertype.dashed, 0,0,null); table.setinsidevborder(xwpftable.xwpfbordertype.dashed,0,0, null); /* table header */ table.getrow(0).getcell(0).settext("column1"); table.getrow(0).getcell(1).settext("column2"); table.getrow(0).getcell(2).settext("column3"); table.getrow(0).getcell(3).settext("column"); /* other rows populed here*/ i not find method using align table left, centre or right of page .is there way this? also content of first row should in bold . there method set header bold ? you can align table using following function public void settablealignment(xwpftable table, stjc.enum justification) { cttblpr tblpr = table.getcttb

Exporting the report itself, not the data from access 2010 -

as title says, export report itself. i have 2 version of access database, in these 2 same except made copy use in 2014 , 1 use in 2015... , there 1 report not present in 2015 access file. possible take out of 2014 file ? right-click export function seems data generated report. open both databases , navigation panes. right-click , copy report in source database. right-click navigation pane in target database , paste report.

java - Returned JSON object does not respect inheritance? -

i have google cloud endpoint api returns product object. product object contains object brand large (id, name, text, description, image urls, ...). when getting list of products don't need whole information inside brand , id , title. so tried factor out brand base class brandbase contains limited set of properties (only id , title). , inside product in public brandbase getbrand() method return brandbase object. but looking @ json output google cloud endpoints - still whole brand content (including text, description, etc). looks google cloud endpoint looks @ object-type , serializes regardless of specified return type in class itself? @entity public class product { @id private long id; @index private ref<brandbase> brand; public brandbase getbrand() { return brand.get(); } public void setbrand(brandbase brand) { this.brand = ref.create(brand); } ... } @entity public class brand extends brandbase { @id private long id; @ind

encryption - How to decrypt the received data from serial to USB using python? -

when send message zigbee connected pc zigbee connected raspberry pi board.we getting message,similarly had sent zigbee connected pc example:* hello world *,but in receiver section getting hello world encrypted data (with header bit , check-sum bit) need hello world in receiver terminal in receiver terminal zigbee connected raspberry pi interfacing ,i using serial usb cable. here simple python code serial usb import serial time import sleep ser = serial.serial('/dev/ttyusb0', 9600, rtscts=1, timeout=0) while true: line = ser.read(ser.inwaiting()) if len(line) > 0: print line sleep(1) ser.close() i getting type of results ,do help pi@raspberrypi ~/iot/xbeeapi/python $ python temperlm.py ~#�}3�@ȶ���#hello world�~#�}3�@ȶ���####��~#�}3�@ȶ���#hello world� ~#�}3�@ȶ���#hello world� ~#�}3�@ȶ���#hello world�~#�}3�@ȶ���#hello world� ~#�}3�@ȶ���#hello world�~#�}3�@ȶ���#hello world� ~#�}3�@ȶ���#hello world�~#�}3�@ȶ���#hello world�

android - Wear App and with custom build type with applicationIdSuffix -

i have app i'd add android wear app extension. main app has 3 build types (debug, beta , release). beta builds have applicationidsuffix allows me install play-store version , current development version in parallel on same device. worked fine until added wear app. the main app`s build.gradle looks this: apply plugin: 'com.android.application' android { ... defaultconfig { ... applicationid "com.example.mainapp" ... } buildtypes { debug { applicationidsuffix '.debug' } beta { applicationidsuffix '.beta' } release { } } } dependencies { ... wearapp project(':wear') } the wear-app has same build types same applicationidsuffix values. however, when build beta app (by calling gradle assemblebeta ) build process builds :wear:assemblerelease instead of :wear:assemblebeta why following error mes

another app:dexDebug error Android Studio -

i have working project , want implement new library name seamless ad network api. while add api in dependencies , build no problems, try debug app , gives error below. error:execution failed task ':app:dexdebug'. >com.android.ide.common.process.processexception: org.gradle.process.internal. execexception: process 'command 'c:\program files\java\jdk1.8.0_31\bin\java.exe'' finished non-zero exit value 3 i tried different solutions mentioned in similar stackoverflow questions no luck! have tried adding multidexenabled true didnt work have tried adding compile 'com.android.support:multidex:1.0.0' didnt work have tried comment out other jar files mentioned in dependencies didnt work. wrong this? here build.gradle in app apply plugin: 'com.android.application' android { compilesdkversion 21 buildtoolsversion android_build_tools_version defaultconfig { minsdkversion android_build_min_sdk_version targetsdkversion android_buil

gruntjs - grunt not installing properly for the commands -

Image
the cursor continuously rotating longer time. have tried sudo npm install -g grunt-cli , npm install -g grunt-cli but both of them not working. please suggest. are using proxy server in environment? if so, need exec command below make npm use proxy server npm config set proxy http://proxy-url:port

linux - convert ushort to long in 64 bit architecture in c++ -

i porting code 32bit unix 64 bit linux machine. if have variable in const long l1 , variable in u short us1 . need compare these 2 if( l1 != us1) .... not working. typecasting should use ?. piece worked in 32 bit unix works unpredictably in linux 64 bit. works correctly , doesn't. reason number of bits occupied long changed now. planning convert us1(ushort) ulong , compare. (l1 != (ulong)us1). again in l1 still signed. please suggest should appropriate type conversions. code snippet below: nise::facex::order::niseworkorder *wrkord = 0; (this ushort) int retcode = getniseorder(wrkord, asyncq->m_order_number); (niseworkorder function wrkord reference pointer). getniseorder croba call , populate niseworkorder structure). now, asyncq->m_version_num osplong. traceprt(app_lvl, ("wrkord->orderhead.wrkordkey.order.orderversion = <%d>",wrkord->orderhead.wrkordkey.order.orderversion)); traceprt(app_lvl, ("(const long)a

Python: Fastest way of parsing first column of large table in array -

so have got 2 big tables compare (9 columns , approx 30 million rows). #!/usr/bin/python import sys import csv def compare(sam1, sam2, output): open(sam1, "r") s1, open(sam2, "r") s2, open(output, "w") out: reader1 = csv.reader(s1, delimiter = "\t") reader2 = csv.reader(s2, delimiter = "\t") writer = csv.writer(out, delimiter = "\t") list = [] line in reader1: list.append(line[0]) list = set(list) line in reader2: field in line: if field not in list: writer.writerow(line) if __name__ == '__main__': compare(sys.argv[1], sys.argv[2], sys.argv[3]) the first column contains identifier of rows , know ones in sam1. so code working with, takes ages. there way speed up? i tried speed converting list set, there no big difference. edit: running quicker have whole lines out of input table , write lines exclusive id output file. how

go - Defer usage clarification -

let's assume have following function func printnumbers(){ var x int defer fmt.println(x) := 0; < 5; i++{ x++ } } as said in specification : each time "defer" statement executes, function value , parameters call evaluated usual , saved anew actual function not invoked. obviously, 0 printed out when function execution ends. should if want print out final value of variable x ? i've come following solution: func printnumbers(){ var x int printval := func(){ fmt.println(x) } defer printval() := 0; < 5; i++{ x++ } } so wonder if there better way resolve problem. if defer has arguments evaluated @ line of defer-statement; illustrated in following snippet, defer print 0: func printnumber() { := 0 defer fmt.println(i) // print 0 i++ return } you can use anonymous function defer statement if want postpone execution of statement or function until end of enclosing (calling) function. here updated

php - How can I validate CSS within a script? -

is there library out there validate css? the tools can find web sites. if 1 of these sites has api, fit bill, too. i have script serves css compiler. sets various variables according settings theme, , generates , writes css file. before committing writing css file, i'd validate make sure there aren't invalid entries. php convenient, python, perl, ruby, java, or executable shell fine. ideally, there's out there can use part of sequence like: $css_file=theme_compile('theme-name'); if(!validate_css($css_file)){ echo "css file contained invalid entry 'width:px'";//just example, of course } else{ file_put_contents('/path/css_file',$css_file); } w3c has api: http://jigsaw.w3.org/css-validator/api.html you can download validator , run locally: http://jigsaw.w3.org/css-validator/download.html you need able run java script.

ruby on rails 4 - Access current location of user using IP address -

is there solution can access user current location, i use geocoder gem @request = request.location but give reserved or nil entry first of put code in html page <script> var x = document.getelementbyid("demo"); function getlocation() { if (navigator.geolocation) { navigator.geolocation.getcurrentposition(showposition); } else { x.innerhtml = "geolocation not supported browser."; } } function showposition(position) { x.innerhtml = "latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude; } </script> you latitude & longitude of location code.then after use value of latitude & longitude geocoder gem. able find address of location. you can see here. http://www.w3schools.com/html/html5_geolocation.asp

Strcmp and string comparison in PHP where string comes from an array -

here's i'm trying achieve, @ moment returns "error", despite $assign holding value a. if ($assign === "a") { echo "assign a"; } elseif ($assign === "b") { echo "assign b"; } else { echo "error"; } $assign getting value array, shown below checked think of. strcmp below returns -52, has me stumped. $assignments[0] holds "a", without extraneous spaces or characters, , type string. $assign = $assignments[0]; print_r ($assign); print (gettype($assign)); echo strcmp ($assign, "a"); i'm assuming issue i'm not assigning $assign value "a" instead sort of reference comes array, i'm afraid that's far troubleshooting has gotten me!

hashmap - Spring mvc form:select path is custom map in model attribute -

how bind map property of model , send selected value controller? i able populate drop down on submitting form getting error 400 - bad request. mymodel.java: public class mymodel{ private map<mysubmodel, string> submodel = new hashmap<mysubmodel, string>(); private submodel submodelsearched; } submodel.java: public class submodel{ public string id; public string name; } jsp: <form:form action="/mysearch" modelattribute="mymodel" method="post"> <form:select path="submodelsearched"> <form:options items="${mymodel.submodel}/> </form:select> ..... </form:form>

xampp - Accessing my Local Host from different computer in a different network -

i'm current using xammp,and have created website in htdocs. want know if can access computer (not in same network) , work on site other computer. you can using dynamic dns service provided noip.com. download noip client , setup account in (try googling on it). after must edit conf files in xampp allow outside network communicate network.

jquery - Javascript function works only on second click -

i'm trying prescription details of particular patient , corresponding result displayed in modal window. problem first result obtained on 2nd click. on successive click result of previous data obtained. below html: <table class="table"> <thead> <tr class="text-center" style="font-weight: bold"> <td></td> <td>name</td> <td>id</td> <td>age</td> <td>registered on</td> <td>view prescription</td> </tr> </thead> <tr class="text-center"> <td><input name="name" type="text"></td> <td><input name="id" type="text"></td> <td><input name="age" type="text"></td> <td><input name="reg_on"

c# - Showing Phone Number in specified format XAML -

this question has answer here: how define textbox input restrictions? 5 answers i have textbox in wpf. <textbox grid.row="3" fontsize="30"></textbox> i need enter 10 digit phone numbers it. displaying format should xxx-xxx-xxxx . is possible handle situation xaml without of code?. if no how possible of code? try using <textbox grid.row="3" maxlength="10(or limit)" fontsize="30"></textbox> you can set limit in xaml in view-model or code-behind file.

c# - Fill fields using value from another subquery in a LINQ -

i have following linq, can use linq values ispremiumuser , islawfirm on go or there other way this? what need values of ispremiumuser , islawfirm based on supplier id. dont want add foreach work, can use linq these values var supplierlistquery = (from sup in db.ppsuppliers select new searchresultsupplierviewmodel { supplierid = sup.ppsupplierid, supplierlocation = sup.locationsfordisplay, createddate = (datetime)sup.createddate, ppmemberid = sup.ppmemberid, ispremiumuser = (from u in db.ppsubscriptions join s in db.ppsubscriptionplans on u.subscriptionplanid equals s.subscriptionplanid u.ppmemberid == sup.ppmemberid && u.subscriptionenddate >= system.datetime.now orderby u.subscriptionstartdate descending select s).firstordefault().ispremium, islawfirm = (from l in db.ppsuppliersuppliertypes join f

ios8.3 - IOS Gmail API - How to get "messageId" of an Email with an attachment -

Image
i using gmail api 1 of ios application. gmail api .i successful in authorizing user login process. got list of mails (users.threads.list) , result shown below. now need mail attachment (user.messages.attachment.get).for need pass 3 parameters i.e. emailid,messageid,id. my problem "how messageid"? thanks :) the threadid in first request id identifies thread, , same first message in thread. has nothing attachment. my latest message in inbox has attachment. listing mail: get https://www.googleapis.com/gmail/v1/users/me/messages?maxresults=1&access_token={your_api_key} response: { "messages": [ { "id": "14e8bf63dd00a52f", // message id! "threadid": "14e8bf63dd00a52f" // since first message in thread, // threadid same. } ], "nextpagetoken": "01097010197696465829", "resultsizeestimate": 3 } i use id message's attachmen