Posts

Showing posts from February, 2014

Ajax success issue with React and Rails -

i've got form trying handle react. ajax method in handlesubmit function: $.ajax({ data: formdata, datatype: "json", url: '/requests', type: "post", success: function(data, status, xhr) { console.log('show here on response'); this.setstate({ formsubmitted: true }); } }); when click on submit, can see post request go through , server responds 200. success callback never entered, don't see console message. my rails controller's action simple: return render nothing: true, status: 200 if request.xhr? the log server response includes: completed 200 ok in 11ms (views: 2.5ms | activerecord: 2.6ms) however when move stuff success callback in ajax request complete callback see error in console: uncaught typeerror: this.setstate not function you seeing error, because this behaves differently inside $.ajax() 's success callback, because jquery uses internally. suppose executing follo...

c# - Identity Provider, MVC,override PasswordSignInAsync, custom storage provider - CRM -

actually l´m building website in mvc5, , l´m using .net identity. while connecting customstorageprovider(just usertable) crm, l´m lagged problem: when l trying logged in: var result = await signinmanager.passwordsigninasync(model.email, model.password, model.rememberme, shouldlockout: false); // <-- here failure - different hashes + salt in crm switch (result) { ... } passwordsigninasync logged user email , password, l´m using in crm different hashes , need edit behaviour of function, getting idea, how ? answers create custom implementation of ipasswordhasher. public class mycustompasswordhasher : ipasswordhasher and custom usermanager custom user class, if need: public class myacessousermanager : usermanager so put setting on myacessousermanager this.passwordhasher = new mycustompasswordhasher(); see: http://aspnetguru.com/customize-authentication-to-your-own-set-of-tables-in-asp-net-mvc-5/

c# - MVC Hidden field via HTML Helper in Form Post issue -

i have issue when using hidden field in mvc form post. when hidden field generated via html helper won't preserve it's value during postback. when using html tag, works. unfortunately 1 has taken me whole day work out work around. here i'm doing... (excuse spelling, re-typed code so): view model public class someviewmodel { public int myproperty1 { get; set; } public int myproperty2 { get; set; } public int myproperty3 { get; set; } } post method [httppost] [validateantiforgerytoken] public actionresult myactionmethod(someviewmodel someviewmodel, string command) { ... ... // someviewmodel.myproperty1 ... ... } view @using (html.beginform("myactionmethod", "somecontroller", formmethod.post, new { @class = "form-horizontal", role = "form" })) { @html.antiforgerytoken() @html.hiddenfor(m => m.myproperty1) <div class="col-md-2"> <input type="hidden...

ios - Multiple UIAlertControllers to show one after the other in Swift -

