Posts

Showing posts from January, 2015

c# - LINQ Syntax for Selecting a Parameter to Be Copied -

i have code sort collection in linq in c#. want group housename sum on volumes, order collection, pass third parameter, pctvol, new sorted collection. doing wrong? know problem lies in pctvol = group.selecct(item => item.pctvol) line. var inbetween = this.groupby(item => item.housename) .select(group => new dataitem { housename = group.key, volume = group.sum(item => item.volume), pctvol = group.select(item => item.pctvol) }) .tolist(); observablecollection<dataitem> objsort = new observablecollection<dataitem>(inbetween.orderby(dataitem => dataitem.volume)); return objsort; what kind of value want pctvol have? code, looks dataitem.pctvol ienumerable containing pctvol values in group. if want single value, , pctvo...

windows vista - What is the simplest library to download files in C++ -

i want download files have full url address using c++ program, library best this? i wondering command like: system("download [url] [destination]"); or download(url,destination); i using windows, sorry forgot mention. have @ curl from curl site curl command line tool transferring data url syntax, supporting dict, file, >ftp, ftps, gopher, http, https, imap, imaps, ldap, ldaps, pop3, pop3s, rtmp, rtsp, scp, >sftp, smtp, smtps, telnet , tftp. curl supports ssl certificates, http post, http put, ftp uploading, http form based upload, proxies, cookies, user+password authentication (basic, digest, ntlm, negotiate, kerberos...), file transfer resume, proxy tunneling , busload >of other useful tricks. its best client side library available http://curl.haxx.se/

How do you modify Ionic colors in Meteor? -

i'm using official ionic package meteor. working directly ionic, there way write sass theme. how in meteor set up? add fourseven:scss package download repo https://github.com/nickw/meteor-ionic-scss-import , copy files /client/stylesheets/ionic in main scss file, import ionic.import.scss: @import "./ionic/ionic.import.scss"; overwrite colors in _variables.import.scss go have beer.

log4j - Logging user interactions with a program -

