Posts

Showing posts from July, 2014

c# - How to create a host application to receive data and send a response back -

i new programming , have given project have no idea how it. i have write host application.the following requirement: develop cxml webservice host testing cxml posts xyz.net . the application should read stream of data,validate against dtd. store in corresponding tables , send response client. this should example. create console application, , set startup object selfhost. run application , wcf service should available @ url stated code : http://localhost:1234/hello " [servicecontract()] public interface iindexer { [operationcontract] bool test(); } public class indexer : iindexer { public bool test() { return true; } } class selfhost { static void main(string[] args) { uri baseaddress = new uri("http://localhost:1234/hello"); // create servicehost. using (servicehost host = new servicehost(typeof(indexer), baseaddress)) {

php - Sending POST data through datatables ajax request -

i'm trying make simple ajax call in datatables reliant on post array of ids previous page's form. getting error : invalid json response which tells me returned json array empty or , have feeling has post data not being sent php/sql external script on ajax requesting data from. i'm not sure how test don't know how include $_post data in url external php page outright trigger script. heres current datatables init , php results page: <?php include_once('../functions.php'); sec_session_start(); print_r($_post['post_id']); <-- making sure post data made far ?> <script type="text/javascript"> $(document).ready(function() { var comptable = $('#comptab').datatable({ "processing": true, "serverside": true, "ajax": { "url": "baddebt_ext_sql.php", "type": "post", "datatype&

c++ - Why can templates only be implemented in the header file? -

quote the c++ standard library: tutorial , handbook : the portable way of using templates @ moment implement them in header files using inline functions. why this? (clarification: header files not only portable solution. convenient portable solution.) it not necessary put implementation in header file, see alternative solution @ end of answer. anyway, reason code failing that, when instantiating template, compiler creates new class given template argument. example: template<typename t> struct foo { t bar; void dosomething(t param) {/* stuff using t */} }; // somewhere in .cpp foo<int> f; when reading line, compiler create new class (let's call fooint ), equivalent following: struct fooint { int bar; void dosomething(int param) {/* stuff using int */} } consequently, compiler needs have access implementation of methods, instantiate them template argument (in case int ). if these implementations not in header, wouldn

camel recipientlist calling rest service is not returning json response to browser -

i have following camel route : <camelcontext trace="false" id="blueprintcontext" xmlns="http://camel.apache.org/schema/blueprint"> <route id="addressroute"> <from uri="cxfrs:bean:addresssearchendpoint"/> <removeheaders pattern="camelhttp*"/> <recipientlist> <simple>http4://<someurl>/postcodeanywhere/interactive/retrievebyaddress/v1.20/json.ws?key=<somekey>&amp;amp;address=wr2%206nj&amp;amp;company=&amp;amp;username=provi11136</simple> </recipientlist> <log message="${body}"/> </route> which uses recipient list invoke external rest service. issue having although see response in log: [ qtp269562434-42] addressroute info [{"udprn":"52269655","company":"","department":"","lin

npm - How do I set an environment variable? -

in bash can see npm environment variables npm run env . user=brianmackey 1 such environment variable. how can set environment variable, user=billybob ? i know can use npm config set <key> <value> [--global] . key+value always/in case environment variable? can set environment variables in session? single command if want set environment variables single node command, can this: $ user=billybob node server.js loaded each session if want permanently set environment variable user, edit ~/.bash_profile , add following line: export user="billybob" this automatically set given environment variable each time create new terminal session. existing entire current session lastly, if want set environment variable current session, run it's own command: $ user=billybob $ node app.js # user billybob $ node app.js # user still billybob when exit session, these temporarily set environment variables cleared.

android - How to update activity when dialog is closed -

i creating custom dialog class in extend default dialog. doing work there. once user closes dialog, how can activity know dialog closed , time update screen views results? do pass instance activity dialog class can call public method on it? or there better design? thank you what i'll this: create interface, example: ondialogcloselistener, method called ondialogclose() the activity have implement interface , override ondialogclose() method create attribute in yout dialog class of ondialogcloselistener type , constructor method , when create dialog pass activity parameter. ondialogcloselistener listener; public mydialog(ondialogcloselistener listener) { this.listener = listener; } now in onclick method of close button of dialog call method of interface. ex.: listener.ondialogclose(); and in activity class in method override ondialogcloselistener whatever want when dialog close. note: can create methods want in interface call each 1 whatever want,

Windows Phone 8.1 Hub Template Project DataContext Binding -

this might stupid question i'm having trouble recreating hub page data binding method used "hub app" template in own windows phone app. my xaml bound viewmodel class defined public property of page object , works fine long include line: this.datacontext = *viewmodel object here* within onnavigatedto() method. if comment out line, no data loaded @ runtime. might sound obvious (and question), "hub app" template never assigns object "this.datacontext" in .xaml.cs file. binding ever defined in xaml. missing? update: added xaml , xaml.cs xaml <page datacontext="{binding subject, relativesource={relativesource mode=self}}" d:datacontext="{d:designdata source=sampledata/subjectsampledata.xaml}"> xaml.cs public sealed partial class blankpage1 : page { public blankpage1() { this.initializecomponent(); } public subject subject { get; set; } protected override void onnavigatedto(navigat

c++ - Is this template syntax illegal? -

i'm getting "internal compiler error" using gcc 4.9.2: #include <type_traits> template <typename t, typename, int, template <typename u, u, u> class> struct sort; template <typename t, template <t...> class z, t n, t... is, template <typename u, u, u> class comparator> struct sort<t, z<n, is...>, 0, comparator> { template <t i> struct less_than : std::integral_constant<bool, comparator<t, i, n>::value> { }; }; int main() {} the error message states: c:\adandd>g++ -std=c++14 comparatorandsortertgeneralized.cpp comparatorandsortertgeneralized.cpp:254:80: internal compiler error: in tsubst, @ cp/pt.c:11738 template<t i> struct less_than : std::integral_constant<bool, comparator<t,i,n>::value> {}; ^ please submit full bug report, preprocessed source if appropriate. s

c# - UDP Socket code in Clojure CLR -

i'm trying figure out proper syntax interop .net system.net.sockets. problem enumeration parts of arguments. here equivalent code in c#: socket newsock = new socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp) in clojure-clr i'm trying following: (system.net.sockets.socket. (addressfamily/internetwork) (sockettype/dgram) (protocoltype/udp)) i'm getting compilerexception.invalidoperationexception. reviewed https://github.com/clojure/clojure-clr/wiki/working-with-enums regarding enum not understanding it. i've tried: (system.net.sockets.socket. (.internetwork addressfamily) (.dgram sockettype) (.udp protocoltype)) try following (import [system.net.sockets socket addressfamily sockettype protocoltype]) (socket. addressfamily/internetwork sockettype/dgram protocoltype/udp)

sockets - Using TLS on Google Talk XMPP TCP connection using PHP -

i trying connect google talk xmpp server using php. successful establishing connection , logging in using x-oauth2. google requires establish tls connection. when trying upgrade connection tls exception: stream_socket_enable_crypto(): peer certificate cn='gmail.com' did not match expected cn='talk.google.com' . here steps: $stream = stream_socket_client('tcp://talk.google.com:5222', $error_num, $error_str); // ... login, //server tells me use tls, //i tell going to, //it tells me proceed ... stream_socket_enable_crypto($stream, true, stream_crypto_method_tls_client); and error: stream_socket_enable_crypto(): peer certificate cn='gmail.com' did not match expected cn='talk.google.com' of course, if try connect xmpp server via tcp://gmail.com or tcp://www.gmail.com , won't work. i have tried establishing tls before logging in (which, assume more secure way of doing it), same problem. here whole handshake error: me: <str

Make a single dropdown menu open to the right in Semantic UI -

the semantic ui dropdown documentation gives examples of dropdowns open left , right. however, of examples given show parent dropdown opens downwards, items of dropdown being dropdown open left or right. trying create vertical menu, each element of dropdown opens right. vertical menu should not dropdown. have tried many combinations of arranging menu , right , dropdown classes , cannot work. possible? ok, i've discovered semantic automatically if place dropdowns in vertical menu: <div class="ui vertical menu"> <div class = "ui dropdown item"> <span class="text">prompt</span> <div class="item">...</div> ...

swift - split now complains about missing "isSeparator" -

after latest upgrade of swift 1.2, can't figure out how split line of text words. used this: let bits = split(value!, { $0 == " "}, maxsplit: int.max, allowemptyslices: false) but no longer works, because... cannot invoke 'split' argument list of type '(string, (_) -> _, maxsplit: int, allowemptyslices: bool)' ummm, ok, though last build? whatever, let's try... let bits = split(value!, { $0 == " "}) well , every other version can think of ends saying: missing argument parameter 'isseparator' in call let's hear beta-testing new programming languages! yay! anyone know correct secret sauce 1.2? it seems order of parameters changed in swift 1.2: let bits = split(value!, maxsplit: int.max, allowemptyslices: false, isseparator: { $0 == " "}) or, using default values: let bits = split(value!, isseparator: { $0 == " "}) the predicate last parameter , requires e

javascript - React 0.13 class method undefined -

so i've started react , es6 , got stuck basics. appreciate help. handleclick() throws error: uncaught typeerror: cannot read property 'handleclick' of undefined code follows export default class menuitems extends react.component { constructor(props) { super(props) this.state = {active: false} this.handleclick = this.handleclick.bind(this) } handleclick() { this.setstate({ active: !this.state.active }); } render() { let active = this.state.active let menuitems = [{text: 'logo'}, {text: 'promo'}, {text: 'benefits'}, { text: 'form'}] return ( <ul> {menuitems.map(function(item) { return <li classname={active ? 'active' : ''} onclick={this.handleclick.bind(this)} key={item.id}>{item.text}</li>; })} </ul> ); } } {menuitems.map(function(item) { return <li classname={active ? 'active' : &#

Is there any feature/API of sendgrid that is not offered in its integration with Google App Engine? -

sendgrid standalone product. there sendgrid integrated google app engine. there feature or api available in standalone sendgrid (e.g. event api / webhooks) not available in sendgrid integrated google app engine? sendgrid isn't integrated app engine. use same sendgrid apis regardless of whether calling them app engine or somewhere else. sendgrid have several pricing plans (bronze, silver, etc.) , 1 of pricing plans specific app engine because of marketing agreement google. sendgrid has detailed explanation of features each plan here . it isn't clear me whether "app engine" plan explicitly restricted use app engine. ip address filtering expect not use app engine plan.

php - CodeIgniter Upload File Ajax not working -

no matter can't seem file upload via ajax codeigniter method. throws , never sees uploaded file. html <div> <h1>upload translation</h1> </div> <form method="post" class="myform" enctype="multipart/form-data"> <!-- add span , pther stuff here--> <input type="file" id="foto1" name="userfile" /> <input type="button" value="submit" onclick="submitfile();" /> </form> <script> function submitfile(){ var formurl = "/system_administration/ajax_upload_translation"; var formdata = new formdata($('.myform')[0]); $.ajax({ url: formurl, type: 'post', data: formdata, mimetype: "multipart/form-data", contenttype: false, cache: false, process

ios - Compilation Error with NSParameterAssert with Xcode 6.3 -

i getting compilation errors anywhere nsparameterassert used. example: -(instancetype)initforplot:(cptplot *)plot withfunction:(cptdatasourcefunction)function { nsparameterassert([plot iskindofclass:[cptscatterplot class]]); nsparameterassert(function); if ( (self = [self initforplot:plot]) ) { datasourcefunction = function; } return self; } the code compiles fine xcode 6.2 it's giving me following errors xcode 6.3: /users/xxxx/project/app/presentation/coreplot/source/cptfunctiondatasource.m:110:5: using %s directive in nsstring being passed formatting argument formatting method i have looked online , have not seen information on error message. temp fix using following: #undef nsparameterassert #define nsparameterassert(condition) ({\ {\ _pragma("clang diagnostic push")\ _pragma("clang diagnostic ignored \"-wcstring-format-directive\"")\ nsassert((condition), @"invalid parameter not satisfying: %s&

database - Rails chart.js data coffee script -

i new rails. want populate chart.js chart data database table. managed set chart static data. i need replace static data data table sales. sales.month should represent x-axis , sales.amount should represent y-axis value. my app.js.coffee looks this: sales = sale.select(month, sum(amount) sum_of_amount) months = sales.collect(month) amts = sales.collect(sum_of_amount) jquery -> data = { labels : months, datasets : [ { fillcolor : "rgba(151,187,205,0.5)", strokecolor : "rgba(151,187,205,1)", pointcolor : "rgba(151,187,205,1)", pointstrokecolor : "#fff", data : amts } ] } my index.html.haml looks , chart displayed static vaulues. %canvas#canvas{:height => "400", :width => "600"} how proceed here? thanks. ok, problem there no data passed coffeescript. i managed getting done using gem 'gon'. here did: my app.js.

ide - How to convert MATLAB code segment to single line? -

i'm looking way convert multi-line code such : for i=1:10 foo(); end to : for i=1:10, foo(); end is there easy way in matlab editor? preferrably reversable? i think accidentally hit keyboard shortcut few days ago, , saw magic happen, couldn't find keys did press :) thanks ! p.s. i'm not sure if question belongs superuser, believe can find quick answer here, , relevant programming, win-win ! it work if write way: for i=1:10, foo();, end (note comma after foo();) but did hit + or - before for, expand of collapse "for" code sequence. if go in "view" tab, there buttons expand of collapse can use same.

numpy - Returns the value of the array when the condition was true on the n -th most recent occurrence -

i have defined function result = valuewhen(condition, array) which returns value of array when condition true on recent occurrence: import pandas pd pd1 = pd.series([0,0,1,1,0,0,1,0,1,0,0,0,1]) pd2 = pd.series([1,2,3,4,5,6,7,8,9,10,11,12,13]) def valuewhen(a1, a2): res = pd.series(index=a1.index) res.loc[a1 == 1] = a2 res = res.ffill().fillna(0) return res result = valuewhen(pd1, pd2) example: result = valuewhen(array1, array2) array1 array2 result 0 1 0 0 2 0 1 3 3 1 4 4 0 5 4 0 6 4 1 7 7 0 8 7 1 9 9 0 10 9 0 11 9 0 12 9 1 13 13 now want return value of array when condition true on n th recent occurrence: result = valuewhen(condition, array[, n]) #[if missing n=1] example: result = valuewhen(array1, array2, 1) result2 = val

Can I always assume the characters '0' to '9' appear sequentially in any C character encoding -

i'm writing program in c converts strings integers. way i've implemeted before so int number = (character - '0'); this works me, started thinking, there systems using obscure character encoding in characters '0' '9' don't appear 1 after in order? code assumes '1' follows '0', '2' follows '1' , on, there ever case when not true? yes, guaranteed c standard. n1570 5.2.1 paragraph 3 says: in both source , execution basic character sets, value of each character after 0 in above list of decimal digits shall 1 greater value of previous. this guarantee possible because both ascii , ebcdic happen have property. note there's no corresponding guarantee letters; in ebcdic , letters not have contiguous codes.

Python: Split a string, including the whitespace character -

i'm trying split given string component characters, while keeping whitespace characters in place. example of should is: input: 'the string' output: ['t', 'h', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g'] i relatively new python (using 2.7.6) , aware of .split() method. know assumes splitting on whitespace character (' ') if delimiter not set. however, when specify delimiter empty (ie split characters) string.split('') , returns valueerror: empty separator. does have suggestion how split string, while keeping whitespace characters? understand accomplished loop going on every character in string , appending list, i'm hoping find way without doing so. this first post on stackoverflow, understandable , has not been answered. thanks. you can use cast list() string: >>> list('the string') ['t', 'h', 'e', ' ', &

ASP.NET MVC: using methods in an ViewModel -

it's anti-pattern make methods in viewmodel on asp.net mvc project? for example, have field named "description" in viewmodel , string type. in view show first 40 caracteres of field. so, knowing view's rule, should do? format field in getter method in viewmodel or use htmlhelper this? or using razor? thank's attention , apologize bad english... if purely layout rule in view. if used in multiple views or don't having code in layout files create property in model substring value calculated .

ruby - Using {{ content }} and generators in Jekyll index pages -

in jekyll, post displayed in layout thusly: {{ content }} any generators might have run on content displayed so: {{ content | toc_generate }} unfortunately, not work on index pages, {{ content }} displays nothing on index pages. instead, told use loop: {% post in site.posts %} {{ post.content }} {% endfor %} so, question: how can generator run on index page, since can't use {{ content }} ? my best guess... {% post in site.posts %} {{ post | toc_generator }} {% endfor %} ...does nothing. any help? try : {% capture content %} {% post in site.posts %} <h2>{{ post.tile }}</h2> {{ post.content }} {% endfor %} {% endcapture %} {{ content | toc_generator }} {{ content }}

android - Query about sync database columns with days of the week -

i'm doing android studio project , i'm using sqlite database. in app allow user enter calorie intake day. the database have corresponding columns hold users calorie intake day. mondays calorie intake saved in monday_cal column. edit: app has 2 tables in database; 1 stores user details, calories needed , mon_cal etc. 2 stores product details , calories amount. user selects product , calories added total. for example, my question how make column in calories being entered change match days ex: when monday on column being selected changes monday_cal tuesday_cal. my original plan simple if statement , presumed there call on (clock or calender) cant find material or tutorials on area think may searching wrong phrase? , if way not possible there other alternatives. you don't want storing individual days fields in user table. if you're storing mon-sun, you're limiting ever keeping 7 days history per person. a better solution separate calorie in

MySQL - using stored procedure with nested statements -

newbie mysql here - i'm having trouble feeding parameters nested statements in stored procedure. the following 3 statements work when executed sequentially. insert rental(movie_id, membership_id, format, no_nights) values (3014, 10004, "dvd", 2); update rental inner join movie_format on rental.movie_id = movie_format.movie_id set rental_cost = daily_rental_cost * no_nights rental.movie_id = 3014 , rental.format = "dvd" , membership_id = 10004; update rental set rental_cost_due = rental_cost rental.movie_id = 3014 , rental.format = "dvd" , membership_id = 10004; however, when try , use stored procedure 1 set of parameters clauses give error messages such error 1054 (42s22): unknown column 'movie_id_in' in 'where clause' delimiter // create procedure usp_rent_movie (in movie_id_in int, membership_id_in int, format_in varchar(15), no_nights_in int) insert rental(movie_id, membership_id, fo

python - Numpy: use dtype from genfromtxt() when exporting with savetxt() -

numpy.genfromtxt(infile, dtype=none) pretty job of determining number formats in each column of input files. how can use same determined types when saving data file numpy.savetxt() ? savetxt uses different format syntax. indata = ''' 1000 254092.500 1630087.500 9144.00 9358.96 214.96 422 258667.500 1633267.500 6096.00 6490.28 394.28 15 318337.500 1594192.500 9144.00 10524.28 1380.28 -15 317392.500 1597987.500 6096.00 4081.26 -2014.74 -14 253627.500 1601047.500 21336.00 20127.51 -1208.49 end ''' code import numpy np header = 'scaled_residual,x,y,local_std_error,vertical_std_error,unscaled_residual' data = np.genfromtxt(indata, names=header, dtype=none, comments='e') #skip 'end' lines print data.dtype emits: [('scaled_residual', '<i4'), ('x', '<f8'), ('y', '<f8'), ('local_std_error', '<f8'), ('vertica

java - Custom deserialization with Gson -

i've been trying improve code on don't know how, json this: { "name": "jhon", "lastname": "smith", "clothes": { "gender":"male", "shirt": { "id": 113608, "name": "green shirt", "size": "large" }, "pants": { "id": 115801, "name": "black leather pants", "size": "large" } } } the way works far having both shirt , pants classes identical im trying use 1 class both of them.i have no in how json generated have work comes. this classes: class person public class person{ private string lastname; private string name; private clothes clothes; } class clothes public class clothes{ private shirt shirt; private pants pants; private string gender; } class shirt public class shirt{

compression - How to create a tar file (tar.gz) file with a specific directory tree -

i'm trying backup directory tree has structure: /home/joe/projects/goodie/binary_program /home/joe/projects/goodie/image.png /home/joe/projects/goodie/sound.ogg /home/joe/projects/goodie/license.txt i want create archive following structure: goodie-2015_04_09-15_34/binary_program goodie-2015_04_09-15_34/image.png goodie-2015_04_09-15_34/sound.ogg goodie-2015_04_09-15_34/license.txt i know how create date/time stamp label, don't know how create tree structure inside of tar file..any ideas? gnu tar has --transform option runs sed on file names (or file paths) prior putting them archive. source=/home/joe/projects/goodie name=goodie-2015_04_09-15_34 tar cvzf $name.tar.gz $source/* --transform "s@^$source@$name@"

html - How to stack two UL classes directly on top of one another in the middle of the page -

i'm attempting center both of these middle image directly in center , text in "nav navbar-nav" centered well, not beginning @ word "bsm". <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <img src="insertimage"> </ul> <ul class="nav navbar-nav"> <li><a href="/">bsm <strong>project</strong> connect</a></li> </ul> </div> i've had success centering left-margin 50% in css, have had no luck z-index. how have both objects directly in center of page image directly , evenly on top of words? css: div.collapse.navbar-collapse { text-align:left; width: 400px; display: block; margin-left: auto; margin-right: auto; } as @showdev says helpful see css, try in parent container set width , add margin:0 auto. don't see point

javascript - Deep equal using promises in Chai.js (testing) -

i'm using chai test , want deep compare returned object promise. i tried approach: expect(promise).to.eventually.eql(object) expect(promise).deep.equals(object) expect(promise).should.eventually.equal(object) but not work. checked many other samples none of them works. i'm getting: assertionerror: unspecified assertionerror does experienced similar? (by way, "object" contains array of objects...) you can combine eventually (which chai-as-promised ?) , deep . expect(promise).to.eventually.deep.equal(object)

ember.js - Transition to current route with different upstream/parent dynamic segment in ember? -

i have peculiar case. say on root.com/product/1/detail i want able change product dynamic segment, still in detail sub route. example `root.com/product/2/detail and if in root.com/product/1 want same transition code go `root.com/product/2 normally, you'd put transitiontoroute('product', this.get('id')) , takes me product route. need flexibility of preserving sub routes visitor may in. perhaps there sort of "currentroute" property can hook transitiontoroute('controller.currentroute', this.get('id')) while passing in new ids or objects dynamic segments? you can set current route using: currentroute = app.__container__.lookup('controller:application').get('currentpath') then should able along lines of mentioned: transitiontoroute('currentroute', this.get('id'))

c# - Implement Derived Class as Base on Constructor Exception? -

i'm working code implement hardware test system, involves communication several benchtop instruments. when instantiate instance of 1 of these instruments, constructor attempts open communication session instrument. if fails, can throw kinds of errors, i'd have instrument object default virtual or simulation mode no actual communication done can still run code. right have instruments of 1 type inheriting base class. i've added virtual methods base class perform these debugging functions, i'm stuck on clean way modify derived object @ creation time implement base classes methods when communication session fails. the ideal solution have constructor (technically new keyword) return instance of base class instead of derived class, i've done fair amount of searching , doesn't appear possible. i add property derived class use boolean flag every method in derived class tests against flag , invokes base class method if true, i'm hoping find more elegant sol

c# - ASP.NET OWIN use Email to Login (instead of username) -

currently, application owin authentication following way (using username & password , in code below). need make users log in using email (instead of username) , password . as workaround, can find username email (entered user) , use current method (username + password), double database call, i'm trying avoid. please advise. thanks! protected void login(object sender, eventargs e) { if (isvalid) { var manager = new myusermanager(new myuserstore(new mydbcontext())); myuser user = manager.find(username.text, password.text); if (user != null) { identityhelper.signin(manager, user, rememberme.checked); identityhelper.redirecttoreturnurl(request.querystring["returnurl"], response); } else { failuretext.text = "invalid login"; erro

html - Why does vw include the scrollbar as part of the viewport? -

i'm trying build website has lots of boxes of equal width , height. example, have page has 2 equal size boxes side side. the simple solution set width , height 50vw. works great until there scroll bar. i've googled around hours , can't understand why on earth vw , vh include scrollbars part of viewport. here's sample of issue html <div class="container"> <div class="box red"></div> <div class="box green"></div> </div> <div class="lotta-content"></div> css body { margin: 0; padding: 0; } .container { width: 100vw; } .box { float: left; width: 50vw; height: 50vw; } .red { background-color: red; } .green { background-color: green; } .lotta-content { height: 10000px; } notice unwanted horizontal scrollbar https://jsfiddle.net/3z887swo/ one possible solution use percentages widths, vw height, won't ever perfe

How to use Apache Cayenne context in session with concurrent ajax requests? -

i have objectcontext stored in session. have multiple ajax requests same session, modifying data of objectcontext. how go ensuring these requests thread safe? the following documentation suggests use context nesting. can give me concrete example of how works? or explanation of how nesting context allow thread-safe requests. or link documentation of best practices in these cases. thanks! https://cayenne.apache.org/docs/3.1/cayenne-guide/persistent-objects-objectcontext.html nesting useful create isolated object editing areas (child contexts) need committed intermediate in-memory store (parent context), or rolled without affecting changes recorded in parent. think cascading gui dialogs, or parallel ajax requests coming same session. edit: found following paragraph on documentation helped me. contexts used fetch objects database , objects never modified application can shared between multiple users (and multiple threads). contexts store modified objects should accesse

mysql connector - python script hangs when calling cursor.fetchall() with large data set -

i have query returns on 125k rows. the goal write script iterates through rows, , each, populate second table data processed result of query. to develop script, created duplicate database small subset of data (4126 rows) on small database, following code works: import os import sys import random import mysql.connector cnx = mysql.connector.connect(user='dbuser', password='thepassword', host='127.0.0.1', database='db') cnx_out = mysql.connector.connect(user='dbuser', password='thepassword', host='127.0.0.1', database='db') ins_curs = cnx_out.cursor() curs = cnx.cursor(dictionary=true) #curs = cnx.cursor(dictionary=true,buffered=true) #fail open('sql\\getrawdata.sql') fh: sql = fh.read() curs.execute(sql, params=none, multi=false) result = curs.fetchall() #<=== script stops @ point print l

security - Is there a way to secure access to android native libraries packaged within an apk or aar? -

i have native android library secure such specific applications can load them. there way restrict loading applications? what general solution establishing trust between lets android application , native library? how can native library prevent unauthorized method calls? use custom encryption , decryption in apk/aar native libs.the runtime decrypted native library , can system.load (from java), or dlopened location on filesystem, including 'external/internal storage'. file name may have no traces of lib or .so.

jquery - javascript .hide on click event trouble -

<header data-role="header"> <h1> tea time </h1> <a href="#home" class="ui-btn ui-btn-icon-top ui-icon-back ui-btn-icon-notext">back</a> </header> <h1>takes 3 minutes</h1> <p id="timedisp">120 sec</p> <div class="clock"> </div> <a href="#" id="start">start</a> <a href="#" id="reset">reset</a> </section> the below html controls timer function greentea(){ set duration var duration = 120; insert duration div class of clock $(".clock").html(duration + " sec"); create countdown interval var countdown = setinterval(function () { // subtract 1 duration , test see // if duration still above 0 if (--duration) { // update clocks's message $(".clock").html(duration + " sec"

java - How to join tables on non Primary Key using JPA and Hibernate -

i have 3 models user , house , userhousemap . , need access user's house through map. problem old db & can't change fact need map user userhousemap using user.name , non primary key. hibernate keeps giving me errors saying need have primary key or errors saying a jpa error occurred (unable build entitymanagerfactory): unable find column logical name: name in org.hibernate.mapping.table(users) , related supertables , secondary tables i have tried @formula workaround, didnt work. tried @joincolumnorformula didnt work either. here solution @formula @expose @manytoone(targetentity = house.class) @formula("(select * houses inner join user_house_map on houses.house_name = user_house_map.house_name user_house_map.user_name=name)") public house house; here attempt @ @joincolumnorformula solution. @expose @manytoone(targetentity = house.class) @joincolumnsorformulas({ @joincolumnorformula(formula=@joinformula(value="select name users users.i

ios - Zoom SKSpriteNode in AND out in Swift -

first off, have seen , tried implement other answers similar questions here , here , here . problem started programming ios last year swift , (regrettably) did not learn objc first (yes, it's on to-do list). ;-) so please take , see if might me see way thru this. i can pinch zoom whole skscene. can scale skspitenode up/down using other ui gestures (ie. swipes) , skactions. based off post have applied skaction uipinchgesturerecognizer , works zoom in, cannot zoom out. what missing? here code on sample project: class gamescene: skscene { var board = skspritenode(color: skcolor.yellowcolor(), size: cgsizemake(200, 200)) func pinched(sender:uipinchgesturerecognizer){ println("pinched \(sender)") // line below scales entire scene //sender.view!.transform = cgaffinetransformscale(sender.view!.transform, sender.scale, sender.scale) sender.scale = 1.01 // line below scales skspritenode // has no effect unless increase scaling >1

VBA - in Word, check if selection contains specified character string -

i have word document multiple lines of text. want determine of lines (or paragraphs if longer line) contains string " / " , delete lines don't have one. this example of i've been trying achieve. if statement part doesn't work @ present i've been having trouble working out solution. selection.wholestory nlines = selection.range.computestatistics(statistic:=wdstatisticparagraphs) selection.homekey unit:=wdstory while startnumber2 < nlines startnumber2 = startnumber2 + 1 selection.homekey unit:=wdline selection.movedown unit:=wdparagraph, count:=1, extend:=wdextend if selection.text = " / " selection.movedown unit:=wdline, count:=1 else: selection.delete unit:=wdcharacter, count:=1 end if loop this example of text it'll checking. need delete 2 & 4 , leave 1 & 3: back in black / acdc (3:54) -- tonight (2:44) -- lucy in sky diamonds / beatles (4:22) -- random song name (3:33) -- any appreciated. thanks comintern.

c# - Window workflow foundation 4.0 (WPF): How to change an activity location in a Flowchart workflow by code -

i use rehosting workflow designer ( https://msdn.microsoft.com/en-us/library/dd489419%28v=vs.100%29.aspx ) load flowchart workflow in application. flowchart flowchart = this.createflowchart();///create flowchart workflow workflowdesigner wd = new workflowdesigner(); wd.load(flowchart); how should change activity location in flowchart? this not trivial task. you need alter location of model item via view state service. wd.context.services.getservice<viewstateservice>().storeviewstatewithundo(modelitem, "shapelocation", new point(20,20)); have read of this article explains view state far better can.

Game Center Authentication Successful & Failure (iOS 7, Objective C) -

i've followed few tutorials & apple documentation on authenticating local player game center functionality using objective c. currently, our beta version has functioning game center authentication leaderboards. however, seems wrong authentication achievements, because none of our achievements coming across itunes connect. viewcontroller.m, first authentication occurs shown below: - (void)viewdidappear:(bool)animated { [super viewdidappear:animated]; [[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(showauthenticationviewcontroller) name:presentauthenticationviewcontroller object:nil]; [[gamekithelper sharedgamekithelper] authenticatelocalplayer]; } - (void)showauthenticationviewcontroller { gamekithelper *gamekithelper = [gamekithelper sharedgamekithelper]; uiviewcontroller *vc = self.view.window.rootviewcontroller; [vc presentviewcontroller: gamekithelper.authenticationviewcontroller animated:yes completion:nil]; } within gamekithelper

python - AttributeError: 'NoneType' object has no attribute 'sqlite_db' -

i don't understand how works. got code flaskr example. used work , doesn't. i getting following error: attributeerror: 'nonetype' object has no attribute 'sqlite_db' offending line: top.sqlite_db = sqlite_db from champnotif_v2 import app flask import _app_ctx_stack, g import sqlite3 def get_db(): """opens new database connection if there none yet current application context. """ top = _app_ctx_stack.top if not hasattr(top, 'sqlite_db'): sqlite_db = sqlite3.connect(app.config['database']) sqlite_db.row_factory = sqlite3.row top.sqlite_db = sqlite_db return top.sqlite_db __init__.py from flask import flask app = flask(__name__) app.config.from_pyfile('info.py') import champnotif_v2.views info.py database = "freechamp.db" it appears top none , not whatever expecting be. therefore _app_ctx_stack.top must none top being

java - Spring MVC - "IllegalArgumentException: Object reference not set to an instance of an object" when get SOAP response -

Image
i'm beginner in spring mvc. want response soap web service. error message. here source code. private static final string get_document_soap_action = "apvx:bus:reportgenerator:{1d81bedf-3894-45b2-99c9-95e50b1b9494}/document_get"; @autowired protected pathcentralwstemplatefactory webservicetemplatefactory; public documentgetresponse documentget(documentget request) { try { return (documentgetresponse) webservicetemplatefactory.getclient().marshalsendandreceive(request, getcallback(get_document_soap_action)); } catch (exception e) { throw new illegalargumentexception(e); } } pathcentralwstemplatefactoryimpl public pathcentralwstemplatefactoryimpl() throws soapexception { marshaller = new jaxb2marshaller(); messagefactory = new saajsoapmessagefactory(); messagefactory obj = messagefactory.newinstance(soapconstants.soap_1_1_protocol); if(obj != nu

c - fscanf and 2d array of integers -

disclaimer: i'm struggling beginner my assignment read integers input txt file 2d array. when used printf's debug/test fscanf isn't reading correct values file. can't figure out why. my code follows: void makearray(int scores[][cols], file *ifp){ int i=0, j=0, num, numrows = 7, numcols = 14; for(i = 0; < numrows; ++i){ for(j = 0; j < numcols; ++j){ fscanf(ifp, "%d", &num); num = scores[i][j]; } } } int main(){ int scorearray[rows][cols]; int i=0, j=0; file *ifp; ifp = fopen("scores.txt", "r"); makearray(scorearray, ifp); system("pause"); return 0; } you assigning num (what read file) value of array scores[i][j] doing backwards. following code read arbitrary number of spaces in between each number, until reaches end of file. void makearray(int scores[][cols], file *ifp) { int i=0, j=0, num, numrows = 7, numco

swift - Find out the view of the gesture has been set -

in secondviewcontroller have uitableview custom uitableviewcell have uipangesturerecognizer , want fail when othergesturerecognizer uipangesturerecognizer viewcontroller firstviewcontroller the uipangesturerecognizer of the cell set self , tried using gesturerecognizer: shouldrequirefailureofgesturerecognizer : override func gesturerecognizer(gesturerecognizer: uigesturerecognizer, shouldrequirefailureofgesturerecognizer othergesturerecognizer: uigesturerecognizer) -> bool { let view = othergesturerecognizer.view if let view as? firstviewcontroller.view { // doesn't work return true } return false } the question is, how can fail uipangesturerecognizer of uitableviewcell when gesture has been recognized firstviewcontroller? this may seem silly, seems me problem purely 1 of identification: gesture recognizer, othergesturerecognizer , particular gesture recognizer i'm worried , supposed yield to? occurs me 2 choices: you ha

angularjs - Angular: how to listen for response that you yourself don't make? -

in angular, there way listen response request don't make? i'm implementing file upload node.js, , i'm submitting form programmatically: html: <form enctype = "multipart/form-data" action = "/blah/fileupload" method = "post" id = "upload_file" > <input type="file" onchange="angular.element(this).scope().onfileselect(event)" name="bulk_uploads" /> </form> angular controller: $scope.onfileselect = function(event) { var form_elem = document.getelementbyid('upload_file'); form_elem.submit(); } the issue submitting form in fashion not return promise, , if submit form so: $http.post('/blah/fileupload', { files : event.target.files }) then there no way uploaded files once hits node server (e.g. req.files empty). is there way listen server's response 'blah/fileupload' submitting form programa