Posts

Showing posts from March, 2015

python - MySQL Query to fuzzy(?) search a software database -

i have software names database need search ,now trying find query select right software name . software name field varchar example software list in db: adobe flash professional mozilla firefox browser 20.0 adobe photoshop lightroom netbeans ide winrar 5.10 beta 2 query firefox be: firefox or mozilla firefox query lightroom be: lightroom or adobe lightroom or photoshop lightroom query winrar be: winrar or winrar archiver i have tried work soundex or levenshtein distance , not return desired result . you looking fulltext searching: https://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html note need create fulltext index on searched column, , may want consider adding relevant keywords (so abovementioned "archiver" matches on something)

c++ - c++11 equivalent of c# Interlocked.Increment -

i'm rewriting c# code c++: public class lightorder { private static int internalidcounter; public int internalid { get; private set; } // control myself call method once each order public void assigninternalid(int ordersexecutorid) { // if internalid assigned, i.e. != 0, can print error or internalid = interlocked.increment(ref internalidcounter); // more } // more } this works fine - each order has sequential id if assigninternalid called different threads parallel. what closest c++ equavalent code? should declare internalid std::atomic<int> , use ++ ? or should declare internalid int , use std::atomic_fetch_add ? should declare internalid std::atomic<int> , use ++ ? yes. or should declare internalid int , use std::atomic_fetch_add ? no. functions atomic_fetch_add work on atomic types (specialisations of atomic , or types atomic_int ), you'd still need atomic type.

c# - How to show a picture box inside a panel on hover programmatically? -

