Posts

Showing posts from June, 2012

android - How to detect KEYCODE_DEL on soft keyboard? -

mmessagecomposeusernames multiautocompletetextview , want delete space (if last char of multiautocompletetextview ) or delete single word (to last " " , if not). code: mmessagecomposeusernames.setonkeylistener(new view.onkeylistener() { @override public boolean onkey(view v, int keycode, keyevent event) { //you can identify key pressed buy checking keycode value keyevent.keycode_ if(keycode == keyevent.keycode_del){ string string = mmessagecomposeusernames.gettext().tostring(); if (!string.substring(string.length() - 1).equals(" ")) { if (string.contains(" ")) { string = string.substring(0, string.lastindexof(" ")); } else { string = ""; } } log.i("string", string); mmessagecomposeusernames.se

javascript - Error in WebRTC connection -

i'm writing app android based on ionic2 , webrtc. used library https://github.com/feross/simple-peer use push notifications exchange signaling data between 2 apps. when user wants contact other called connecttopeer() method , subsequently other receives request , returns response. works fine except point have establish real connection, i have error . class code: var self; var peer; import {injectable} 'angular2/core'; import {storage, localstorage, events} 'ionic-angular'; @injectable() export class vallasciappdata { static parameters() { return [[events]]; } constructor(events) { //conacts data if(window.localstorage.getitem("contacts") == null || window.localstorage.getitem("contacts") == 'false'){ this.contacts = [ { username: 'this contact', id:'1' },

c++ - What are the basic rules and idioms for operator overloading? -

note: answers given in a specific order , since many users sort answers according votes, rather time given, here's index of answers in order in make sense: the general syntax of operator overloading in c++ the 3 basic rules of operator overloading in c++ the decision between member , non-member common operators overload assignment operator input , output operators function call operator comparison operators arithmetic operators array subscripting operators pointer-like types conversion operators overloading new , delete (note: meant entry stack overflow's c++ faq . if want critique idea of providing faq in form, the posting on meta started this place that. answers question monitored in c++ chatroom , faq idea started out in first place, answer read came idea.) common operators overload most of work in overloading operators boiler-plate code. little wonder, since operators merely syntactic sugar, actual work d

Move computers from xml file c# to dictionary with read/write capabilities -

i writing application run service , check computers once hour see if up. have computerlist.xml file reading , writing to. format of xml file is <computers> <primaryservers> <location1 type="primary"> <ipaddress>192.168.1.2</ipaddress> <isalive>true</ipaddress> </location1> <location2></location2> </primaryservers> <secondaryservers> <location1 type="secondary"> <ipaddress></ipaddress> etc... </location1> </secondaryservers> <clients> etc... <type="client"> </clients> </computers> each location has different number of computers , i'd store values use in other methods , write bool file whether or not host alive after has been checked. the idea application check if primary server alive, if it's not checks see if clients alive, if down know network d

javascript - Access constructor parameters inside the google sign in function Angular 2 -

i translate google sign in javascript typescript, , works, issue i'm having cannot access _router variable inside google sign in function. inside attachsignin() function try access _router: router param constructor , undefinded. this code import {component, ngzone} "angular2/core"; import {toastsmanager } 'ng2-toastr/ng2-toastr'; import {router, router_providers} 'angular2/router' // google's login api namespace declare var gapi: any; @component({ selector: "sous-app", templateurl: "app/login/login.html", providers: [toastsmanager, router_providers] }) export class login { googleloginbuttonid = "google-login-button"; userauthtoken = null; userdisplayname = "empty"; auth2 = null; self = this; constructor( public _router: router) { } // angular hook allows interaction elements inserted // rendering of view. ngafterviewinit() { var loginpro

dependencies - maven warning: duplicate version when using two different types of dependecy of the same artifact -

maven throws strange warning while builduing our multi-module project. i'm referencing jar , test-jar of same project in project. both dependencies have test scope. im running maven 3.3.1 , cannot upgrade version easily. does of have idea how solve problem without getting warning maven? pom.xml of projecta: <dependency> <!-- line 130 --> <groupid>${project.groupid}</groupid> <artifactid>projectb</artifactid> <version>${project.version}</version> <type>test-jar</type> <scope>test</scope> </dependency> <dependency> <groupid>${project.groupid}</groupid> <artifactid>projectb</artifactid> <version>${project.version}</version> <scope>test</scope> </dependency> warnings maven (anonymized): [warning] problems encountered while building effective mo

java - Access JTable cell component -

ok have jtable i'm displaying jlist on every cell. had implement tablecellrenderer , extend defaultcelleditor. here return actual jlist rendered in gui. what want when user de-selects item jlist, want de-select items jlists table row starting @ clicked column. my problem can't figure out way de-select items come after current clicked table column. can access defaultlistmodel. guess need access actual jlist in order remove selected items. below method i'm using. ideas how this? thanks. public void deselectfromlocation(int row_, int column_){ defaulttablemodel dtm = (defaulttablemodel) table1.getmodel(); int cols = dtm.getcolumncount(); for(int i=column_; i<cols;i++){ pcslistmodel lm = (pcslistmodel) dtm.getvalueat(row_, i); //how can access actual jlist object in order remove selected items? //the pcslistmode defaultlistmodel , has no access jlist object. thanks. } } pr

java - Activemq went out of memory when sending large files over queue -

when sending 100mb size messages using queue, activemq runs out of memory error, using file cursor queue - queue detail - our producer sending non-persistent messages @ size of 100mb per messages , producer keep producing through while loop of same 100mb messages. we use default heap size came activemq 1gb max. we have activemq config setting follows: <policyentry queue=">" producerflowcontrol="false" memorylimit="512mb" maxpagesize="1000000"> <pendingqueuepolicy> <filequeuecursor /> </pendingqueuepolicy> </policyentry> on consume side have async consumer keep listening on messages coming in , send auto-ack. after program runs while activemq throws following error: 2016-04-21 14:52:18,961 | error | error in thread 'activemq brokerservice.worker.1' | org.apache.activemq.broker.brokerservice | activemq brokerservice.worker.1 java.lang.outofm

Simple Elevator Program Python Using While For Loop. Why does my loop not update every item on list? -

my below loop in python goes through list of customers seems once removes customer list go start of while loop instead of repeating through rest of customers. can please have @ doing wrong? entire code below , attached. author = 'alan doonan' import random import time class building: # defines class building number_of_floors = 0 # sets number_of_floors variable 0 customer_list = [] # creates empty array customer_list elevator = 0 # sets elevator variable 0 def __init__(self, floors, customers):

ruby on rails - Explanation of why "Expected result to have changed by 1, but was changed by 0" error happens and what to do to fix it -

i have feature in user able add new location, , i'm having hard time adding test it. (i'm horrible @ testing, trying hard better.) i feel close getting test work. error running right expected result have changed 1, changed 0 now don't know i'm doing wrong. i'm wondering if me allow test pass, kind of explanation of happening when error happens. i'm trying become better testing been i've avoided , until accepted importance of it, , had courage understand it. here spec file require 'spec_helper' describe admin::locationscontroller, type: :controller let(:admin) { factorygirl.create(:admin) } context 'super admin' let!(:super_admin) { factorygirl.create(:super_admin) } before(:each) sign_in(:user, super_admin) end describe '#create' 'creates new location' expect{ post :create, location: { name: 'sample location', phone: '5555555555',

node.js - Extract values from nested XML using Node JS -

i'm writing rest service in node takes xml input, when parse it, 1st level nodes displayed, nested ones displayed objects. i cannot hard-code xml elements read because per specification there optional elements, has dynamic. i'm using body-parser-xml parse xml. var express = require('express'), bodyparser = require('body-parser'); require('body-parser-xml')(bodyparser); //var xmlparser = require('express-xml-bodyparser'); var app = express(); app.use(bodyparser.xml({ limit: '1mb', // reject payload bigger 1 mb xmlparseoptions: { normalize: true, // trim whitespace inside text nodes normalizetags: true, // transform tags lowercase explicitarray: false, // put nodes in array if >1 preservechildrenorder: true } })); // app.use(xmlparser()); app.post('/users', function(req, res, body) { // request xml payload parsed // , javascript object produced on req.body // correspond

c# - Ways of checking if left mouse button is down -

i new programming , first time have done in c#. have source code of program use , modify make better me use personally. program set in way when user holds down left mouse button, mouse clicks in random intervals. want there delay between when mouse held down , again, why implemented code: public void performleftclick(int xpos, int ypos) { mouse_event(0x02, xpos, ypos, 0, 0); //leftdown thread.sleep(49); mouse_event(0x04, xpos, ypos, 0, 0); //leftup leftdown = true; } ... private void leftmouseup(mousehook.msllhookstruct mousestruct) { leftdown = false; } private void leftmousedown(mousehook.msllhookstruct mousestruct) { if (leftdown == false) { timeleftclicked = datetime.now; } leftdown = true; } mouse hook (not code obviously): #region copyright /// <copyright> /// copyright (c) 2011 ramunas geciauskas, http://geciauskas.com /// /// permission hereby granted, free of charge, person

Android Detect Flag Emojis Present -

it understanding of lollipop (android 5.0), flag emojis included. have google nexus device , samsung galaxy note 4, , nexus has emojis while samsung shows 2 letter country code. there anyway detect if flag emojis supported hide country codes if emoji flags aren't there?

netsuite - Can a transaction column formula field update after line item is added? Or only after record save -

i wanted create "total line" field on expense report expense line adds in amount taxes subtotal "amount" give total specific expense. problem though, after add line, blank. works after save record, not helpful staff entering expenses. limitation of netsuite? have put in script somehow refreshes record after line added? i'm not familiar scripting. the formula {amount} + ({amount} * {taxrate1}) + ({amount} * {taxrate2}) the field id custcol_total_line thanks http://i.imgur.com/nwtzrai.jpg below field changed function use. make client script using below function. fire if amount on line changed. /** * recordtype (internal id) corresponds "applied to" record in script deployment. * @appliedtorecord recordtype * * @param {string} type sublist internal id * @param {string} name field internal id * @param {number} linenum optional line item number, starts 1 * @returns {void} */ function clientfieldchanged(type, name, linenum){

nlp - What text processing tool is recommended for parsing screenplays? -

i have plain-text kinda-structured screenplays, formatted example @ end of post. parse each format where: it easy pull stage directions deal specific place. it easy pull dialogue belonging particular character. the obvious approach can think of using sed or perl or php put div tags around each block, classes representing character, location, , whether it's stage directions or dialogue. then, open web-page , use jquery pull out whatever i'm interested in. sounds roundabout way , maybe seems idea because these tools i'm accustomed to. i'm sure recurring problem that's been solved before, can recommend more efficient workflow can used on linux box? thanks. here sample input: somewhere corporation - optional comment guy named bob sitting @ computer. bob mmmm. stackoverflow. like. footsteps heard approaching. alice where's report said you&#

php - Why cant I run bin/behat? -

i trying run behat on vendor folder. have installed composer globally, have installed behat package, every time run bin/behat keep getting message composer you must set project dependencies, run following commands: curl -s http://getcomposer.org/installer | php php composer.phar install i not sure how fix this. see files in vendor folder, , when type "composer" on terminal, see manual. if can me resolve appreciate it. thanks! there several possible problems leading situation: make sure composer installed in $path . is, running composer @ command prompt should work, , shouldn't need run explicit path ~/downloads/composer.phar execute composer install instruction error message suggests. common error message mcrypt php extension required in case need install specified extension. example, brew install php56-mcrypt on mac or sudo apt-get install php5-mcrypt on ubuntu.

Creating a table to query in Spark using Python -

i'm trying load file directly s3 , trying sparksql on it. eventually, plan on bringing in multiple files multiple tables (1:1 map between files , tables). so i've been following this tutorial @ describing each step. i'm bit stuck on declaring proper schema , variable, if any, referred in from clause in sql statement. here's code: sqlcontext.sql("create table if not exists region (region_id int, name string, comment string)") region = sc.textfile("s3n://thisisnotabucketname/region.tbl") raw_data = sc.textfile("s3n://thisisnotabucketname/region.tbl") csv_data = raw_data.map(lambda l: l.split("|")) row_data = csv_data.map(lambda p: row( region_id=int(p[0]), name=p[1], comment=p[2] )) interactions_df = sqlcontext.createdataframe(row_data) interactions_df.registertemptable("interactions") tcp_interactions = sqlcontext.sql(""" select region_id, name, comment region region_id > 1 ""&qu

javascript - Finding the Alpha given 3 colors -

for javascript program making, need find alpha value of overlay layer (#7f7f7f) on top of color (for example, #4a6cd4), had created output color (for example, #6380da). this: from top bottom: #7f7f7f (the alpha unknown) #4a6cd4 which output #6380da. need know alpha value of overlay , how find it. can please me? the "official" blending formula should be resulting color = alpha * overlay color + (1 - alpha) * background color the equation has calculated each channel (red, green , blue, each represented 2 digits of color code in hexadecimal representation) you can solve alpha (or use excel , solve numerically) the formula not match example values have given, though - actual values or random example?

if statement not working batch (goes directly to else) -

i'm working on password batch file;but, if statement not working. when ask check whether password correct, goes else statement, if correctly enter password (hi). here part of code has problem: if "%r%"=="hi" ( goto b ) else ( echo access denied. goto f ) and here entire code: echo off color 0f pause :f set /p r = "please enter passcode " if "%r%"=="hi" ( goto b ) else ( echo access denied. goto f ) :a /l %%a in (1,1,234) ( color 6e echo %random%%random%%random%%random%%random%%random%%random% color 2a echo %random%%random%%random%%random%%random%%random%%random%%random% color 1b echo %random%%random%%random%%random%%random%%random%%random%%random% color 5d echo %random%%random%%random%%random%%random%%random%%random%%random% color 4c echo %random%%random%%random%%random%%random%%random%%random%%random% ) goto c :b echo welcome pause >nul echo current computer not contain previous files. pause >nul echo d

how to delete 2 rows with one query with mysql -

hi guys how can delete 2 rows in 1 query 1 table. code is: delete panel_friends friends_friend_id = ' . $k . ' , friends_member_id = ' . $key2 , friends_friend_id = ' . $k2 . ' , friends_member_id = ' . $key delete panel_friends (friends_friend_id = :k1 , friends_member_id = :k2) or (friends_friend_id = :k2 , friends_member_id = :k1)

angularjs - Meteor reactive sources -

i have app there 5 collections: 1 books, 1 types (of books, fantasy, sci-fi...), 1 languages, 1 subscribtions (including type_id, lang_id , user_id) , last 1 if meteor.users. i created helper function retrieve books fitting subscribtions of each user (i'm using angular-meteor) $scope.helpers({ userbooks:function(){ var subbooks=[]; var books; var user_id=meteor.userid(); subscribtions.find({user_id:user_id}).foreach(function(sub){ books=books.find({type_id:sub.type_id,lang_id:sub.lang_id}).fetch(); for(var i=0;i<books.length;i++){ subbooks.push(books[i]); } }); return subbooks; } }) suppose new book or new subscribtions added, or user logs it, subbooks data updates? considered reactive (because contains reactive data)? i suggest simplify , publish joined collection of subscriptions , books server using reywood:pu

grep - Difficulties adding data to R dataset -

i'm not advanced r appreciated. trying add values columns in dataset , dataset called 'katie'. example, in column 'word' i'd select instances 'subjected' written , post 'middle' in column 'pre.environment', on same line 'subjected' written. there doing wrong? code, initial line works (as can see how many "subjected" items recognized in column 'word') nothing happens when enter second line of code. >x=grep("subjected", katie$word) >katie[x,]$pre.environment= c('middle') i hope example sufficient. in advance help. try following code, if understand question correctly, katie$pre.environment <- ifelse(grepl("subjected", katie$word), yes = "middle", no = katie$pre.environment)

jquery - Turning DOM element into JavaScript class with all it's inheritances -

i've been searching hours , found nothing. i'm making set of premade elements (similar bootstrap has) , want animations of these elements handled jquery , javascript. all these elements have names: dframe, dcategory, dbutton , dpanel. i've created set of classes in javascript, along functions such onclick, onload, onhover etc. now issue quite simple - want every dom element of aforementioned classes turned javascript class, inherits functions , executing function on element (elem.dofunc()) work. i've tried: document.getelementsbyclassname( "dbutton" )[0] = new dbutton(); for obvious reasons resulted in: 'elem.test() not defined function' or along these lines. thanks help! @edit: here's example, maybe that'll make bit clearer: function initialize() { document.getelementsbyclassname( "dbutton" )[0] = new dbutton(); document.getelementsbyclassname( "dbutton" )[0].test(); } document.addeventlistener( &#

unity3d - Android/data/com.project.xx/files directory missing Unity -

so i'm trying use application.persistentdatapath save device. i'm seeing though coming null. looked on device , not seeing files folder on device, makes me think that's why i'm getting null. i'm wondering how can make sure files directory made when built device using unity. to work mobile devices, should try saving , loading files resources folder. files in resources copied devices. unity load text resources

c# - Get the Count of a SubQuery -

i need count result of sql query have no control over. idea wrap inner sql wrapper count query. outer sql quite simple, here got: select count(*) ( x ) countquery where x whatever inner sql goes. problem query crash, namely if else end. how craft wrapper sql wrap around sql? here example of 1 of inner sql need count: if null <> 'pipeline_stage' begin cnts ( select o.[opportunity_id] ,[opportunity_name] ,[opportunity_details] ,[image_url] ,opportunity_value ,[probability] ,[bid_currency] ,[bid_amount] ,[bid_type] ,[bid_duration] ,[forecast_close_date] ,o.[category_id] ,c.category_name ,c.background_color ,o.[pipeline_id] ,o.[stage_id] ,[opportunity_state] ,[responsible_user_id] ,u.[first_name] ,u.[last_name] ,o.[visible_to] ,o.visible_team_id ,o.[date_created_utc] ,o.[date_updated_utc] ,o.owner_user_id

python - Can't load .css and image files in django -

Image
i can't load images , css files in django, although seems fine in settings.py , in home.html file itself... can problem here? in static folder there template , css , image folders. html: {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <title>main page</title> settings.py: # static files (css, javascript, images) media_root = os.path.join(base_dir, "/media") #media_url = '' #static_root = os.path.join(base_dir, "static") staticfiles_dirs = [ os.path.join(base_dir, "/static") ] static_url = "/static/" unfortunately, looks this: django.contrib.staticfiles not included in installed_apps. your settings.py should (in installed apps) installed_apps = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes

ubuntu - How can i do "-" * 60 for Unix command line -

this question has answer here: how can repeat character in bash? 17 answers if want print 60 dashes. somehow echo "-" * 60 . how can this? thanks. printf "%*s" 60 "" | tr " " "-" the printf command prints empty string padded spaces fit width of 60. tr converts spaces dashes. this not print trailing newline. if want one, add ;echo end of command.

Is it possible to process objects in a Google Cloud Storage bucket in FIFO order? -

Image
in web app, need pull objects gcs 1 one , process them. question is, "how send request gcs next unprocessed object?" what i’d rely on sort order provided gcs , process objects in sorted list 1 one. way, need keep track of last processed item in app. i’d rely on sort order provided timecreated timestamp on each individual object in bucket. when query bucket via json api, notice objects returned sorted timecreated oldest newest. for example, query ... returns list ... { "items": [ { "name": "cars_train/00001.jpg", "timecreated": "2016-03-23t19:19:47.506z" }, { "name": "cars_train/00002.jpg", "timecreated": "2016-03-23t19:19:49.320z" }, { "name": "cars_train/00003.jpg", "timecreated": "2016-03-23t19:19:50.228z" }, { "name": "cars_train/00004.jpg", "timecreated": &qu

java - Can I better use memory in this program? -

the code below works way want work. wanting see if using necessary amount of memory , not of it. want go programming career nice hear of professionals out there. import java.util.*; public class guessinggame { public static void main(string[] args) { int counter = 0, number, guess, yes = 1, no =2, answer; scanner input = new scanner(system.in); number = ((int) (math.random() * 100)); system.out.println("would play guessing game?"); system.out.println("enter " + yes + " yes, , enter " + no + " no"); answer = input.nextint(); if(answer == no) { return; } else { while (answer == yes) { system.out.println("welcome guessing game"); system.out.println("there has been number between 1 , 100 picked \n have 5 chances guess number"); system.out.print("please enter guess >> ");

javascript - Remove certain values in multidimensional array -

i have array arr = [ [1,2,3], [4,5,6], [7,8,9] ] i want remove array contains element 4. here remove 4,5,6. it'd arr = [[1,2,3],[7,8,9]]; i tried for loop 0. read remove items array splice in loop didn't work. removed first number instead. arr.filter(function(v) { return !v.includes(4); });

javascript - What does "ease" stand for? -

what term "ease" stand for? appears in code spoiler button. refer margins, gradient, link styling or totally different? in nutshell ease timing function used in css animations , transitions. for more details go through these links : timing function w3schools timming function

sockets - How to authenticate with Node.js/Express + Passport + Websockets? -

i building angular2-login-seed uses passport.js oauth strategies authentication. default method of authentication these tools use of http cookie signed express. passport, can tell, manages actual set cookie header express can authenticate each subsequent request via request.isauthenticated() , access data set passport via req.session.passport.datahere . i want incorporate realtime data in application via websockets. of course means socket stream coming server client. communication entirely separate regular http server request meaning: it not contain http cookie http requests contain express not broker interaction sockets, managed whatever implementation used in backend (sock.js, socket.io) this makes difficult streamline authentication between http requests express, , websocket data backend separate methods of communication. from research, leaves me 2 options. 1 of use library give socket implementation (preferably sock.js on socket.io need more research) access expr