we have app , want log how user interacting it. example using pages expect them to. dont want log via app hard me information device. each page interacts webservices planning log interaction. i have had thoughts on * webservice being called add logging table database - problem here performance impact * use log4j async mode log these details. does have other suggestion on how this? im reading lean startup @ moment (very far) , sort of thing seems fundamental im wondering if there other tips this. thanks since no 1 answered couple months, thought couple pointers might you... use mobile analytics tools fabric.io google analytics mobile apps flurry amazon mobile analytics appsee have server record users access (that's approach you're considering). offload overhead, there couple tactics employ (mix 'n match will): use async mechanisms (async operations in server, such futures; log4j async mode; async databases; etc). use separate database. use...

javascript - Calculating BST time from Date object? -

i've reviewed few questions on similar topics already, none of them address calculating destination timezone, taking its dst (daylight savings time) account. i'm trying write simple widget displays live local time of specific timezone visiting page. timezone of interest bst ( what bst? ), if possible i'd love see generic implementation locale. here's attempt, using vanilla javascript: function getbst() { var date = new date(), utc = date.gettime() + date.gettimezoneoffset() * 60000, local = new date(utc), // gmt, not bst day = local.getdate(), mon = local.getmonth() + 1, year = local.getfullyear(), hour = local.gethours(), minute = ('0' + local.getminutes()).slice(-2), second = ('0' + local.getseconds()).slice(-2), suffix = hour < 12 ? 'am' : 'pm'; hour = (hour - 24) % 12 + 12; return mon + '/' + day + '/' + ye...

how to increase font size in Jqgrid(free version )/Free jqGrid -

need on how increase font size in jqgrid(free version )/free jqgrid effect in parts of grid. ( add,edit,delete, search,view etc) you can use following css change font-size of ( add, edit, delete, search, view). .ui-jqdialog { font-size: 20px !important; // use font size here }

osx - Running Multiple PHP SSH2 Script -

i have shop having 10 macs. current able shutdown/restart them remotely through php ssh2 function using code <?php include('net/ssh2.php'); $server = "hostname"; $username = "user"; $password = "pwd"; $command = "sudo shutdown -r now"; $ssh = new net_ssh2($server); if (!$ssh->login($username, $password)) { exit('login failed'); } echo $ssh->exec($command); echo "sucessfully restarted blah blah blah"; ?> but in order shutdown/restart 10 of terminals, have run 10 different script achieve that. there methods can connect multiple server , run same command? you store hostnames , credentials in multi-dimensional array . allow iterate through each item using foreach , execute required command on each host....

php - 403 nginx error - permissions denied -

i getting 403 forbidden error when try access domain using nginx. nginx logs are: [error] 13656#0: *4 "/var/www/example.com/www/index.php" forbidden (13: permission denied), client: 31.179.107.194, server: example.com, request: "get / http/1.1", host: "example.com" /var/www/ has recursive 777 permissions. sites-available config is: #http serve # server { listen 80; root /var/www/example.com/www/; index index.php index.html index.htm; server_name example.com; access_log /var/log/nginx/example.com.access.log combined buffer=1024k; error_log /var/log/nginx/example.com.error.log; client_max_body_size 128m; if (!-e $request_filename) { rewrite ^/([a-za-z0-9]+)/([a-za-z0-9]+)/$ /index.php?controller=$1&action=$2 last; } location ~ \.php$ { if (!-f $document_root/$fastcgi_script_name){ return 404; ...

Swift + Parse: Facebook login flow has "Back to Safari" in iOS9 -

now, know button in status bar new feature of ios 9, how prevent showing "back safari" on left of status bar once user has logged in facebook ? see other apps not having issue, how go ensuring that not happen? i can edit in code or more information if needed. want figure out. as reply long put in comment textfield: i used techniques in 1 of apps. in appdelegate write method example: func builduserinterface(){ let objectid:string? = nsuserdefaults.standarduserdefaults().stringforkey("user_id") if objectid != nil { let mainstoryboard:uistoryboard = uistoryboard(name: "main", bundle: nil) let singlemode:singlemodevc = mainstoryboard.instantiateviewcontrollerwithidentifier("singlemodevc") as! singlemodevc let mainpagenav = uinavigationcontroller(rootviewcontroller: singlemode) let appdelegate:appdelegate = uiapplication.sharedapplication().delegate as! appdelegate appdele...

r - Have same heat legend for two different heatmap plots, ggplot2, Rstudio -

Image
summary , info of problem i have 2 big datasets (as in matrix-layout keeping them df-s) 100 columns , 11640 rows. each row represent time hourly , each column specific depth. 2 data sets (named ucco2 , rcco2), time same depths differs (i.e. different specific depth). range of ucco2 0 12 , rcco2 0 ~30 please me create 1 legend both of them. manage create plots different legends (notice: i'm having them on separated windows) presenting data sets below summary of data after melt() command. i've after commad melt() added dates again (date_dates) , last column seen here. in plot later: x-axis is: "date_dates" --> hourly measurement time the y-axis is: "variable" --> depths , can seen in code further down, fill value column. dataset name: ucco2_m & rcco2_m summary(ucco2_m) date variable value 2014-10-26 02:00:00: 200 124 : 11640 min. : 1.2 ...

java - AdjustViewBounds works for android:src not android:backgound in imageview -

i've got imageview has different images source , background. when use adjustviewbounds , scaletype, works fine on image added in source not 1 in background. how can make work background image too? <imageview android:layout_width="199dp" android:layout_height="112dp" android:id="@+id/thumbnailsocial" android:src="@drawable/videopost" android:background="@drawable/coldplay" android:layout_marginstart="120dp" android:layout_marginleft="120dp" android:layout_margintop="110dp" android:adjustviewbounds="true" android:scaletype="centercrop" /> try divide background , src image 2 separate view. top view transparent background <relativelayout android:id="@+id/thumbnailsocial" android:layout_width="199dp" android:layout_height="112dp" android:l...

javascript - Getting Error TypeError: onOk is not a function -

i want create conformation dialog, conform before sending data database, getting typeerror: onok not function , onok() defined confirmservice , please check it. app.directive('confirmdialog', function(confirmservice) { return { restrict: 'a', scope: { eventhandler: '&ngclick' }, link: function(scope, element, attrs){ element.unbind("click"); element.bind("click", function(e) { confirmservice.open(attrs.confirm, scope.eventhandler, 'confirm_dialog'); }); } } }); app.service('confirmservice', function($modal) { var service = {}; service.open = function (text, onok, dialog_type) { var modalinstance = $modal.open({ templateurl: 'templates/dialog.html', controller: 'confirmctrl', resolve: { text: function () { return...

junit4 - JUnit behaviour with static final variable of usual Java class -

assuming, want use predefined static final list instance(s) holder of "configuration" test. list, use static {} block values added instances: public class config{ ... public static final list<object[]> config = new arraylist<>(); static{ //object[] pairs her`e config.add(new object[] { ... whatever}); config.add(new object[] { ... whatever}); config.add(new object[] { ... whatever}); } } ... //then test class: @runwith(parameterized.class) public class generaltemplate{ ... @parameters(name = "{index}: source: {0} target: {1}") public static collection<object[]> config() { return config.config; } } i use instances in junit test class. guess, because of definitions + annotations test runs mistake "no tests have been found"? i think @test annotation missing templates. compiler complaining "no tests have been found" in not able find test methods junit 4 @test annotation in test clas...

c# - custom button in wpf with path as content -

how can create custom button control takes argument of path in button constructor can reuse control throughout projects? this how create buttons.... <grid> <button style="{dynamicresource buttonpathstyle}" width="24" height="24"> <path fill="gray" data="m50,50 l100,100 l150,50" stretch="uniform" /> </button> </grid> however create custom button create them along custom style sheet <grid> <pathbutton width="24" height="24" data="m50,50 l100,100 l150,50" stretch="uniform" /> </grid> if knows of resources of can whip quick example it'd appreciated. assume creating button pretty simple custom control. and custom control mean compile dll can share. code behind: public class pathbutton : button { public static dependencyproperty dataproperty = dependenc...

dictionary - How do I add different numbers in multiple lines in python? -

so have file 9 different phone numbers. there line every call, , duration. want add duration of calls , match them own phone number. here part of file: 7803214567;94 7801234567;602 7801234567;910 7808765432;925 7801234567;631 the first being phone number , second being duration in seconds. more clear, example: 7801234567 , want add 602 , 910 , 631 , match own phone number 7801234567 . it seems want count total number of minutes each unique phone number. you use counter : from collections import counter c = counter() open("path/to/file.txt", 'r') f: line in f: k, v = line.split(";") c += counter({k: int(v)}) >>> print(c) counter({'7801234567': 2143, '7808765432': 925, '7803214567': 94})

sinatra - Rack::Reloader not picking up changes -

consider config.ru file: require 'sinatra' use rack::reloader, 0 '/' 'hi' end run sinatra::application i start command line thin start . application runs , shows hi when hit localhost:3000 . if change hi hello , save file, , reload page, change not appear: page still says hi . why rack::reloader not work in case? can change make work? see here detailed explanation of what's happening. essentialy everytime file changed, rack::reloader re-requires it. unfortunately sinatra, if redefine route second time (which happens when re-require), sinatra ignores new definition since get '/' end defined! what need reset defined routes have well: # inside app.rb require 'sinatra' require 'rack' configure :development sinatra::application.reset! use rack::reloader end '/' 'hi' end note takes few seconds (5s on machine) changes reloaded , recommend take look @ alternatives here ...

oracle - I have a SQL with nvl and case statement that has to be converted into Informatica expression -

i have following sql statement: nvl(w_sales_invoice_line_fs.invoiced_qty, case nvl(w_sales_invoice_line_fs.net_amt,0) when 0 w_sales_invoice_line_fs.invoiced_qty else -1 end) could me converting informatica expression isnull , decode(). tried following , gives out parsing errors: iif(isnull(ext_invoiced_qty), decode(ext_net_amount, iif(isnull(ext_net_amount),0,ext_net_amount) =0, ext_invoiced_qty, -1), ext_invoiced_qty) to note: w_sales_invoice_line_fs.invoiced_qty = ext_invoiced_qty w_sales_invoice_line_fs.net_amt = ext_net_amount your sql statement little bit strange. let's analyse it: w_sales_invoice_line_fs.invoiced_qty != null => w_sales_invoice_line_fs.invoiced_qty w_sales_invoice_line_fs.invoiced_qty = null , w_sales_invoice_line_fs.net_amt = null => w_sales_invoice_line_fs.invoiced_qty (but it's null) w_sales_invoice_line_fs.invoiced_qty = null , w_sales_invoice_line_fs.net_amt != null = > -1 it seems need have same output: ...

python - What happens when a coroutine raises an exception? -

i'm not sure happens in following piece of code: def coroutine(): lst = [] try: while true: item = (yield lst) if item == 3: raise valueerror print('append {}'.format(item)) lst.append(item) except generatorexit: print('generatorexit') crt = coroutine() next(crt) print(crt.send(1)) print(crt.send(2)) try: print(crt.send(3)) except valueerror: pass print(crt.send(4)) this outputs: append 1 [1] append 2 [1, 2] traceback (most recent call last): file "d:\documents , settings\brecht\desktop\crt.py", line 25, in <module> print(crt.send(4)) stopiteration when stepping through code debugger, on raise valueerror , execution jumps except generatorexit: , body of except clause not executed ('generatorexit' not printed). why not? aside that, don't suppose can in way resume coroutine after has thrown exception? there particular...

r - How to change label format, distance between main text and plot, and put the number on the each parts? -

i plot pie chart questions on how modify it. code library(plotrix) df <- c(29, 29, 36,26) lbls <- c("blue(29)","gold(29)","green(36)","orange(26)") labelco <- c('blue','yellow','springgreen3','darkorange1') pie3d(df, main="yi li's color", labels=lbls, radius=0.5, col = labelco ,labelrad=1.7, explode=0.1) and can pie chart below: pie chart made is can teach me: how change label format(maybe choose times new roman), distance between main text , plot, , put number on each parts ? thank much. best regards,

c - Why is scanf of a string saved to str while for the int it is being sent to the pointer of i? -

i have code: char str [80]; int i; printf ("enter family name: "); scanf ("%79s",str); printf ("enter age: "); scanf ("%d",&i); why scanf() of string saved str while int being sent pointer of i ? scanf needs passed address of variable in order modify it. when passing array (a char array, in case) function, array decays pointer first element. so passing str %s specifier functionally same passing in &str[0] . this works char * points dynamically allocated memory: char *str = malloc(80); scanf ("%79s",str);

ios - Change genstrings generated key (Object ID) extracted from Storyboard for localization? -

Image
i pressed localize... button on storyboard generate strings file storyboard may localized other languages. in 1 strings file corresponds storyboard, see this: "orz-58-mzb.text" = "we looking bright, energetic individuals represent us."; i'm wondering if can change key field orz-58-mzb.text more meaning such faq.answer.23.text can used in other platforms android? noticed in storyboard editor, object id cannot changed (see screenshot). there other way change key? there's no way change key, can add comment in notes field on same ui. string gets passed on translator via generated xliff, , best way communicate meaning behind string want translated.

PHP Array of DateTime seems skewed -

i trying create function create array of datetime(s). dates want every saturday in given year. i have function when values stored in array, begin second saturday of year , extend first saturday of following year. note following displays list of saturdays generated function , after couple of blank lines displays saturdays store in array. <?php define ('sql','y-m-d'); define ('br','<br/>'); function allsaturdays ($year){ $endofyear = "$year-12-31"; $interval = new dateinterval("p7d"); $year--; $workingdate = "$year-12-31"; $workingdate = strtotime ($workingdate); $workingdate = strtotime ("next saturday",$workingdate); $workingdate = date ("y-m-d",$workingdate); $workingdate = new datetime ($workingdate); $result[] = new datetime; while ($workingdate->format(sql) <= $endofyear ) { $result[] = $workingdate; echo $w...

oracle - Java Recon Job - Fastest and generic solution -

currently, running application in rds , in process of moving mongodb. now, have synch job syncs data oracle mongo , when row gets added/modified or deleted. write happening on oracle. planning come recon job compares source , target data. trying full recon fetches data oracle , then compares mongodb find descrepencies. i planning below approach. note, oracle db size in terabytes. 1) first thousand rows oracle table a. ( simple jdbc results approach ) 2) each entry, create map of key values. ( map) 3) corresponding data mongodb , convert data based on oracle format. 4) each entry, create map of key values. 5) compare these 2 map find if same. ( oracle map equals mongoldb map ) 6) repeat same next rows .... but, approach taking time using multi threading. not have idea on big data, open new ideas. is there other way or technology can used here parallel processing. note, there tables mapped straight forward b/w oracle , mongo. few tables in denormalized form ...

matplotlib - Python modules to plot game of life script -

i wanted know modules recommend plotting lists of coordinates on x-y plane are. purpose implement game of life; i've tried matplotlib.pyplot i've got issues axes ratio , in general doesn't seem best way plot sort of animation. main idea in script plot world in cells live, tick given time.sleep. import matplotlib.pyplot plt class cell: #cell class, coordinates , on-off state def __init__(self,x=0,y=0,state=0): self.state=state self.x=x self.y=y self.coord=[self.x,self.y] def __repr__(self): if self.state: return "*" else: return " " #methods turn on , off cells: def turn_on(self): self.state=1 return self def turn_off(self): self.state=0 return self class mondo: #the world in cells live: def __init__(self,width=10,height=30,starting_cells=[]): self.width=width self.height=height self...

python - Best way to store emails from a landing page on google app engine? -

i have landing page set , have html text box (with error checking valid emails) put submit button. using ndb store different entities. what i'm looking best way store email person enters. hundreds or thousands of emails entered, there shouldn't duplicates, , want use of emails send large news update entered in emails. what best way store email data these contraints: fast duplicate checking quick callback sending emails en masse create email entity, , use email address entities key. this prevent duplicates. fetching of email addresses can efficient need query kind keys query, , use map_async process emails. in addition use these entities store progress of email, maybe provide audit trail. to increase speed @ time of emailing, periodically build cached lists of emails, either in datastore or stored in blob storage.

sql - Aplication Deadlocks (ERROR 1213 (40001)) when running an alter table command -

when i'm running following alter table, application still live hitting deadlocks: error 1213 (40001) @ line 2: deadlock found when trying lock; try restarting transaction query: alter table `comm` add column `thumb_url` varchar(256) null default null comment '' after `search_index_version`, add column `thumb_src_url` varchar(256) null default null comment '', lock = none; when read mysql 5.6 documentation shouldn't lock, or wrong? version: server version: 5.6.27-76.0-56-log percona xtradb cluster (gpl), release rel76.0, revision 2a6d4e5, wsrep version 25.13, wsrep_25.13 pointers here? thanks in advance assistance! if try add column table beeing continuously used application, can meet deadlock - means process waiting other process finish, , other process waiting process finish. every select/insert/update make kind of lock on table. you can try turning off application, make database changes , turning on. you can try lock table moment. gu...

css - Easily create an animated glow -

Image
i created image: using photoshop, had make around 50 layers manually, , create gif out of it. there easier way automatically create animated glow similar this? you can use css animation. here example using vanilla div container, can give background image: div { width: 200px; height: 200px; border-radius: 100px; background-color: #ccc; animation: glow 1s infinite alternate; } @keyframes glow { { box-shadow: 0 0 10px -10px #aef4af; } { box-shadow: 0 0 10px 10px #aef4af; } } <div></div>

javascript - clearInterval not clearing the interval -

thanks response. have solved problem. did see list of callback functions. after work managed shoot intervals, first shot after 1 second. 1 - problem - if call function in setinterval imidiatly , set interval - shoots rapidly. 2 - fixed problem making settimeout set bool value hasshooted false after 1 second , if value false can shoot. in function set true. 3 - realized need last function set timeout , not setinterval @ all. var playermanager = (function(parent){ 'use strict'; var bulletpossleft, bulletposstop, fire_speed = 1000, hasshot = false; playermanager.prototype = object.create(parent.prototype); function playermanager() { parent.call(this); this.moveleft= false; this.moveright= false; this.moveforward= false; this.moveback= false; this.isshooting= false; this.bulletmanager = new bulletmanager(); } playermanager.prototype.ongameloop = function(obj) { if (this.isshooting) { bulletpossleft = obj.posi...

sql - Adding identity column - order of ID -

please see ddl below: create table #test (name varchar(10),dateofbirth datetime) insert #test values ('ian', '1976-09-08') insert #test values ('maria', '1976-09-08') i realise poor design choice not have primary key. want add new identity column this: alter table #test add id int identity this works expect i.e. ian has id of 1 , maria has id of 2. there 10 million rows in table. can assume id order respect order entered table? e.g. ian entered first has id of 1. anne millionth row entered id 1,000,000. the order in identity values assigned existing rows undefined. heap example, sql server assign values in physical order of files/pages/slots used store rows. if matches order of insertion, happenstance , should not relied on. space allocation , reuse can cause physical order of data differ original order of insertion may database multiple files. if table has clustered index, values assigned in order of clustered index key,...

scala - Extending Enum in scalaz and implicit parameters with subtypes -

this question has answer here: typeclasses , inheritance in scalaz 1 answer i playing scalaz , thought extend enum type class make myself understand scalaz better. wrote this: sealed abstract trait counter case object first extends counter case object second extends counter case object third extends counter implicit val enumcounter: enum[counter] = new enum[counter] { override def succ(a: counter): counter = match { case first => second case second => third case third => first } override def pred(a: counter): counter = match { case first => third case second => first case third => second } override def order(x: counter, y: counter): ordering = { val map = map[counter, int](first -> 0, second -> 1, third -> 2) implicitly[or...

java - Is it appropriate to use a series of lambda functions to define class functionality? -

in recent discussion, friend , have disagreed on following use of lambda functions define class functionality. when creating object dynamic values, should dynamic values passed using lambdas, or provided using overriden methods in custom subclass? consider following example, in goal have custom label component dynamic text , icon traits. label must have methods gettext() , geticon() . following 2 examples: 1 using multiple lambdas, , 1 defining subclass. lambda approach: class label { private supplier<string> text; private supplier<image> icon; public label(supplier<string> text, supplier<image> icon) { this.text = text; this.icon = icon; } public string gettext() { return text.get(); } public image geticon() { return icon.get(); } } use: label timelabel = new label( () -> system.currenttimemillis(), () -> clock_image ); subclass approach: class label { priv...

javascript - Return '0' or 0 on success from AJAX call? -

i have series of nested ajax calls validate each element of form that's being submitted. each 1 checks result of data variable created php file that's called. if php routine not successful, routine echoes error message captured ajax routine, in turn presented in alert box user see form can corrected necessary , resubmitted. if php routine successful, echo 0 , next ajax validation script called. once of form elements validate form processed. my question has our dear friends != operator , !== operator, regards efficiency of operation performance (i understand difference in how function). currently, routines structured this: in jquery/ajax: $.get('data_check.php', { id: $('#id').val() }, function(data) { if (data != 0) { alert(data); } else { [...next ajax call...] and @ end of data_check.php (and such php routines called parent ajax routine): if (!$success) { echo $error_message; exit; } else { echo 0; ex...

machine learning - Explanation for Coordinate Descent and Subgradient -

Image
how easy explanation of coordinate descent , subgradient solution in context of lasso. an intuitive explanation followed proof helpful. suppose have multivariate function f(w) k number of variables/parameters w ( w_1, w_2, w_3, ..., w_k ). parameters knobs , goal change these knobs in way f minimized function f . coordinate descent greedy method sense on each iteration change values of parameters w_i minimize f . easy implement , gradient descent guaranteed minimize f on each iteration , reach local minima. picture borrowed internet through bing image search as shown in picture above, function f has 2 parameters x , y . on each iteration either both of parameters changed fixed value c , value of function evaluated @ new point. if value higher , goal minimize function, change reversed selected parameter. same procedure done second parameter. 1 iteration of algorithm. an advantage of using coordinate descent in problems computing gradient of function exp...

Tensorflow Incompatable Shapes Error in Tutorial -

i've been trying create convolutional network tensorflow tutorial , i've been having trouble. reason, i'm getting errors size of y_conv 4x larger size of y_, , have no idea why. found this question , appears different problem mine, though looks similar. to clear, batch size in below code 50, error it's coming is tensorflow.python.framework.errors.invalidargumenterror: incompatible shapes: [200] vs. [50] and when change batch size 10, get tensorflow.python.framework.errors.invalidargumenterror: incompatible shapes: [40] vs. [10] so it's related batch size somehow, can't figure out. can tell me what's wrong code? it's pretty straight tutorial linked above. from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('mnist_data', one_hot=true) import tensorflow tf sess = tf.interactivesession() def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.var...

Pass javascript variables into PHP use AJAX -

i have 1 javascript variable , want pass php file. search , find use ajax don't know how use ! here code . wrong ? .js file : var message1 = message.message; var jq = document.createelement('script'); jq.src = "https://code.jquery.com/jquery-1.10.2.js"; document.queryselector('head').appendchild(jq); $(document).ready(function() { $.ajax({ type: "post", url: 'http://localhost/a.php', data: { newmessages : message1 }, success: function(data) { alert("success!"); } }); }); my a.php file : <?php if(isset($_post['newmessages'])) { $uid = $_post['newmessages']; echo $uid; } ?> listen onload event of asynchronously loa...

javascript - Are AWS server-side TemporaryCredentials usable for client-side S3 upload? -

using client-side version of aws javascript sdk v2.2.29 (e.g. bower aws-sdk-js ) possible (though unacceptable because exposes real aws credentials client): var region = 'us-east-1', accesskeyid = 'az12341234', secretaccesskey = 'abcde1fghij2klmnopqr3tuvwx4yz'; var creds = new aws.credentials(accesskeyid, secretaccesskey); creds.get(function() { s3location = new aws.s3({ region: my.region, credentials: creds }); ready(); // presents upload form, binds events, etc.. }); the dream split process 2 parts, 1 secure server-side , following client-side. part 1. use nodejs server-side version of aws javascript sdk (e.g. aws-sdk ) this: var creds = new aws.temporarycredentials(accesskeyid, secretaccesskey); creds.get(function() { var aws = { accesskeyid: creds.accesskeyid, sessiontoken: creds.sessiontoken, region: my.region, }; // e.g. makes aws var available client res.render('form', { aws: aws })...

How should I go about finding a string within two chars in c++? -

hello been trying find way of finding string of characters within 2 characters. how should go doing in c++? sdfgkjr$joeisawesome$sdfeids -> joeisawesome edit: other answer looking if string exist within string. i'm looking string within 2 characters , outputting sting within 2 chars. thank looking pox. okay, when 2 characters, i'm assuming referring delimiters. in case have use string.find() find position of delimiters. after finding positions of delimiters, can can use string.substr(index1,index2-index1) return substring. example: #include <iostream> #include <string> int main() { std::size_t index1,index2; std::string mystring = "sdfgkjr$joeisawesome$sdfeids"; std::string sub= ""; index1 = mystring.find('$'); //string::npos -1 if unaware if(index1!=std::string::npos&& index1<mystring.length()-1) index2=mystring.find('$',index1+1); if(index2!=std::string:...

javascript - Linking to specific twitter bootstrap tabs from URL on same page -

i'm javascript noob , i'm wondering how implement answer question? twitter bootstrap tabs: go specific tab on page reload or hyperlink i want use code on same page tabs located.... <script type="text/javascript"> // javascript enable link tab var url = document.location.tostring(); if (url.match('#')) { $('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ; } // change hash page-reload $('.nav-tabs a').on('shown', function (e) { window.location.hash = e.target.hash; }) </script> where inside page containing tabs should plugg in. again, sorry being such noob. try wrapping code in $(document).ready() function $(document).ready(function() { //your code here... }); what have above won't work dom won't ready when runs. using $(document).ready() function delay execution until dom has loaded. can go pretty anywhere in pa...

elixir - Ecto association to more than one schemes -

let's have these schemas: defmodule sample.post use ecto.schema schema "post" field :title has_many :comments, sample.comment end end defmodule sample.user use ecto.schema schema "user" field :name has_many :comments, sample.comment end end defmodule sample.comment use ecto.schema schema "comment" field :text belongs_to :post, sample.post belongs_to :user, sample.user end end my questions how can use ecto.build_assoc save comment? iex> post = repo.get(post, 13) %post{id: 13, title: "foo"} iex> comment = ecto.build_assoc(post, :comments) %comment{id: nil, post_id: 13, user_id: nil} so far it's ok, need use same function set user_id in comment struct, since return value of build_assoc comment struct, can not use same function iex> user = repo.get(user, 1) %user{id: 1, name: "bar"} iex> ecto.build_assoc(user, :comment, comment) ** (undefinedfunctione...

javascript - How to specify location of image on hover -

i have code display image directly on hyperlinks. unfortunately, if image populates directly on cursor, there seems conflict: website you can see code works small images. large images flicker. how can images stop flickering. think location of displayed image needs away hyperlink. jquery(document).ready(function() { jquery("<div id='player-image-hover'></div>").appendto("body").css("position", "absolute").css("z-index", "1000").css("padding", "2px").css("backgroundcolor", "#666"); jquery("a[href^='http://thepoolscene.com/player-profile']").each(function() { var title = jquery(this).attr("title"); title = title.tolowercase(); title = ucwords(title); var url = "http://" + window.location.host + "/wp-content/gallery/playerphotos/" + escape(title) + ".jp...

css - Change table class in mobile view? -

i using bootstrap , table have table-condensed class applied in mobile view, , table-responsive class applied above mobile size. what best approach that? there way in sass ? i have stumbled across ' extend ' in sass don't think quite need when tried implement it, couldn't use within media query, outside of media query worked ok thank :) (i working on trying include code getting error) you can use jquery resize function example $( window ).resize(function() { var screenwidth = $(document).width(); if(screewidth <= 480) { $("#table").removeclass("table-responsive"); $("#table").addclass("table-condensed"); } else { $("#table").removeclass("table-condensed"); $("#table").addclass("table-responsive"); } });

javascript - codeigniter csrf not work in select option -

i want make step input select option, in case, make 3 step, when select first option show next option 2, option 3. using ajax , set $config['csrf_protection'] = true; in codeigniter config file. in first select option (#kategori) work , show next value in second select option, in step 3 select option (#sub1 or secon function of javascript) n't work. thank before. this view: <?php echo form_open_multipart('',array('class'=>'form-horizontal'));?> <?php echo form_label('kategori','id_kategori',array('class'=>'col-sm-2 control-label'));?> <select id="kategori" name="id_kategori"> <option value=""></option> <?php foreach($kategori $kategori_umum) { echo '<option value='.$kategori_umum->id.'>'.$kategori_umum->nama_kategori.'</option>'; } ?> </select> <select i...

ios - what is the relation between CVBuffer and CVImageBuffer -

if check doc apple https://developer.apple.com/library/tvos/documentation/quartzcore/reference/cvbufferref/index.html#//apple_ref/c/tdef/cvbufferref in second line , says : "a cvbuffer object can hold video, audio, or possibly other type of data. can use cvbuffer programming interface on core video buffer." means can hold images . if yes , why have cvimagebuffer. i have done work on generating images video using avassetimagegenerator.now want merge frames make video.so,i have started reading this. my current status: 1.well right know need use avassetwriter. 2.then need provide input using avassetwriterinput. 3.i need use cv , cg classes. so please me know reason using cvimagebuffer if have cvbuffer.i know cvbuffer abstract cvimagebuffer doesn't inherit cvbuffer.this bamboozles me more. cvimagebuffer does inherit cvbuffer , in "simulated object orientation in c" way. is, if know cvbuffer 's type of subclass, can safely cast type, e...

jsp - Struts 2 s:if with getText -

i want see if message key presented in message bundles. tried below none of them worked: <s:if test=" gettext('site.message') == 'site.message'"> <s:if test=" gettext('site.message').equals('site.message')"> <s:if test=" %{gettext('site.message').equals('site.message')}"> but workaround works fine: <s:text name="site.message" var="test"/> <s:if test=" #test=='site.message'"> please consider: <s:text name="site.message"/> </s:if> so possible omit #test variable , works in s:if it's possible if use body of <s:text> default message instead of body of <s:if> tag. docs page if named message not found in property file, the body of tag used default message . if no body used, stack searched, , if value returned, written output. if no value found on stack, key of message written out....

c - Reloading a Stopped process in xv6 OS -

want write program can save process's state when exits in file , program reload process's state , run left in xv6 os. keeping processes' state when changing among processes in scheduler. how can reload process state cpu , run ? know should run in kernel level mode , can adopt scheduler() , swtch() function in proc.c file.

C pointers and malloc confusion between &str,str -

im beginner in c,in following code can output value of &str , str when cast integer.?? int main() { char *str; /* initial memory allocation */ str = (char *) malloc(15); strcpy(str, "hello"); printf("string = %s, address = %d ,val=%d\n", str, &str,str); free(str); return(0); } this output got: string = hello, address = -1407247144 ,val=22335504

jquery - Is it possible to have a remote: true AJAX partial load into a bootstrap modal on desktop, but as a slide-in-from-the-side form on mobile devices? -

i have rails app working on desktop, ux on phone quite bad, bootstrap modals being loaded page. create new objects load form bootstrap modal using ajax , pop view on page. as part of redesign make mobile user experience better considering using responds_to block design different layout mobile users, , dynamically loaded rails forms (it's data entry) render single page , slide in right, slide out once user submits action. is possible? there suitable gem available might make easier? i considering using responds_to block design different layout mobile users don't. you can use same layout, set css styling different. responsive you're best using media-queries . lots of people confused / overwhelmed "responsive" interfaces; reality simple - use logic assign classes on per-platform basis, else should handled media queries. 99% of styling, logic & flow remains same. in case, believe bootstrap 's modals responsive (ie work on phon...