i have following problem, because quite new don't know if asking right questions...hope can put me in right direction, in advance. i have panel. inside there textbox(same size panel(140*40) , picturebox(smaller , in right top corner, 15*15).at moment able when mousehover panel(and textbox) show picturebox image deleting in it. if pass mouse on picturebox himself dissapears, , want happens when mouseleave textbox or panel. a college told me must use parent property, have no idea how can that. i don't know if explanation good, leave code here, can point me solution. textbox tbrole , panel pnrole , picturebox pbdeletex : tbrole.mousemove += (senderl, el) => { if (mousehover) { pbdeletex.visible = true; mousehover = true; } else { pbdeletex.visible = true; mousehover = false; } tbrole.backcolor = col

c - How does preprocessor make that expansion (define macro found in included header file ) -

i have header file contain constant f_cpu , use macro guard header.h #ifndef f_cpu #define f_cpu 1000000ul #endif and source.c file #define f_cpu 16000000ul #include "header.h" how first macro(in c file ) expand value not included yet? use -e option of preprocessor follow happens. define f_cpu macro in first line of source.c , after when header file included, macro definition in header not takes place because of #ifndef guard. note there no macro expansion in code. expansion takes place when use macro.

mysql - Calculating average from 2 database table colums -

i trying calculate average based on values 2 table columns in mysql . lets have table structure: id | user_id | first_score | last_score 1 | 1 | 10 | 60 2 | 1 | 70 | 10 3 | 1 | 100 | null what trying achieve here, calculating avg of highest value (i.e. 60, 70, 100). seeing in different colums, not sure how go it.. you solve greatest function. unfortunately results in null when 1 or both values null. so: select avg( greatest( coalesce(first_score,last_score) , coalesce(last_score,first_score) ) ) mytable;

grep command to match only request url of access log -

i need find accessed urls having keywords config,tmp,backup or dump. grep '/config/\|/tmp/\|/backup/\|/dump/' access.log when grep access log getting unwanted logs below 106.221.160.250 - - [11/apr/2014:12:07:13 -0400] "get url.com/perfect http/1.1" 200 43 "file:///something/tmp/579928.html" "htc_smart_f3188 mozilla/5.0 (like gecko) obigo/q7" 0 20675 it's unwanted get url.com/perfect http/1.1" 200 43 "file:///something/tmp/579928.html doesn't contain desired keyword. how should change grep command? try this: grep 'tmp\|config\|backup\|dump' accessl.log

linux - "cannot write to log file pg_upgrade_internal.log" when upgrading from Postgresql 9.1 to 9.3 -

i keep on getting above error whenever run following command via postgres user. /usr/lib/postgresql/9.3/bin/pg_upgrade \ -b /usr/lib/postgresql/9.1/bin/ \ -b /usr/lib/postgresql/9.3/bin/ \ -d /var/lib/postgresql/9.1/main \ -d /var/lib/postgresql/9.3/main cannot write log file pg_upgrade_internal.log failure, exiting i'm using ubuntu 13.10. both postgresql 9.1 , 9.3 running properly. make sure run command directory writable postgres user, /tmp or /var/lib/postgresql : $ cd /tmp $ usr/lib/postgresql/9.3/bin/pg_upgrade ...

php - simplexml-load-file -- remote or local loading? -

simple question apache+php: if use simplexml-load-file make http request or load file filesystem in case have: option a: simplexml_load_file('test.xml'); option b: simplexml_load_file('http://my.website.com/test.xml'); moreover in second option, php perform dns resolution of my.website.com or there bypass mechanism? thanks lot! option load straight disk, option b perform http request, including dns lookup. there no bypass dns lookup, other modifying hosts file or putting in ip directly.

Android: Sharing app content to a web page -

i want app users able share 1 of app pages others external web link marketing strategy, people don't have app can view page , excited download , register although no 1 can view app without signed in, have app , web domain didn't build website yet, efficient way ? you can write code on server receive data, store , serve (php/mysql or java or else). easiest way make form , send request android app simulate filled-in form. publish facebook or google+, there apis , android app.

c++ - Linker Error using g++ with Qt 4.5.1 -

i'm trying test out new dev environment , having problems referencing of required qt libraries. first ran this: $ g++ helloworld.c -o helloworld -i /usr/local/trolltech/qt-4.5.1/include/qtcore/ -i /usr/local/trolltech/qt-4.5.1/include/ and got error: /tmp/ccmsm4kz.o: in function `qstring::qstring(char const*)': helloworld.c:(.text._zn7qstringc2epkc[_zn7qstringc5epkc]+0x1d): undefined reference `qstring::fromascii_helper(char const*, int)' /tmp/ccmsm4kz.o: in function `qstring::~qstring()': helloworld.c:(.text._zn7qstringd2ev[_zn7qstringd5ev]+0x2d): undefined reference `qstring::free(qstring::data*)' collect2: ld returned 1 exit status so added reference qtcore library via: $ g++ helloworld.c -o helloworld -i /usr/local/trolltech/qt-4.5.1/include/qtcore/ -i /usr/local/trolltech/qt-4.5.1/include/ -l /usr/local/trolltech/qt-4.5.1/lib -lqtcore which removed compile errors, when try run program error: ./helloworld: error while loading shared libr

moment() function works in html but not in separate javascript file -

i have included moment.min.js in page <script src="js/jquery.js"></script> <script src="js/modernizr.js"></script> <script src="js/moment.min.js"></script> <script src="js/fatcalc.js"></script> i can call <script>document.write(moment());</script> and displays date fine on page. but, when call within fatcalc.js var date = moment(); i error: 'moment' not defined. why can html page see it, not fatcalc.js file? well, figured out. seems issue jshint don't understand adding top of script fixed it. /*global moment:true */

c# - Getting XML elements textboxes from search string -

i've got xml file has multiple entries, each looking this: -<crq> <id>crq000000003314</id> <status>1</status> <summary>complete</summary> <service>server</service> <impact>3000</impact> <risk>2</risk> <urgency>4000</urgency> <class>4000</class> <environment>1000</environment> <trigger/> <triggerid>cp_00</triggerid> <coordinator>user name</coordinator> <desc>ticket description.</desc> </crq> i have string in c# app matches id, eg crq000000003314. how able load xml , return elements underneath id (status summary etc) separate text boxes when string matched on event? you can element using linq xml this: var xmldocument = xdocument.load("path"); var element = xmldocument .descendants("crq") .firstordefault(x => (string) x.el

If the prototype of `Object` in JavaScript is null, why can I do Object.toString()? -

all newly created objects (with exception of objects created using object.create(null)) contain object object.prototype in prototype chain. these newly created objects can call newobject.tostring() because tostring defined on object.prototype . however, internal prototype of object said null . if that's case, why heck can this: object.tostring(); // prints: "function object() { [native code] }" perhaps i've answered own question. tostring defined on object constructor function? why?! > var obj = object.create(null); undefined > obj.tostring(); typeerror: undefined not function > object.tostring(); "function object() { [native code] }" see, obj created null prototype, when call .tostring() on it, error happen. but object self function, , prototype function object, has .tostring() method.

networking - WCF consume web service and network architecture -

Image
i'm getting start wcf soap web service. trying implement flexible, hot-plug featured, interoperable web service. a device consumes server service (predefined ip address) means registering server, , service asks device returning configuration information of device. service remotely control registered devices later. network architecture please see diagram below. server-side service listening on 80 port. had router (router b) connects server, , set nat table 220.120.20.209:80 mapping 192.168.0.3:80. 220.120.20.209 public ip. two clients connect router (router a) , have private ip addresses relatively(170.15.40.1/ 170.15.40.2) . clients host service (called deviceservice) listening on 80 port. , didn't set nat on router a. 68.250.250.1 public ip. operation (request registration) client sends (request) message service. (response) service response message. (get config devices) service consumes client through calling http: //clientsip:80/deviceservice. operatio

java - ResultSetMetaData getting default value of column -

i using oracle database. i want default value assign column using java jdbc. but using resultsetmetadata not provide method default value of column. so please tell me idea. in advance. you can run query select data_default user_tab_columns table_name ='mytable' , column_name = 'mycolumn'

Javascript confirm multiple changes -

i want alert user changes made in 4 fields. script works 1 @ time. if 1 or 4 changes have been made, alerts first 1 , skips others. displayed in 1 confirm box. <script> function validateform() { var w = document.getelementbyid("item_name"); if (w.value != w.defaultvalue) { return confirm('update item name. continue?'); } var x = document.getelementbyid("item_brand"); if (x.value != x.defaultvalue) { return confirm('update item brand. continue?'); } var y = document.getelementbyid("department_id"); if (!y.options[y.selectedindex].defaultselected) { return confirm('update item department. continue?'); } var z = document.getelementbyid("vendor_part_num"); if (z.value != z.defaultvalue) { return confirm('update vendor part number. continue?'); } } </script> you don't want ask each field individually, first check them all, ask user, this <script

rust - How to define and use macro in module? -

when i'm trying define macro in code, compiler says this: refix/mod.rs:12:1: 12:12 error: macro definitions not stable enough use , subject change refix/mod.rs:12 macro_rules! re_fix( ^~~~~~~~~~~ refix/mod.rs:12:1: 12:12 note: add #[feature(macro_rules)] crate attributes enable refix/mod.rs:12 macro_rules! re_fix( i've added lot of #[feature(macro_rules)] , didn't help. source code: https://gist.github.com/suhr/11207656 ps: yes, they're lot of other errors there, interested one. i think error message misleading. have add #![feature(macro_rules)] main crate module (note exclamation sign), along #![crate_id=...] , others. #![crate_id="rsfix#0.0"] #![feature(macro_rules)] macro_rules! example( ... ) fn main() { example!(...); } this should work on latest compiler version.

actionscript 3 - How to drag and drop multiple objects to specific targets? -

i new as3. of course ignore reset button now. know code big , clunky don't mind understood me. i trying match yellow ball yellow goal , green green , on. however every time try drag second object can't, object stuck, hear problem as3/flash , simple way solve drag off screen don't want do. yellowball.addeventlistener(mouseevent.mouse_down, mousedowny) redball.addeventlistener(mouseevent.mouse_down, mousedownr) blueball.addeventlistener(mouseevent.mouse_down, mousedownb) greenball.addeventlistener(mouseevent.mouse_down, mousedowng) yellowball.addeventlistener(mouseevent.mouse_up, mouseupy) redball.addeventlistener(mouseevent.mouse_up, mouseupr) blueball.addeventlistener(mouseevent.mouse_up, mouseupb) greenball.addeventlistener(mouseevent.mouse_up, mouseupg) resetbutton.addeventlistener(mouseevent.click, reset); addeventlistener(event.enter_frame,enterframehandlerr); function mousedowny(event:mouseevent):void { yellowball.startdrag(); } function mousedownr(e

css3 - Bootstrap 3 Change display:block to another value -

when looking @ checkbox based on bootstrap 3 class "checkbox" in ie development tools display set block, as: display:block; when uncheck box in front of display:block has cross-over line. checkbox looks how want. need specify in inline style value display equal crossed on display:block being unchecked. tried different values display in inline style nothing works. suggest set value display in inline style? here segment of code: <div class="checkbox" style="min-height:20px;padding-top:3px"> <asp:checkbox id="chkclosewo" runat="server" cssclass="checkbox" /> </div> here html code: <div class="checkbox" style="min-height:20px;padding-top:3px;display:inherit"> <span class="checkbox"><input id="maincontent_chkclosewo" type="checkbox" name="ctl00 $maincontent$chkclosewo" /></span> </div>

java - Interface methods - implementation vs. definition -

please explain why following isn't valid in java (1.7). having interface: interface foo { mymethod(argument arg) } where argument interface: interface argument{} an implementation of argument : class someargument implements argument{} and implementation of foo : class bar implements foo { mymethod(someargument arg) {} } the class bar results in compilation errors, since mymethod isn't implemented. there anyway accomplish above out need of casting? thanks! the mymethod() signature has exact defined in foo interface. suppose have class ( baz ) implements argument . then, mymethod(argument arg) signature allow passing parameters of baz type. but if keep this: class bar implements foo { mymethod(someargument arg) {} } you not able pass baz instances mymethod , because you've broken contract. as side note, should follow naming conventions when developing!

ios - Reminder App using Core Data and TableView -

how can create table each section there titles such dates , dates duplicate different times included in section same date? ios calendar. i not use eventstore , calendar, , reason work using core data , have created data model inside created date attribute. let me give example, sample output: reminder 04/23/2014 17:33:32.502 [2654:60 b] (      "4/22/2014 16:45:42 +0000",      "4/22/2014 16:50:25 +0000",      "4/23/2014 17:50:03 +0000",      "24/4/2014 15:45:43 +0000" ) my thought is: the sections of tableview should 3, takes dates of 22, 23 , 24 , in section 22, there must 2 dates of 22 different times. any advice on how move?

mongodb - Mongo db aggregation multiple conditions -

i want project collection applying exporting value if field inside range. sort of: db.workouts.aggregate({ $match: { user_id: objectid(".....") } }, { $project: { '20': { $cond: [ {$gt: [ "$avg_intensity", 20]} , '$total_volume', 0] } } }) i need value if avg_intensity inside range. group , sum on projection result. what trying applying $gt , $lt filter no success. db.workouts.aggregate( { $match: { user_id: objectid("....") } }, { $project: { '20': { $cond: [ [{$gt: [ "$avg_intensity", 20]}, {$lt: [ "$avg_intensity", 25]}] , '$total_volume', 0] } } }) how may apply both $gt , $lt conditions? to combine logical conditions under $cond operator wrap conditions $and operator: db.workouts.aggregate([ { "$match": { "user_id": objectid("....") }}, { "$project": { "20": { &q

javascript - Why do JS Promise A+ create/fulfill/reject not part of the spec? -

http://promisesaplus.com/ finally, core promises/a+ specification not deal how create, fulfill, or reject promises, choosing instead focus on providing interoperable method. future work in companion specifications may touch on these subjects. as functional developer, deal monads , operators point bind map or flatmap chain calls wrapped inside monad box. according question js deferred/promise/future compared functional languages scala , map , flatmap operators seems melted under then in js spec, because not make sense provide both in dynamically typed language js (?) , more convenient use , remember single operator. so far good, there's then operator ( that doesn't seem implemented ) but why promise create / fulfill / reject not part of spec? it's having half monad :( it seems i'm not 1 complain typically, problem is: i want create js library i want expose promise-based api i want client choose promise implementation wants use

Create PostgreSQL 9.3 index on json column through python, django, south? -

i have json column , need add index that: create unique index index_name on table ((column->'nest1'->'nest2'->'nest3'->>'data_to_index')); this works if execute sql lets pgadmin iii. problem need create index on django south migration. so, i'm doing in migration file is: def forwards(self, orm): ... db.execute("""create unique index index_name on table ((xml->'nest1'->'nest2'->'nest3'->>'data_to_index'))""") but index not created after migration. i tried in lot of different ways using psycopg2 directly, loading , executing sql file... nothing works! can me? thank you!

C++/Qt perform mouse click -

i've started qt5 / c++ project , wish control mouse (outside application window) in platform independent way. i've figured out, there nice method: qcursor::setpos(int x, int y) which allows, move cursor. is there api performing clicks?

Android Add Yes/No box to listView.setOnItemClickListener -

i've been trying lot of things try working, have list view displaying sqlitedb. each row of database clickable want able copy table in database. function working fine. problem want yes/no box appear confirm before gets copied in. have gone through numerous tutorials , been on here searching solution, none can fit in. here code have sitting inside displaylistview() method. in advance! listview.setonitemclicklistener(new onitemclicklistener() { public void onitemclick(adapterview<?> listview, view view, int position, long id) { // cursor, positioned corresponding row in // result set cursor cursor = (cursor) listview.getitematposition(position); dbhelper.addtoplanner( cursor.getstring(cursor.getcolumnindexorthrow("band")), cursor.getstring(cursor.getcolumnindexorthrow("day")), cursor.getstring(cursor.getcolumnindexo

In Android system, how many intents can system handle per second? -

roughly how many intents can android system handle per second/minute? i refer http://developer.android.com/guide/components/intents-filters.html seems loaded question , not seem answerable, sorry.

binary - Bitwise rotation with AND, OR, XOR gates -

how 1 rotate 4 bit binary number 4 places using and, or, xor gates? the inputs called x_0 , x_1 , x_2 , x_3 x_3 msb , x_0 lsb. for example 1010 rotated right 4 places 0101 . i can't seem find sources this. a 4-bit number rotated 4 bits in either direction same number started with. think playing joke on you. actually showed bit-reversing number, not rotating it. to implement bit-reverser combinatorial function, need 4 pieces of wire. connect input[i] output[3-i]. to implement state machine, use gates implement 4 clocked d-type flip flops (see the wikipedia page diagram . connect input[i] output[3-i].

mod rewrite - How to redirect from magento site to wordpress blog using .htaccess? -

i have magento main site , wordpress in blog folder. i want redirect blog when types http://www.example.com/blog/ however not redirecting blog. tried om magento's .htaccess (root) ... rewriteengine on rewriterule ^blog/(.*)$ http://example.com/blog/$1 [l,r=301] please if wrong.

python - Two-way ssl authentication for flask -

i have implemented ssl communication client application verifies identity of ssl server application using flask. want ssl server application verify identity of ssl-client application. possible flask ? how verify client certificate ? during first handshake client sending csr , in response sending certificate signed self signed ca certificate. but not yet clear how client verified server while next communication. there callback cert verification. link on google groups says not possible have ssl authentication on flask. in order 1 need use webserver apache,ngnix. way authenticate client ? there 1 more thing want achieve need identify each client based on certificate. possible flask. my question naive not yet familiar flask disclaimer before start note @emanuel ey's comment. want consider if being done on production or development server first. example; if using apache webserver https component can done apache. thing differently pass through certificate details

XML/PHP: XML doesnt get written properly by my script -

Image
i seem have small problem, whenever insert information via form xml file, adds information directly in previous's entry's child, instead of creating new child, entry, this: <people> <person> <name>lighty</name> <age>17</age> <sex>m</sex> <comment>iets</comment> <name>darky</name><age>22</age><sex>f</sex><comment>things</comment></person> while need have something, this: <people> <person> <name>lighty</name> <age>17</age> <sex>m</sex> <comment>iets</comment> </person> <person> <name>darky</name> <age>22</age> <sex>f</sex> <comment>iets</comment> </people> i tried using "$xml->formatoutput = true;" line, add child formatoutput 1 filled in, complete fail. an

CodeIgniter store session data in variable and pass it to another function -

i want store information of user if submits form, in order display in function able know did action. here 1st function public function view() { $page = 'listevisiteurs'; $comptable = array(); $compt= array(); $message = array(); if ($this->input->post()) { $mois = $this->input->post("mois"); $nom = $this->input->post("nom"); $session_data = $this->session->userdata('logged_in'); $data['nom'] = $session_data['nom']; $comptable = array($data['nom'] => $mois); ........ } $compt = array('fields' => array()); foreach ($comptable $key => $label) { $compt['fields'][] = array( 'key' => $key, 'label' => $label ); } ...... here second one public function get_visiteursmep() { $

plugins - Android DDMS is already installed so an update will be performed instead -

i had same problem many people had in updating adt plugin. used procedure described here: error message : android sdk requires android developer toolkit version 22.6.1 or above so, checked developer tools , hit next button. , says 'your original request has been modified. "android ddms" update performed instead.' but doesn't update, nor give me way one. (tried post screencap stackoverflow says need rep of @ least 10) here solution follow steps here: start eclipse, select > install new software. click add, in top-right corner. in add repository dialog appears, enter "adt plugin" name , following url location: https://dl-ssl.google.com/android/eclipse/ click ok. if have trouble acquiring plugin, try using "http" in location url, instead of "https" (https preferred security reasons). in available software dialog, select checkbox next developer tools , click next. in next window, you'll see list o

creating accumulator function (python) -

how create accumulator function called repeatedly single numeric argument , accumulate argument sum. each time called, returns accumulated sum. example given below. a=make_accumulator() a(10) -> 10 a(20) -> 30 a(-15) -> 15 class myaccumulator: def __init__(self): self.sum = 0 def add(self, number): self.sum += number return self.sum = myaccumulator().add print(a(10)) # => 10 print(a(20)) # => 30 print(a(-15)) # => 15 something ?

serial port - Using inbuilt Fingerprint Scanner .NET -

i making application , wanted ask if can interface inbuilt fingerprint scanner (of hp laptop) in .net application there's no reason why couldn't, if it's connected serial port device (as implied tags used on question). however, that's not end of it. need know how communicate device, , need know how make sense of data sends you. now, devices give functioning activex component can import project , handles you. otherwise, you're going want consult documentation of particular device on computer, , see if it's workable. there's sdks work .net (like http://www.griaulebiometrics.com/page/en-us/grfinger_sdk , http://www.digitalpersona.com/developer-tools/sdks/software-development-kits/ ), , c sdks quite easy interface .net well.

angular services - Angularjs: Pass parameter from controller to factory -

i have following code in service define(['./module'], function(services) { 'use strict'; services.factory('user_resources', ['$resource', '$location', function($resource, $location) { return $resource("", {}, { 'testservice':{method:"get",url:'http://11.11.11.11/url/index.php?data={method:method_name,params:{param1:value,param2:value,}}',isarray:true} }); }]); }); from controller calling factory method how pass parameters testservice controller? following code in controller call factory user_resources.testservice().$promise.then(function(data) { console.log("****************************"); console.log(data); $scope.mylist=data; }); thats not how $resource works. $resource("http://11.11.11.11/url/index.php", {'testservice':{method:"get",url:'http://11.11.11

android - Web App Database vs Mobile App Data base -

i have created web application inventory management system , have used sqlserver 2005 supporting database. need create similar application using android. my questions are: 1.) can use same database creating android application or should modify database fit mobile platform. 2.) if can use above database how provide connectivity between android application , sqlserver. web service way out? thanks in advance

xml - PHP DOMNode insertAfter? -

i bit stuck on how reorder nodes. trying add 2 simple "move item up" , "move item down" functions. while insertbefore() want move sibling before preceding one, easiest way move 1 node down in dom? appreciated! code example: try { $li->parentnode->insertbefore( $ul, $li->nextsibling); } catch(\exception $e){ $li->parentnode->appendchild( $ul ); }

php - How to see Google Analytics dimension variables on Dashboard -

Image
i going through strange problem; may doing wrong. i need see list of usernames (and analytics) logged in on site. created dimension1 variable , listed "user name" "session" type on google analytics. here did in code:- p.s. code in analyticstracking.php @ end of page (after "body" tag) var user = "<?php echo $_session['username']; ?>"; if (user) { //alert(user); (function(i,s,o,g,r,a,m){i['googleanalyticsobject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new date();a=s.createelement(o), m=s.getelementsbytagname(o)[0];a.async=1;a.src=g;m.parentnode.insertbefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'ua-xxxxxxxx-1', 'thesite.com'); var dimensionvalue = user; //ga('set', 'dimension1', dimensionvalue); ga('set', {

java - Have to write a Tic Tac Toe game for 2 players -

import java.util.scanner; public class gameboard { public static void main(string[] args) { string str1; scanner scan = new scanner(system.in); system.out.println("player 1 please enter 1 or 2, 1 = o, 2 = x"); int = scan.nextint(); if(a == 1){ string str2 = "o"; str1 = str2; }else{ string str2 = "x"; str1 = str2; } system.out.println("player 1 please enter row (1, 2 or 3) want: "); int b = scan.nextint(); if (b == 1 || b == 2 || b == 3){ system.out.println("player 1 please enter column want: "); int c = scan.nextint(); if( c == 1 || c == 2 || c == 3){ if ( b == 2 && c == 2){ system.out.println(" | | "); system.out.println("-----------"); system.out.println(" | " + str1 + " | "); system.out.println(&quo

cookies - RabbitMQ as Windows service: badarith error on rpc.erl -

i experiencing problems rabbitmq started service on windows. operative system: windows 8 (microsoft windows nt version 6.2 server) (build 9200) erlang: r16b03 (erts-5.10.4) rabbitmq: 3.2.2 goal: create rabbitmq cluster 3 servers: srv1, srv2, srv3. note: have followed official documentation all following operations executed user "administrator". first scenario: start rabbitmq command line background process i used command "rabbitmq-server -detached" on srv1. result: file ".erlang.cookie" created under c:\users\administrator execution of command "rabbimqctl status" successful , gives me current state of node. can copy file .erlang.cookie in same folder on srv2 , srv3 , create cluster. second scenario: start rabbitmq service (this requirement have) result: file ".erlang.cookie" created under c:\windows. when type command "rabbitmqctl status" file .erlang.cookie created under c:\users\administrator , recei

c++ - how to tell if a string is contained in another string -

this question has answer here: check if string contains string in c++ 7 answers c++ code. example: x: "this #my first program"; y: "#my"; bool function(string x, string y) { //return true if y contained in x return ???; } you can use std::string::find() bool function(string x, string y) { return (x.find(y) != std::string::npos); }

mysql - Setting Auto_Increment to start from 1000 when creating table -

i want table's primary key start number 1000 instead of default. read around here , answer declare increment value when creating table follows: auto_increment = 1000; i tried when create table returns syntax error. of course make changes on phpmyadmin want on create instead. please advice wrong. thanks. create table if not exists departments ( dept_id int auto_increment=1000, -- equals sign returns syntax error. dept_name varchar(255), dept_address varchar(255), dept_tel int, primary key (dept_id) ); the starting point must specified table option: create table if not exists departments ( dept_id int auto_increment, dept_name varchar(255), dept_address varchar(255), dept_tel int, primary key (dept_id) ) auto_increment=1000; you can see full syntax creating table here

SQL Combining two joins -

i understanding of sql average, wondering if there way more efficiently write statement? the primary key of table company uniqentity , has company name nameof in row. in table line , primary key uniqline , have columns entitycompanybilling , entitycompanyissuing (both foreign keys uniqentity ). this code below works fine, trying make more efficient. possible? select l.uniqline, b.nameof billingcompany, l.uniqentitycompanybilling, i.nameof issuingcompany, l.uniqentitycompanyissuing line l inner join company b on b.uniqentity = l.uniqentitycompanybilling inner join company on i.uniqentity = l.uniqentitycompanyissuing changing structure of query may not make more efficient (it seems simple can be). changing structure of data might: add indexes (if not already) on uniqentitycompanybilling , uniqentitycompanyissuing add index on company.uniqentity didn't catch column pk if index on company.uniqentity isn't clustered,

mysql - PHP-cgi stops working randomly without error log -

i'm using nginx (wt-nmp - portable mysql nginx php app.). working except php-cgi, stopping randomly , have start again, in fact realized if add post website (in wordpress), stopping. stopping without no reason, maybe there reason cant see because no error shows in errorlogs. i searched on internet , found problem couldn't use these methods on windows server. the solution found: set php_fcgi_max_requests=0 script starts php-cgi.exe @echo off echo starting php fastcgi... set php_fcgi_max_requests=0 set path="d:\program files\php;%path%" "c:\program files\php\php-cgi.exe" -b 127.0.0.1:9000 -c "c:\program files\php\php.ini" any idea problem? or idea how use codes on windows server. searched windows , found 1 solution, iis. the proccess: adding php_fcgi_max_requests=0 environment variables. the following setting works fine windows 2012 r2 server !!! http://i.stack.imgur.com/hriao.jpg control panel-> system->advanced syst

python - How to take a text file and create a copy but with numbered lines -

this poem saved in text file: 'twas brillig, , slithy toves did gyre , gimble in wabe; mimsy borogroves, , mom raths outgrabe. - lewis carroll i want create copy of file , change name , have output this: 1: 'twas brillig, , slithy toves 2: did gyre , gimble in wabe; 3: mimsy borogroves, 4: , mom raths outgrabe. 5: - lewis carroll can done using loop or there simpler way this? you can iterate through each line of poem file , line number using enumerate : with open('poem.txt') poem_file: open('poem-numbered.txt', 'w') numbered_file: index, line in enumerate(poem_file, 1): numbered_file.write('{}: {}'.format(index, line)) the code above first opens original poem file ( poem.txt ) , opens file writing (hence w second argument open ). iterates through lines of original file , writes line output file ( poem-numbered.txt ) line number. when passing w second argum

batch file - convert infopath form to html form -

i need convert infopath form html form (logic & visual) knows how can automatically batch script or other language script php ? hope can me thanks the infopath file *.xsn zip file. can change extension myform.zip , extract internal files. of files xml data , xsl views. can use whatever scripting language want convert them else. xsl hmtl xsl added data supposed go.

sql - MySQL - JOIN based on CONVERT a column to NUMERIC -

basically, i'm trying convert table field while doing join. numbers in field starts 0009897896, 000239472938, 00032423, , forth. i want join based convert, when query column, display numbers without leading 0s, display 9897896, 239472938, 32423 , forth. can me avchieve this? i've been stuck on issue awhile :( here's i've got far... joining different database: select l.loannumber '1 loan number', fl.loan_num '2 loan number', case when loannumber<>fl.loan_num "yes" else "no" end "issue?" loan l left join cware_cms.file_lst fl on (convert(substring_index(l.loannumber, '-', -1), unsigned integer)) = (convert(substring_index(fl.loan_num, '-', -1),unsigned integer)) left join cware_cms.case_lst cl on cl.case_id = (select max(cware_cms.file_case.case_id)) cware_cms.file_case inner join cware_cms.case_lst on cware_cms.file_case.case_id = cware_cms.case_ls

Proper way to include PHP files in Wordpress theme -

i trying develop wordpress theme requires lot of php functions , custom classes. i wondering best practice including additional php files within worpdress. example: list every file include using: include(); require_once() etc when review other developers themes, never stumble across batch of "include() statements, believe must missing standard method of performing these includes. thanks in advance :) you can follow method. suggest use require include file. _s ( aka underscores ) theme starter kit , default themes of wordpress such twentyfourteen, twentythirteen, etc using require include files. see sample code used in tweentyfourteen theme. require get_template_directory() . '/inc/template-tags.php';

Count number of times a word appears in php array -

i need count how many times user entered word appears in array. user enters text form textbox, , text goes string variable in php, exploded array index every space. i need count how many times each word appears. let's text "yo yo yo man man man", need count how many times word "yo" appears amount of times "man" appears. please keep in mind text user enters, using method such "str_word_count" isn't option, since takes hard-coded text. the code have set far: form.php: <html> <head> <title>part 1</title> </head> <body> <h1></h1> <form action="part1result.php" method = "post"> <input type="text" name="text"/> <input type="submit" value="submit" /> </form> </body> </html> result.php: <head> &l

python - How to create custom filter_by in SQLAlchemy -

i want create more complex filter_by - in way if pass kwargs , values of none, don't want included in filter. i'm not sure how override filter_by globally. effectively i'm looking is. data = {'is_enabled': true, 'city': 'sf', 'address': none} query.smart_filter(data) and smart_filter excludes 'address' field , calls filter_by 'is_enabled' , 'city' values. is there way build this? subclass sqlalchemy.orm.query , add smart_filter method, , pass new class sessionmaker . along lines: class myquery(query): def smart_filter(self, **kwargs): kwargs = {key: value key, value in kwargs.items() if value not none} return self.filter_by(**kwargs) session = sessionmaker(query_cls=myquery)

Given acceleration data and the corresponding time, how can I find the position and velocity in MATLAB? -

i given data in excel spreadsheet. after importing velocity = cumtrapz(t,y) , position = cumtrapz(velocity) ? it correct if car starts 0 @ distance zero. otherwise need have initial velocity there well. notice here solving the equation a = f(t) = dv/dt , further a = d^2s/dt^2 identifying v ds/dt . solving system of ordinary differential equations: a = dv/dt v = ds/dt this can done in few ways. eg euler forward. v'(t) = (v(t+h)-v(t))/h <=> v(t+h) = hv'(t)+y(t) where derivate given, means a = a(t) . iteration initialized initial condition v(0) , must given. when know v go s. use again euler forward as, s'(t) = (s(t+h)-s(t))/h <=> s(t+h) = hs'(t)+s(t) where must know initial condition s(0) . if v(0) = s(0) = 0 . euler forward o(h) algorithm, knowing trick of solving differential equations step step doing transformation s'(t) = v(t) possible better. runge-kutta method available you. , method use, cumtrapz, o(h^2) method. litt

Android video does not resume in webview -

i use webview show local html content contains video on android 4.2 , 4.3. and call " webview.onpause() " method prevent video still playback when activity not visible. when activity comes foreground, video not resume after call " webview.onresume() " method. how can resume video after activity comes foreground? thanks. by default, it's not possible start media playback automatically script. can change behavior websettings.setmediaplaybackrequiresusergesture api: http://developer.android.com/reference/android/webkit/websettings.html#setmediaplaybackrequiresusergesture(boolean)

c# - Struct in Struct -

this question has answer here: c# compiler error: “cannot have instance field initializers in structs” 7 answers well, i'm trying create struct inside another, , having trouble ... the code: using system; using system.collections.generic; using system.linq; using system.text; namespace wamserver { class pstruct { public static pstruct.player[] player = new pstruct.player[100]; public struct player { public int id; public string username; public string password; public pstruct.character[] character = new pstruct.character[2]; } public struct character { public string charactername; public string gender; public string classid; public string level; public sbyte mapid; public int x;

Dynamic added controls in JQuery -

i create 2 textboxes dynamically , append table row. need validate textboxes if empty or having values.if empty means need highlight textboxes. if press validatecontrols button ,that particular row textboxes need highlighted if empty . if press validateallcontrols means need highlight textboxes in table if empty. how this? please refer fiddle link <script> $(document).ready(function () { $("#inputid").click(function () { var table = $('table#mytable'); var row = "<tr><td> <input name='name' id='name' type='text' />* </td>" + "<td> <input name='email' id='email' type='text' /> </td>" + "<td> <input id='btnadd' type='button' value='validatecontrols' /> "

java - PrintWriter wont write to .txt file -

i have tried reviewing old threads topic none of solutions seem work me. have trying write .txt file named "receipt.txt" following code getting nothing. no file created (and nothing in file doesn't exist) no errors nothing. //write file string filename = "receipt.txt"; try{ printwriter writer = new printwriter(filename); writer.println("thank shopping us"); writer.println("name: " + customername); writer.println("returning customer: " + previouscustomer ); writer.println("phone: " + phonenumber); writer.println("shirt type: " + shirttype); writer.println("shirt color: " + shirtcolor); writer.println("shirt material: " + shirtmaterial); writer.println("item amount: " + itmamt); writer.println("total cost: " + fmt3.format(totalcostmsg)); writer.close(); writer.flush(); system.out.println("receipt

excel - Time subtraction with ms involved -

Image
i have csv file data this: 1,success,19:1:6:445 1,success,19:1:7:652 1,success,19:1:10:172 1,success,19:1:11:500 1,success,19:1:12:893 ... the goal calculate time difference row above. example, duration row 1 row 2 = 1000ms + 652-445ms = 1207 ms first, load csv excel , parse using text columns below: result this: use formula in g1 millisecond difference. =sumproduct(c2:f2-c1:f1,{3600000,60000,1000,1}) , there have millisecond difference.

php - MYSQL string to check against multiple fields -

i'm trying check similar entry doesn't exist in database based on 4 pieces of information before inserting new row. it's ok if same name exists example, not if name, lat/long,, , time same. here code: $query3 = "insert locations ( name, time, area, latitude, longitude, current, previous, destination ) select * ( select name, time, area, latitude, longitude, current, previous, destination) tmp not exists ( select name, latitude, longitude, time locations name = '$name' , latitude = '$latitude' , longitude = '$longitude' , time = '$timereceived') "; the error pulling could not connect: unknown column 'name' in 'field list' i don't understand error message, , i'm thinking have syntax error in mysql string. thank in advance! your query messed up. using single quotes column names , somewhere using backticks values , somewhere using variables in column name as in query have used