i have set alertcontroller app, way works if section score higher 10, ui alert. now problem if have 2 or 3 sections on 10, first uialert show, id see of them 1 after other (if sutuation happens here code : func sectionalert () { var message1 = nslocalizedstring("section 1 score ", comment: ""); message1 += "\(section1score)"; message1 += nslocalizedstring(" please review before continuing", comment: "1"); var message2 = nslocalizedstring("section 2 score ", comment: ""); message2 += "\(section2score)"; message2 += nslocalizedstring(" please review before continuing", comment: "2"); var message3 = nslocalizedstring("section 3 score ", comment: ""); message3 += "\(section3score)"; message3 += nslocalizedstring(" please review before continuing", comment: "3"); if (section1score >= 10)...

Wordpress Custom Post Type Search -

Image
i have wp installation menu/restaurant theme adds custom post type "food". "food" has title , excerpt field doesn't have regular "content" field. seems default wp search facility search in title , content fields not excerpt field. i've tried several plugins either add content field custom post type or search in excerpt field title field i've had no success. am missing obvious? many thanks we've had lot of success using relevanssi plugin altering wordpress's search functionality. can have wordpress index custom fields, excerpts, , other things, , add more or less weight them in search results. in excerpt's settings, check box shown in screenshot below: and click bottom rebuild search index.

Is there a Way to search several Youtube-Channels in one API-Call -

i'm wondering if there way newest video-items of several youtube-channels? youtube killed collection-feature last month , i'm thinking writing own app organizing 400+ youtube-subscription. would great, if there function search new videos on several channels 1 api-call. seems me youtube.search.list suppport searching in 1 channel-id. any ideas? if there no way, i'm thinking using youtube-push-notifications , caching channel-items in own db, simpler have no own sever running, using youtube-api clientside. thanks help! yes, there no api call search through multiple channels. best solution use push notifications latest videos.

sql server - Function for word by word string comparison in T-SQL -

i need write sql server function take in 2 fields , perform logical operation in manner - take first field value, split words - make sure of these words exist in second field. for example: first field of le chien , second le chien joue avec la balle function return true in case, since words first 1 in second. i use substring : substring(field1, 0, 5)=substring(field2, 0,5) but in cases not work; if have field1 la maison (1) , field2 la maison (2) substring(field1, 0, 5)=substring(field2, 0,5) return true though strings not match. increasing number of characters in cases work, not in others. boils down writing function split first string separate words , ensure of them exist in second string. can me build function or point me in right direction? i'd appreciate help you can use charindex if want see if value1 exists in value2. https://msdn.microsoft.com/en-us/library/ms186323.aspx if charindex(value1, value2) > 0 --found if words in val...

cordova - Architecture of an app when using CouchDB/PouchDB -

i wondering how architecture should when using pouchdb local storage in mobile app instead of localstorage . at moment used cache app's data localstorage , when needed perform api call backend request or post data. backend holding logic. such as: does user has correct permission/role action? any other logic needed check if action can done all data stored relational database. have been reading nosql databases , in particular couchdb , pouchdb . wondering how architecture like? 3 questions arise @ point me: if have multiple users there own authentication, how can make sure users access data? , still have 1 database on server end? pouchdb on client side can in sync remote pouchdb . when application build javascript how make sure people not inserting data pouchdb 'hacking' client-side javascript? would use of backend gone in these kinds of setups? , if want have api 3rd party , put example sails.js backend around couchdb ? pouchdb maintainer he...

Bash alias to script generating shebang text -

how create alias short code snippet generates shebang ( #!/bin/bash ) text? i'm looking like: alias createconfiger='echo -e "#!/bin/bash\necho configvalue" > printconfig.sh' you need in 2 steps, , apparently use single-quotes well: tempvar='#!/bin/bash\necho configvalue' alias createconfiger='echo -e "$tempvar" > printconfig.sh'

jquery - How can I get button events in the following code? -

i new jquery , don't know how events when press button on following code. please me. <div class="key"> <div class="buttonwrapper"> <span data-i18n="keypad.one" class="button i18n"></span> </div> </div> first want capture element want use, using $() . in case: $(".button") then after have gotten element using $() want bind event it. in case .click() event: $(".button").click(function(){ // insert want happen when clicks button here }); to learn more jquery, recommend looking @ api . more information .click() event click here . learn more events in general click here .

javascript - ES6 classes with Angular 1 DI issue with $inject -

class foo { constructor(dep1) { } } foo.$inject = ['dependency1'] i know can di in angular /w es6 classes. however, need pass constructor foo (a config object). eluding me because knowledge, di parameters go first. essentially, want do let foo = new foo(config); //config defined above but still have benefits of injectable dependencies in class. solution 1: let angular = window.angular; class foo{ constructor(config){ let injector = angular.injector(); let dep1 = injector.get('dependency1'); this.prop1 = config.prop; this.prop2 = dep1.get(); } } solution 2: //assuming es6 modules, export dependency module import dependency 'path'; class foo{ constructor(config){ this.prop1 = config.prop; this.prop2 = dependency.get(); } }

android - CSS Media Query Landscape - Keyboard Issue -

i tried in mobile page @media screen , (orientation:landscape) { /* landscape based css here */ } it's broken on keyboard opened. after tried; @media screen , (min-aspect-ratio: 13/9) { /* landscape */ } tested , works on; nexus 5, iphone 4, iphone 6, iphone 6+, samsung note 4, samsung s3, samsung s4, samsung s5, still broken on when keyboard opened on nexus 4 . i couldn't find global solution css. appriciated. thanks i didn't came , straight answer hacked out nexus 4. @media screen , (width: 384px) , (height:233px) { /*my landscape div sets out display:none on nexus 4*/ }

javascript - Append a new row to a table using jQuery -

this question has answer here: add table row in jquery 30 answers i'm using following code trying append new row jquery it's not working. $('#search-results > tbody').append('<tr><td data-th="name">test</td><td data-th="email">test@test.com</td><td data-th="phone number">07777777777</td><td data-th="car reg.">ocf83or</td><td data-th="time">1pm</td></tr>'); my table setup so: <table class="view-bookings-table mobile-optimised hidden" id="search-results"> <thead> <tr> <th scope="col">name</th> <th scope="col">email</th> <th scope="col">phone number</th> ...

oauth - Mule Facebook Null Payload -

asked evaluate buying mulesoft - , produce demo connects facebook. following 2 samples here: https://github.com/mulesoft/facebook-connector/blob/master/doc/sample.md , http://blogs.mulesoft.com/mule-school-integration-with-social-media-part-ii-%e2%80%93-facebook/ ran problem first sample - wouldn't compile because endpoint http connector same facebook connector. did research , made changes, error below , can't find else experienced same: unable fetch access token. message payload of type: nullpayload - on callback page. has experienced this? here code: <http:listener-config name="http_listener_configuration" host="localhost" port="8099" doc:name="http listener configuration"/> <facebook:config-with-oauth name="facebook-config" consumerkey="..." consumersecret="..." scope="user_photos" doc:name="facebook"> <facebook:oauth-callback-config domain=...

xml - How to pick all the firsts occurrences of data when iterating through xsl:for-each -

in xslt want iterate through 1 node of each country. dont know how many countries in xml... with file: <catalog> <cd> <title>empire burlesque</title> <country>usa</country> </cd> <cd> <title>hide heart</title> <country>uk</country> </cd> <cd> <title>greatest hits</title> <country>usa</country> </cd> <cd> <title>greatest hits</title> <country>uk</country> </cd> <cd> <title>greatest hits</title> <country>fin</country> </cd> <cd> <title>super greatest hits</title> <country>spa</country> </cd> <cd> <title>greatest hits2</title> <country>fin</country> </c...

git - Push remote specific branches with different names -

lets have origin branch called master checked out by; >> git checkout master switched branch 'master' branch up-to-date 'origin/master' now add remote fork branch called master checked out by; >> git checkout -b fork-master fork/master switched branch 'fork-master' branch up-to-date 'fork/master' this knows remote given branch belongs to, , references correct origin. lets want push origin i'd this; >> git push which update origin/master changes ( duh ). below 2 examples of pushes; example 1 **correct!**; >> git push fork fork-master:master example 2 **fails**; >> git push fork --all this automatically pushes fork branches origin except branch master rejected (in case changes made). what thought example #2 push fork-master fork/master , isn't happening. can push remote specific branches @ once without having point them correct remote branch name? i'm asking because there lot ...

oracle - How can I handle/recover a DB Integrity constraint violation exceptions in hibernate? -

i'm developing big web application uses jsf , hibernate orm. hibernate sessions long (the user can big amount of modifications on screen , changes persistent on db when he'll press save button) i'm struggling issue of roll-back / cancellation of user modification , looking different solutions , approaches. i want recover violation constraint exception ("ora-02292: integrity constraint"). consider following scenario: there table 'x' record 'x' , table 'y' record 'y' - 'x' depends on 'y' foreign key. user trying delete record 'y' , although there future possible integrity constraint violation on step, i'm not throwing exception because user able fix later , if won't fix , try save screen db throw exception aggregated user interface. i can't find way recover violation. in save process, after trying delete record 'y', db launches "ora-02292: integrity constraint" exceptio...

performance - Gatling - show failed requests only after max retry -

in test scenario i'm polling user session possible responses. due product behavior' normal receive 503 several times before receiving response , reason why i'm retrying 5 times. trymax(5){ exec(http("poll user") .get("/something.html") .queryparammap(map("nc" -> "true", "data" -> "true", "v" -> "1")) .check( status.is(200)) )} now' when @ statistics see 4 failed requests: [--------------------------------------------------------------------------] 0% waiting: 0 / active: 80 / done:0 ---- requests ------------------------------------------------------------------ > global (ok=1771 ko=4 ) > form login (ok=80 ko=0 ) > ********************** (ok=80 ko=0 ...

c++11 - C++ Cereal Archive Type Specialization not working -

i'm using cereal 1.1.2 vs 2013. i've tried example archive specialization types here: http://uscilab.github.io/cereal/archive_specialization.html but doesn't compile error: error c2665: 'cereal::make_nvp' : none of 3 overloads convert argument types ... while trying match argument list '(const std::string, const std::string) i'm trying compile following code, using snippets example: #include "cereal\types\map.hpp" namespace cereal { //! saving std::map<std::string, std::string> text based archives // note shows off internal cereal traits such enableif, // allow template instantiated if predicates // true template <class archive, class c, class a, traits::enableif<traits::is_text_archive<archive>::value> = traits::sfinae> inline void save(archive & ar, std::map<std::string, std::string, c, a> const & map) { (const auto & : map) ar(cereal:...

What is special about .NET primitive types? -

i reading primitive types on msdn , came across this answer on stackoverflow question primitive types. 2 seem differ ever slightly. according msdn documentation, states few of advantages of primitive types: primitive types permit literal values. primitive types can declared constant values. operands of expression made of primitive types can compiled constant expression. however, part differs stackoverflow states system.string , example, not primitive type. makes sense: typeof(system.string).isprimitive yields false . and, stackoverflow answer points cli spec: ecma 335 (link broken) source of reference. leads me believe msdn documentation not entirely accurate. if case, makes primitive types special? the msdn link points ancient page visual basic.net 2003. in current specification string removed list of primitive types. visual basic language reference doesn't mention string primitive type, vb.net 2003. i suspect documentation error in 2003

javascript - How to address to values of the two INPUTs of one position, if there are many positions -

i'm beginner in jquery, please simplifying following function in java script (by converting jquery). need write price calculator of goods. a piece html code <li> <input type="checkbox" class="option" value="5000" id="price-cb-1" onchange="calculate_price();"> <input id="price-uts-1" class="price-count" type="number" min="1" onchange="calculate_price();" value="1"> </li> <li> <input type="checkbox" class="option" value="9000" id="price-cb-1" onchange="calculate_price();"> <input id="price-uts-1" class="price-count" type="number" min="1" onchange="calculate_price();" value="1"> </li> .....there 30 elements of <li>..</li> with different values(prices). need add prices, multiplie...

svg - Firefox 38-40 SMIL problems - very slow speed (resolved in FF version 41 from 22.09.15) -

can give information new versions ff, passed after version 37.0.2. knew of bugs in version 38 have been fixed in version 38.0.5. noticed difference in processing speed of attributes 'animate' , 'animatetransform' in new versions of ff, , because of page becomes slow. if remove animate tags: <rect x="-1.32" y="-0.63" width="3.64" height="1.26" fill="#ffd9d9" stroke-width="0.0" rx="0.12"> <!--this animation makes half-visible selecting effect --> <animate attributetype="css" attributename="opacity" to="0.65" dur="0.5s" begin="mouseover" fill="freeze"></animate> <animate attributetype="css" attributename="opacity" to="1" dur="0.5s" begin="mouseout" fill="freeze"></animate> </rect> to th...

xml - LibXML : colon in removeAttribute and value in getAttribute -

this xml file <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <outer1 xmlns="http://blablabla"> <inner1> <name>hello</name> <org>wwf</org> <profession>warrior</profession> </inner1> </outer1> </config> i want 2 things get attribute value config , outer1 delete attribute this perl code use strict; use warnings; use xml::libxml; $xml = "sample3.xml"; $parser =xml::libxml->new(); $tree =$parser->parse_file($xml); $root =$tree->getdocumentelement; print $root->getattribute('xmlns:xc'), "\n"; print $root->getattribute('/config/outer1/@xmlns'), "\n"; --> not working $root->removeattribute('xmlns:xc');--> not working print "$tree->tostring"; the output should be <config> <outer1> <inner1> ...

python - theano csv to pkl file -

i trying make pkl file loaded theano csv starting point import numpy np import csv import gzip, cpickle numpy import genfromtxt import theano import theano.tensor t #open csv file , read in data csvfile = "filename.csv" my_data = genfromtxt(csvfile, delimiter=',', skip_header=1) data_shape = "there " + repr(my_data.shape[0]) + " samples of vector length " + repr(my_data.shape[1]) num_rows = my_data.shape[0] # number of data samples num_cols = my_data.shape[1] # length of data vector total_size = (num_cols-1) * num_rows data = np.arange(total_size) data = data.reshape(num_rows, num_cols-1) # 2d matrix of data points data = data.astype('float32') label = np.arange(num_rows) print label.shape #label = label.reshape(num_rows, 1) # 2d matrix of data points label = label.astype('float32') print data.shape #read through data file, assume...

Can I split compressed files into json components in Camel via Spring DSL -

in nutshell, need take gzipped file containing json similar example, unzip (i know how that), each json object string , push amq popped webservice. i'm fine of 1 object, receiving file represents array. if array of strings or xml, see how camel processes it, don't see way split json. also, require streaming these files can large. edited try make request clearer, , provide sample json. [ { "rickenbackerrepair": { "estimateid": 22788411 }, "repairshop": { "inspectionsite": { "inspectiondate": "" }, "repairfacility": { "companyidcode": "", "companyname": "", "city": "", "stateprovince": "", "zippostalcode": "", "country": "" }, "repairin...

scala - Sum or Product Type? -

given following algebraic data type : scala> sealed trait person defined trait person scala> case class boy(name: string, age: int, x: string) extends person defined class boy scala> case class girl(name: string, age: int, y: boolean) extends person defined class girl note - know it's not recursive type - there's no recursion involved. so, sum or product type ? why?

C++ Gnuplot pipe input from C++ defined variables -

i using c++ pipe commands gnuplot using following code: file *gnuplotpipe = popen("gnuplot -persist", "w"); // open pipe gnuplot if (gnuplotpipe) { // if gnuplot found fprintf(gnuplotpipe, "reset\n"); //gnuplot commands fprintf(gnuplotpipe, "n='500'\n"); fprintf(gnuplotpipe, "max='1500'\n"); fprintf(gnuplotpipe, "min='-1500\n"); fprintf(gnuplotpipe, "width=(max-min)/n\n"); fprintf(gnuplotpipe, "hist(x,width)=width*floor(x/width)+width/2.0\n"); fprintf(gnuplotpipe, "set term png #output terminal , file\n"); fprintf(gnuplotpipe, "set output 'observable_histogram.png'\n"); fprintf(gnuplotpipe, "set xrange [min:max]\n"); fprintf(gnuplotpipe, "set yrange [0:]\n"); fprintf(gnuplotpipe, "set offset graph 0.05,0.05,0.05,0.0\n"); fprintf(gnuplotpipe, "set xtics min,(max-min)/5,max\n"); fprintf...

python - Go through tar archive in memory to extract metadata? -

i have several tar archives need extract/read in memory. problem each tar contains many zip archives , each contain unique xml documents. so structure of each tar follows: tar -> directories-> zips->xml. obviously can manually extract single tar have 1000 tar archives 3 gb each , contains 6000 zip archives each. i'm looking way handle .tar archives in memory , extract xml data of each zip. there way this? this should doable, since of relevant methods have non-disk-related options. lots of loops here, let's dig in. for each tar archive: tarfile.open open tar archive. ( docs ) call .getmembers on resulting tarfile instance list of zips (or other files) contained in archive. ( docs ) for each zip within tar archive: once know member file (i.e., 1 of zips) want through, call .extractfile on tarfile instance file object zip. ( docs ) instantiate new zipfile.zipfile file object in order open zip can work it. ( docs ) call .infolist o...

javascript - Why color of navigation not changing -

hi writing code change navigation link colour based on url address not doesn't run please me. want change color of navigation link @ particular url address js code function big(x){ x.style.fontsize = "17px"; x.style.color="#03c1cb"; } function small(x){ var y=location.hash; if(x.href== y){ x.style.fontsize = "17px"; x.style.color="#03c1cb"; } else{ x.style.color = "white"; x.style.fontsize ="15px"; } } and function iselementinviewport (el) { //special bonus using jquery if (typeof jquery === "function" && el instanceof jquery) { el = el[0]; } var rect = el.getboundingclientrect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerheight || document.documentelement.clientheight) && /*or $j(window).height() */ rect.right <= (window.innerwidth || document.documentelement....

linux - C++ getenv doesnt update -

i'm trying make program bash script runs. want bash script able change state of c++ program, , thing find use environment variables. thing is, seems getenv gets value @ time when program run. bash export blink=1 ./blink & sleep 5s unset blink c++ int main(int args, char **argv) { char *blink = getenv("blink"); while(blink && blink[0] == '1') { std::cout << getenv("blink") << std::endl; usleep(500000); } return 1; } so run blink program, wait 5 seconds unset environment. c++ program sees enviorment value 1 , never stops. how updated environment variable while program running? or there better way have bash script control state of c++ program. edit should note, not want kill process either because has turn off hardware when ends. it not possible modify program environment after started. have use method of interprocess communication. simplest 1 register handler signal ap...

jquery - Cloudinary Java direct upload BAD REQUEST error -

i used java building image upload tag: map options = objectutils.asmap("resource_type", "auto"); options.put("callback", "http://localhost:8080/cloudinary_cors.html"); map htmloptions = null; string html = cloudinary.uploader().imageuploadtag("image_id", options, htmloptions); put string model attribute , show on page. looks button "choose file" . picked image , jquery.fileupload tried send image cloudinary. i took status code: 400 bad request , response: error: {message: "upload preset must specified when using unsigned upload"} all of settings right, can send image server side , using code: map uploadresult = cloudinary.uploader().upload("image.jpg", objectutils.emptymap()) but can't send file client side . code of page : <!doctype html> <html xmlns:th="http://www.thymeleaf.org"> <head> <script th:src="@{/js/common/jquery-1.11.3.min...

html - Why is my animation not playing? -

i've followed short tutorial create bouncing arrow code i've used pretty same excluding small differences. however, when add hero unit, doesn't play animation. it transform or keyframe mixins used... here jsfiddle: http://jsfiddle.net/x9hxfusa/ place keyframes & mixins declarations @ top. have declare them before calling them. see demo

How can I get the object value of a combobox in django view? -

i creating app in django , have form field 'person' foreignkey field. so, when run application appears form correctly showing me combobox lets me select 'person' object want. problem when try catch information in view. i send data post method, so, when try value of selected 'person' object in view next: selected_person = request.post['person'] (person field name) i surprised when tested value of variable 'selected_person' number (concretely, number of selected index of element in combobox). my question is: how can object value of selected element in combobox? than much! no, primary key of person object in database. can via person.objects.get(pk=selected_person) . but should using django form, give person object via form.cleaned_data['person'] . also note, clarity, select field, or drop-down, not combobox; combobox desktop widget has both drop-down , edit field.

python - Installing Twisted through pip broken on one server -

i setting virtualenv on new server, , when used pip on our requirements file, kept dying on twisted. commented twisted line out, , else installed fine. @ command line, output see when try install twisted (the same error see when run entire requirements file once gets twisted line): (foo)company@server:~$ pip install twisted collecting twisted not find version satisfies requirement twisted (from versions: ) no matching distribution found twisted i can install twisted fine dev machine , other servers, , on server seem able install other packages fine. case , version not matter. same result if use "twisted", "twisted", "twisted==15.2.1". this ec2 instance running ubuntu 14.04.02. ok after struggling several hours, figured out problem. running pip install --verbose twisted helped diagnosis. the error message misleading. problem built custom installation of python 2.7.10 without having installed libbz2-dev. steps fix were: sudo ap...

cmd - auto-completion in MATLAB with nodesktop option -

i'm using matlab r2012b on win7 computer. when launch matlab cmd using matlab -nodesktop , tab disabled auto-completion in command line window. have type full name of file, path or function. when open gui , set link says, ( http://www.mathworks.com/company/newsletters/articles/avoiding-repetitive-typing-with-tab-completion.html ) auto-completion works fine in gui. doesn't work when -nodesktop option used. i used use r2014b on ubuntu machine -nodesktop option, auto-completion function works fine. is there way enable auto-completion in cmd when -nodesktop chosen.

c - I am running a simple addition program, but I am having an issue with the output, when I check for an integer? -

#include <stdio.h> #include <ctype.h> int addi (int n, int m) { int x; x = n + m; printf("%d", x); return 0; } int main () { int t, u, i, j, k; printf("please enter 2 integers added"); while (1) { scanf("%d%d",&u,&t); if (isdigit(t)==0 && isdigit(u)==0) { break; } else { if(isdigit(t)==1 or isdigit(u)==1) printf("invalid input"); } } = addi(u, t); return 0; } the above code, having slight issue with. keep getting wrong output each time input character instead of getting invalid input output on screen. first of have pretty basic issue's in code. try explain those. #include<stdio.h> #include<ctype.h> int addi(int n, int m) { // 1 int x; x=n+m; printf("%d",x); return 0; } in code number:1 point, printing value of addition , returning 0 , that's no...

.htaccess - How to Block Spam Referrers like darodar.com from Accessing Website? -

i have several websites daily around 5% of visits spam referrers. there 1 strange things noticed referrers: show in google analytics, cannot see them in custom designed table insert visitors site, think manipulate ga code, never reaching site itself. if follow link, redirect affiliates link. i don't know whether have impact on seo/serp, rid of them. may via htaccess file? one peculiar aspect visitors different forum pages. e.g.: forum.topic221122.darodar.com , forum.topic125512.darodar.com etc., block full darodar.com domain. besides darodar.com , there econom.co , iloveitaly.co bothering stats. can block them htaccess ? this blog post suggests spam referrers manipulate google analytics , never visit site, blocking them pointless. google analytics offers filtering if want mitigate fake site hits.

design - Best practices for creating a project utilities module? -

does know of best practices around creating utilities module or class specific project? have project i've been working on has 3 different moving pieces, keep in same project. directory structure looks like: ├── dir_a │ └── driver.py ├── dir_b │ └── driver.py ├── dir_c └── driver.py each driver has common functions, want rip them out , throw them in utilities module project looks this: ├── dir_a │ └── driver.py ├── dir_b │ └── driver.py ├── dir_c │ └── driver.py └── utilities ├── __init__.py └── utilities.py the problem i'm having i'm finding out driver files can't import utilities module without utilities dir being in pythonpath. best practice creating or adding project-specific modules , classes in general? adding utilities pythonpath seems clunky , inelegant. ideally project self-contained , wouldn't dependent on modifying environment run.

python - How can I define a constraint on an inherited column in SQLAlchemy? -

i have class inheritance scheme layed out in http://docs.sqlalchemy.org/en/latest/orm/inheritance.html#joined-table-inheritance , i'd define constraint uses columns both parent , child classes. from sqlalchemy import ( create_engine, column, integer, string, foreignkey, checkconstraint ) sqlalchemy.ext.declarative import declarative_base base = declarative_base() class parent(base): __tablename__ = 'parent' id = column(integer, primary_key=true) type = column(string) name = column(string) __mapper_args__ = {'polymorphic_on': type} class child(parent): __tablename__ = 'child' id = column(integer, foreignkey('parent.id'), primary_key=true) child_name = column(string) __mapper_args__ = {'polymorphic_identity': 'child'} __table_args__ = (checkconstraint('name != child_name'),) engine = create_engine(...) base.metadata.create_all(engine) this doesn't work because ...

api - How to know if Linkedin user is admin of his company on LinkedIn? -

i'm building website using linkedin oauth api visitors can log in using linkedin. works fine, want give people administrator company registered linkedin. when people log in can different fields of info them using following: people/~:(firstname,lastname,positions) which gives me this: { u'firstname': u'john', u'lastname': u'doe', u'positions': { u'_total': 1, u'values': [ { u'startdate': { u'year': 2012 }, u'title': u'freelanceprogrammer', u'summary': u'this summary of company', u'iscurrent': true, u'id': 123456789 u'company': { u'industry': u'informationtechnologyandservices', u'size': u'myselfonly', ...

html - Use font awesome star rating define by width -

Image
currently reviews use star rating displayed css background classes. want replace font awesome because font sharper on high res screens. the problem rating defined dynamically width class in %. can not change code different div classes define width. for example score of 4,5 stars displayed using class width="80%;" max score 5 stars. it should this: how can replace font awesome stars? see jsfiddle: https://jsfiddle.net/tlj2ybnu/8/ this answer includes 2 solutions. first pure css. set class indicate score 0 10. second snippet simpler and more flexible; allows set percentage in tag itself. in both examples used stars wingdings font, use other fonts , characters or background image. solution in both cases have grey background of starts , golden overlay clipped right width. 1: predefined classes indicate value 0 10 i think bit of css can this. use special font, maybe wingdings option. contains couple of stars may use. the snippet below shows can ...

python - What's the correct way to clean up after an interrupted event loop? -

i have event loop runs co-routines part of command line tool. user may interrupt tool usual ctrl + c , @ point want clean after interrupted event loop. here's tried. import asyncio @asyncio.coroutine def shleepy_time(seconds): print("shleeping {s} seconds...".format(s=seconds)) yield asyncio.sleep(seconds) if __name__ == '__main__': loop = asyncio.get_event_loop() # side note: apparently, async() deprecated in 3.4.4. # see: https://docs.python.org/3.4/library/asyncio-task.html#asyncio.async tasks = [ asyncio.async(shleepy_time(seconds=5)), asyncio.async(shleepy_time(seconds=10)) ] try: loop.run_until_complete(asyncio.gather(*tasks)) except keyboardinterrupt e: print("caught keyboard interrupt. canceling tasks...") # doesn't seem correct solution. t in tasks: t.cancel() finally: loop.close() running , hitting ctrl + c yields:...

objective c - Parse Cloud Code query not getting executed -

i have below cloud code function , when call function os x app, success response well. none of console log output messages inside success , failure blocks of query operation gets executed. ideas on appreciated. parse.cloud.define("markalertasexpired", function(request, response) { parse.cloud.usemasterkey(); var alert = parse.object.extend("alert"); var query = new parse.query(alert); query.get("vc6ppoxuqd", { success: function(alertobj) { // object retrieved successfully. var status = alertobj.get("status"); console.log("received object status:"); console.log(status); if (status == "active") { console.log("active"); markactivealertasexpired(alertobj); } else if (status == "inactive") { console.log("inactive"); markinactivealertasexpired(alertobj); } else { console.error("unknown_status")...

python - How do I Start/Stop AWS RDS Instances using Boto? -

i had question amazon rds. wanted start/stop aws rds instances @ need . aws console not allow me so. the method know take snapshot of rds instance , delete , when need create rds instance using snapshot. there better way acheive same using boto? no, that's best can do. rds api not support stop/start functionality of ec2 instances.

sql - Stored Procedure Parameters -> error converting data type nvarchar to money -

i stuck error @ stored procedure. i've searched , tried different stuff, solutions didn't fix it. i want check if salary of employees between 2 different values , don't cross minimum or maximum value. i use trigger fires on insert , update , gets following data , uses data execute stored procedure. 1 - job_id (int datatype) 1000.00 - salaris (money datatype) 13 - employee_id (int datatype) 3000.00 - min_salary (money datatype) 7000.00 - max_salary (money datatype) calling of stored procedure: exec sp_salary_check salary, emp_id, job_number, min_salary, max_salary, '' (output) parameters of stored procedure: (@new_salary money , @emp_id integer, @job_number integer, @min_salary money, @max_salary money, @msg varchar(50) output) if insert employee break on parameters of stored procedure. receive error: error converting data type nvarchar to money . indicated attribute @new_salary. if change nvarchar works perfectly. if change datatype money nvar...