Posts

Showing posts from July, 2010

C#: Optimizing error prevention with the input console -

i've started learning c# using rob miles' c# programming yellow book , related lab exercises website. did 1 of them , produced solution works...(there's not 1 provided). wanted not crash if user inputs nonsensical answers or string can't converted integer(i googled , found tryparse method. textbook briefly taught try/catch method, didn't seem useful user interface, i.e. let program continue after bad input). set that, in 1 of these cases, sends out alternate message. i've ended long code... do/while within do/while , do/while within while. if have tips streamlining this, i'd obliged. best, elliot using system; using system.io; static class cinema { static void main() { int[] selection = new int[] //array age requirements of each film { 15, 15, 12, 18, 0 }; string filmnumbertext; //console input film number int filmnumber; //input string parsed integer string agetext; //console input age int age; ...

jquery - How can i take the value of the specific option? -

i have code : function select(cities, country) { $('<div class="btn-group "><button type="button" id="forecast" data- toggle="modal" data-target="#mymodal" name="forecast" class="btn btn-primary pull-right" >show me forecast</div>').insertafter('.btn-group'); $('#cities').html(' <label for="cities">select city</label> <select name="cities" id="city" class="form-control">' + '<option disabled selected value> -- select option -- </option>' + cities.map(function (city) { return '<option value="' + city + '">' + city + '</option> '; }).join('') + '</select>' ); var city = $("#city option:selected").val(); console.log(city); } i want ta...

Android Fit image to full width using Picasso library -

i using picasso library load images , working fine after using library image not fit layout .if set image directly image view image fit layout.is there option pass method in picasso fit image layout picasso.with(getcontext()) .load(r.drawable.dddd). .into(lavdateimageview); even tried pass following method no use fit() , croptinside() etc xml file <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:orientation="vertical"> <scrollview android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="none" android:background="#ffffff" > <l...

java - Spring controller redirect to another module -

Image
i need help. i have app, in backend , frontent separated(backend - java + spring, frontent - angularjs), located in different modules in project , connected via rest protocol. on request mapping "/" should redirect user page index.html, html file located not in same package , module of application spring controller. i know, can user internalresourceviewresolver redirect user view, located in web-inf folder. not case.. can me problem please? how can redirect user view in module? structure of application: you can put index.html in src/main/webapp (not in web-inf) folder , let serving index.html file is. no configuration needed. additionally rest controllers should respond not on / but, example on /rest/something, can annotate directely controllers classes

javascript - Mutually Exclusive Data Attribute Selectors -

is possible select elements based on mutually exclusive data attributes, example: i'd .show() div s data attribute of country="united-kingdom" , type="partner" or "director" ? like: $('.post[data-country="united-kingdom"]&[data-type="partner,director"]').show(); or $('.post[data-country="united-kingdom"]&[data-type="partner"]or[data-type="director"]').show(); i'd .show() divs data attribute of country="united-kingdom" , type="partner" or "director"? then want selector group : $('.post[data-country="united-kingdom"][data-type="partner"], .post[data-country="united-kingdom"][data-type="director"]').show(); that says: match element which has class post , has data-country set united-kingdom , , has data-type set partner or has class post , has data-country set un...

How to reduce return content size from Slack rtm.start api -

the api doc can found here . i connect rtm.start api bot user : https://slack.com/api/rtm.start?token=bot_token , doc described: this method returns lots of data current state of team, along websocket message server url acutally content care websocket message server url . currently, i'll 19mb content api(as big team many channels , users). it take long code make request , cause timout. can increase timeout time, want wss url , make websocket call, idea how decrease content size api? i know parameters simple_latest & no_unreads & mpim_aware can used. i've tried them https://slack.com/api/rtm.start?token=bot_token&simple_latest=true&no_unreads=1&mpim_aware=true or did not work. i want know how make these 3 optional parameters work. no_unreads=1 correct way use these 3 parameters. and got way: per contact slack team, got additional parameter did not appear in document: cache_ts ==> timestamp 1479103245436 indica...

javascript - Drawing a line between moving objects -

i'm trying draw line between 2 moving vertices. vertex's drawing stored in variable called object , has position , three.vector3 . the line created thusly: var line = function(scene, source, target){ var geometry = new three.geometry(); geometry.dynamic = true; geometry.vertices.push(source.object.position); geometry.vertices.push(target.object.position); geometry.verticesneedupdate = true; var material = new three.linebasicmaterial({ color: 0x000000 }); var line = new three.line( geometry, material ); scene.add(line); return line; }; ..., source , target vertices , vertices updated via: vertex.object.position.add(vertex.velocity); now, assigned source.object.position , target.object.position line.geometry.vertices[0] , line.geometry.vertices[1] because wanted 1 update other. instead, vertex positions vary wildly line positions. vertices are, lines don't connect vertices. how can make lines move vertices? in animation loop ha...

python - Flask-Login not working with two applications on same domain -

i have been using flask-login on <domain>/<app_1> year without issue. recently, built second application same stack , deployed <domain>/<app_2> . now, whenever log either app, kicks me out of other. there reason this? apps have different databases , secret keys, , have assumed have 2 cookies same domain. i'm not familiar cookies , not sure how debug this. i'm happy provide headers or other information if people can tell me relevant. you need configure cookies use separate paths. app.config['remember_cookie_path'] = '/app_1'

javascript - Unknown provider: ngStorageProvider <- ngStorage when trying to use Angular ngStorage -

i have code below uses ngstorage. when try run part of angular app error console: error: [$injector:unpr] unknown provider: ngstorageprovider <- ngstorage <- signupcontroller why? sign in controller.js var smalltalkzmodel = angular.module('smalltalkzmodel', ['ui.router', 'luegg.directives', 'ngcookies', 'ngstorage', 'angular-jwt']); smalltalkzmodel.controller('signupcontroller', ['$scope', '$location', '$http', 'userdetails','ngstorage', function ($scope, $location, $http, userdetails,$localstorage) { $scope.register_user = function (info) { $http({ url: '/register_user', method: 'post', data: info }).then(function (response) { $localstorage.jwt = response.data.id_token; $location.path('main'); }, function (error) { ...

TypeScript typings give me "index.d.ts is not a module" -

i getting file node_modules/@types/webrtc/index.d.ts not module code: import * webrtc "webrtc"; const peerconnection1 = new rtcpeerconnection(); i have installed typings using npm @types/webrtc --save-dev . hovering on rtcpeerconnection in const peerconnection1 = new rtcpeerconnection(); display type annotations in visual studio code @ least code editor sees types. running tsc (or webpack ts-loader ) fails error. i have tried npm webrtc --save in misguided attempt solving this, did not change , want typings anyway, webrtc right there in browser, don't need package that. (support aside.) the index.d.ts file indeed not module, references 2 other files interfaces in them. thought remove import * webrtc "webrtc"; hoping typings still visible tsc somehow. (but that's impossible since exclude node_modules in typescript config file.) when rtcpeerconnection no longer recognized. adding /// <reference src="node_modules/@types/webrtc/...

haskell - Cabal selects wrong linker -

i working on haskell program linked old c++ code. created c interface , got working ghc only. tried convert used makefile cabal project , cabal on last step selects wrong linker. because of dependencies have use quite old ghc , gcc. doing calling cabal (1.24.0.0.) this: cabal install --with-ghc=ghc-7.6.3 --with-gcc=/opt/gcc-3.3.6/bin/gcc --with-ld=/opt/gcc-3.3.6/bin/gcc for compile- , intermediate configure linking ok, -v3 following lines: using gcc version 3.3.6 given user at: /opt/gcc-3.3.6/bin/gcc using ghc version 7.6.3 given user at: /home/oswald/ghcs/bin/ghc-7.6.3 ... using ld given user at: /opt/gcc-3.3.6/bin/gcc all works fine until final linking step: linking dist/dist-sandbox-c45ed4c7/build/miscconfig/miscconfig ... *** c compiler: '/opt/gcc-3.3.6/bin/gcc' '-c' '/tmp/ghc28340_0/ghc28340_0.c' '-o' ... *** c compiler: '/opt/gcc-3.3.6/bin/gcc' '-c' '/tmp/ghc28340_0/ghc28340_0.s' '-o'...

in app purchase - Android In-App Billing - Error Authentication is required. You need to sign into your google account -

my android app using in-app billing since april 2015 without problems. process not working anymore. have not changed process of purchasing or methods in app. since last update 1 week ago users getting error when want purchase iap. app throws error saying "error authentication required. need sign google account". updated latest sdk-tools , targetversion 23. i have done found on web, checking product id , on. can me, fix problem?

php - I need to share data between steps in different classes -

i need share data between steps in different classes using behat. ( good practice pass variables between cucumber-jvm steps ) picocontainer cucumber. there such framework? know can use static member maybe framework this. you have multiple options: create specialized class static methods handle different data use behat functionality communicate between contexts, see similar question accessing contexts each other if need generate different data use faker php

ruby on rails - bundle exec rake db:migrate -- schema.rb regenerated WITHOUT indices -

Image
i have large database tons of tables , many indices on tables. every time run migration, schema.rb file generated fine, except none of indices included. new tables , columns added fine. if manually re-add add_index lines schema.rb file after migration, works fine, doing after every migration major hassle. i've been dealing problem months , haven't been able find solution or workaround. know might happening? using postgres & rails 3. in rails 3 indexes not displayed in schema.rb file. given below screenshot of shema dump rails 3 documentation. no indexes shown. i have tried install rails 3 postgres, rails 3 mysql , rails 3 , sqlite. indexes added database cannot see them in schema.rb . there 1 way show them in schema.rb adding indexes manually file or can leave scehma.rb without indexes. indexes added database when run rake db:migrate . , if want can upgrade rails 4 or above , never face problem.

java - extract date from string in Scala efficiently -

i want extract date (e.g. 2015-01-01 ) multiple strings have form in scala: val s = "basedir/somedir/tmp/blah/2015-01-01.txt" i know can basic string split-trim-strip operations achieve that, there more cleaner way in scala? can use nice regex "hidden features" scala offers this? i tried without success: val s = "basedir/somedir/tmp/blah/2015-01-01.txt" val regex = "(\\d+)-(\\d+)-(\\d+).txt" val regex(year, month, date) = s use pattern matching using regex extractor val regex = ".*/(\\d{4}-\\d{2}-\\d{2}).txt".r //remove / after .* if think not needed. str match { case regex(date) => some(date) case _ => none } use above code instead of below because below 1 cause match error @ runtime. val regex(a) = "basedir/somedir/tmp/blah/2015-01-01.txt" instead of .* in front of regex. can use unanchored . val regex = "(\\d{4}-\\d{2}-\\d{2}).txt".r.unanchored scala repl scala> v...

keychain - A proper way to install PEM certifiate in Android -

i developing android project. i have pem certificate string: -----begin certificate----- miieczcca1ugawibagibadanbgkqhkig9w0baqqfad..akga1uebhmcr0ix ezarbgnvbagtclnvbwutu3rhdguxfdasbgnvbaotc0..0egthrkmtcwnqyd vqqley5dbgfzcyaxifb1ymxpyybqcmltyxj5ienlcn..xrpb24gqxv0ag9y ...many lines... it8una2gy4l2o//on88r5iwjlm1l0oa8e4fr2yrbhx..adsgefkkynrwgi/ 7vqmfxdgsrrxngrgnx+vwdz3/zwi0jodtcknnqepvn..hox -----end certificate----- (assigned above certificate string variable named cert_str ) i decode above pem string byte array: byte[] pembytes = base64.decode( cert_str.replaceall("-----(begin|end) certificate-----", "") .replaceall("\n", "") .getbytes("utf-8"), base64.default ); i try programmatically install pem certificate android phone following code: intent intent = keychain.createinstallintent(); // because pem contains certificate, no privat...

c++ - How to find unique element count in string array? -

this question exact duplicate of: how unique strings array c++ 4 answers for example, have list of towns. 20 of them in fact, in 20 town string array there 4 unique towns, randomly scattered in array , can repeat. how find unique town count? use std::set , e.g. std::set<std::string> myset(list_of_towns.begin(), list_of_towns.end()); assuming town names in std::vector called list_of_towns .

angular2 routing - How to display details of an item next to the parent in Angular 2? -

Image
i have multiple datasets listed on page , on clicking on of them display details below it. change routing on click, example '/datasets' '/datasets/1234567'. i added routing '/datasets', can't figure out how tell angular 2 display item details next summary. tried add 1 router-outlet element next each summary idea display details in element, can't specify "name" attribute of router-outlet id of dataset example {{dataset.id}} - template parser throws syntax error. please check attached screencast. it looks overestimated challenge. there few ways achieve it: the parent component - prints datasets create router-outlet element. then, child route :id added , dataset details rendered in router-outlet element. router-outlet element can displayed next dataset summary using css. the child component (dataset-details) may notify parent id of dataset. then, parent component render render-outlet next summary of dataset same id. ...

C/C++ module vs python module. -

in python ( cpython) can import module: import module , module can *.py file ( python code) or module can module written in c/c++ ( extending python). so, such module compiled object file ( *.so / *.o on unix). i know how executed interpreter exactly. i think python module compiled bytecode , interpreted. in case of c/c++ module functions such module executed. so, jump address , start execution. please correct me if wrong/ please more. when import c extension, python uses platform's shared library loader load library , then, say, jumps function in library. can't load library or jump function way. works libs implemented support python , functions exported library python object. lib must understand python objects , use objects communicate. alternately, instead of importing, can use foreign-function library ctypes load library , convert data c view of data make calls.

javascript - All checkboxes getting checked even if one is checked -

i'm making basic todo app in angularjs. here's code that's used create new todo checkbox <div class="container" ng-controller = 'controller' > <h3>enter todo </h3> <input type="text" ng-model = 'new'> <button ng-click = 'add();' ng-disabled="status();">add</button> <div ng-repeat = "i in todo" > <input type="checkbox" ng-model = "todo.done" /> <label>{{i.name}}</label> </div> </div> the problem checkboxes checked when check one here's controller module todoapp.controller('controller',['$scope',function($scope){ $scope.new = ''; $scope.todo = []; $scope.add = function(){ $scope.todo.push({name : $scope.new, done: false}); console.log($scope.todo); $scope.new = ''; }; $scope.status = function(){ return !(/\s+/.test($scop...

ef code first - Entity Framework: How to Insert and Update entity with one-to-many relationship? -

we are using ef-6 code-first approach, , having trouble one-to-many relationship. we have following entities in database gives related data: public class university { public int uid { get; set; } public string name { get; set; } } public class subject{ public int subjectid { get; set; } public string name { get; set; } } public class specializedsubject{ public int specializedsubjectid { get; set; } public int subjectid { get; set; } public string name { get; set; } } public class maleteacher{ public int maleteacherid { get; set; } public string name { get; set; } } public class universitymaleteacher{ public int universitymaleteacherid { get; set; } public int maleteacherid { get; set; } public int uid { get; set; } public string name { get; set; } } public class universitymaleteachersubject{ public int universitymaleteachersubjectid{ get; set;...

Gulp Sass Compiles Only With Two Saves -

i've been trying compile changes @imports along main scss files, , have working. the issue setup: see changes, must save files twice (irrespective of whether they're main files or imports). ideas on appreciated. the directory structure simply: --> scss --> scss/partials here relevant parts of gulpfile: var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var autoprefixer = require('gulp-autoprefixer'); var rename = require('gulp-rename'); var sync = require('browser-sync').create(); // create browser sync instance. var sasspaths = [ 'bower_components/foundation-sites/scss', 'bower_components/motion-ui/src' ]; var paths = { 'assets': 'assets', 'dev': 'assets/styles/dev' }; // dev css gulp.task('dev-styles', function() { return gulp.src(['scss/**/*.scss', 'scss/*.scss']) .pipe($.sass({ ...

android - Getting SurfaceTexture pixels fast or trick with TextArea -

i have qt realtime broadcasting chat application android (v 4.1, api 16), sends h.264/aac chunks rtmp server. for now, application uses surfaceview capturing frames camera , in onpreviewframe function encode frames h.264 chunks , in other thread create rtmp chunks, sending rtmp server, wrote above. background transparent (with qt::windowstaysontophint flag) , qml ui draws above camera 's surfaceview - works pretty well, without lags , other. but, when tried use qml's textarea (for writing chat messages), above surfaceview , there long delays on devices (and not on samsung's) when press on key on android's virtual keyboard, did app absolutely unusable. example, type "lag" on keyboard, , there 3-4 second delay between showing every symbol in textarea ))): surfaceview , broadcast works without lags. so, dear developers, shall solve problem? for now, moved camera 's preview surfacetexture , draw using qt's qsggeometrynode , there prob...

swift3 - Swift 3 Convert Double to String -

i keep getting error "initializer conditional binding must have optional type, not 'double'". trying display core data values , 1 double. ive tried work around same way had store values when converting it. heres code gives me error: func displaystats() { // display other attributes if have values if let servingsize = mealstats.serving { servingslabel.text = servingsize } mealstats.serving of type "double" , not "double?" since not optional cannot unwrapped. right way use be func displaystats() { // display other attributes if have values servingslabel.text = "\(mealstats.serving)" }

MATLAB's smooth implementation (n-point moving average) in NumPy/Python -

matlab's smooth function, default, smooths data using 5-point moving average. best way same in python? example, if data 0 0.823529411764706 0.852941176470588 0.705882352941177 0.705882352941177 0.676470588235294 0.676470588235294 0.500000000000000 0.558823529411765 0.647058823529412 0.705882352941177 0.705882352941177 0.617647058823529 0.705882352941177 0.735294117647059 0.735294117647059 0.588235294117647 0.588235294117647 1 0.647058823529412 0.705882352941177 0.764705882352941 0.823529411764706 0.647058823529412 0.735294117647059 0.794117647058824 0.794117647058824 0.705882352941177 0.676470588235294 0.794117647058824 0.852941176470588 0.735294117647059 0.647058823529412 0.647058823529412 0.676470588235294 0.676470588235294 0.529411764705882 0.676470588235294 0.794117647058824 0.882352941176471 0.735294117647059 0.852941176470588 0.823529411764706 0.764705882352941 0.558823529411765 0.588235294117647 0.617647058823529 0.647058823529412 0.588235294117647 0.617647058823529 0...

java - JSON object within object -

this question has answer here: how parse json in java 27 answers "fid": "123", "farm_info": { "name": "example farm", "address": "example address", "phone": "111-111-1111", "web": "" }, "personal_info": { "name": "myname", "email": "myname@example.com", "phone": "111-111-0000" }, "delivers_to": ["60001", "60002"] this object returned json. in java fid string , delivers_to array of strings. data type farm_info , personal_info have json returned? a class custom defined data type in java (you can define group of elements structure in c) , so, farm_info , personal_info object types. so parse json, along data types mention...

jsp - How to pass a scriptlet variable into onclick() function call to javascript -

i need read variable , have pass argument function after onclick(). using jsp, reading variable using scriptlets <% int lateregdays = 6;%> i passing variable as onclick="displaydatepicker('starttestadminno','mdy',<%=lateregdays %>,120,0,3);" but, unable pass valueof 6. string "<%=lateregdays%>" being passed function. however, when tried print value using alert, worked. changes did is, onclick='<%="alert("+lateregdays+")"%>' in similar fashion, need know, how pass arguments function scriptlet variable. entire code snippet is: <td><input name="starttestadminno"></td> <td> <chtml:img srckey="order.calendar.search" onclick="displaydatepicker('starttestadminno','mdy',<%=lateregdays %>,120,0,3);" altkey="order.calendar.alt_search" bundle="prompt" /> </td> ...

user interface - Python icon not showing anymore -

during last days, have realized python icon created in dock when launching ipython no longer launching (see example here ). problematic if want select other application , come plot, since can't click on icon in dock (so have minimize lot of windows until reach it). using python 3.5 , running on os x el capitan. i don't know when issue appeared exactly, , hard tell origin since updated xcode , python packages through conda, wondering if has idea of why happening. if manage installations using homebrew, can run brew linkapps in terminal recreate symlinks them.

javascript - How to set warnings when time is almost up on DateTime -

i have due_dates column in db , datetime format. want rails app able detect when there day left or hour left etc. based on datetime value. every request have due date each datetime unique. know how make notifications don't know how make timer aspect or you're suppose detect these datetimes before or when pass date. ex. today <-- 11/5/2016 |(one day)| 11/6/2016 <--duedate db update/ send notification "one day left" if want know whether before or duedate if datetime.now <= duedate # end to show distance in word one day left or one hour use use this # if needed, include actionview::helpers::datehelper distance_of_time_in_words_to_now(duedate) so if datetime.now <= duedate @distance_in_words = distance_of_time_in_words_to_now(duedate) # else setup notification end

jpa - EntityManager null pointer exception from Persistence Context Java EE -

i have problem using entitymanager managed ejb container. in ear have 3 modules: -domain - there entity classes , dao implementations interfaces ejbs. -services - there have logic related processing requests, invoking bussiness exceptions based on libraries exceptions (for example database exceptions). -rest services - there have rest endpoints receive , send business objects. so main problem using ejbs in services layer, can declare rest endpoint class, service class, , dao class ejbs. way can't catch exceptions related database, because red transactionrollback exception in ejb container provided wildfly , exception existing on commiting transaction. i thought removing @stateless annotation service class, when ejb container don't inject entitymanager in dao class. tried using @inject annotation in service class, still same nullpointer exception on entitymanager in dao class. below adding sample code implementations in project : dao class: @stateless publi...

javascript - Show full json set in Angular Material Autocomplete dropdown result on focus -

i filtering json file angular material autocomplete search input; can't seem recreate automatic dropdown json elements on focus demo: angular material demo autocomplete here's code far : html: <md-autocomplete md-search-text="searchtext" md-items="item in items | filter:searchtext" md-item-text="item.companyname + space + item.stocksymbol" placeholder="type company name or stock symbol"> <span md-highlight-text="searchtext">{{ item.companyname }} {{ item.stocksymbol }}</span> </md-autocomplete> js: app.controller('ctrl', ['$scope', function($scope) { $scope.items = stocks.dowjones30; $scope.searchtext = ''; $scope.space = " "; }]); the json bit goes this: var stocks={dowjones30:[{companyname:"3m",stocksymbol:"mmm"}, {companyname:"american express",stocksymbol:"axp"}, {companyname:...

How to prevent the Visual C++ linker from including every function whose address is taken? -

the question pretty simple. let's compile & link code: static char const *foo() { static char const *baz = "0123456789abcdef"; return baz; } static char const *(*bar)() = foo; int main() { return 0; } the visual c++ compiler or linker automatically seems mark string baz used, , includes it, though never used (despite fact foo 's address taken). is there way make compiler or linker avoid including code isn't used? separating foo() , bar() different obj file (i.e., different cpp) start - not enough. turns out when linking executable linker pulls in every obj file built exe anyway. the second part of solution extract cpp foo() , bar() static library , , have executable main() link against it. afaict exact vc linking apparatus isn't officially documented, surveyed raymond here . also, not work if check ' use library dependency inputs '

Can Laravel Auth::attempt() handle relationships? -

i'm using entrust managing role based permissions in laravel 5.3, , naturally using manual/custom logins different user types. possible auth::attempt() handle foreign table relationships? basically, want this: if(auth::attempt(['email' => $request->email, 'password' => $request->password, hasrole('teacher') => true])) { return redirect()->intended('teacher/dashboard'); } but keep getting error hasrole() undefined function. have included use zizaco\entrust\traits\entrustusertrait; , use entrustusertrait; , thought provide me access function, apparently not. i appreciate fact hasrole() method user objects, , @ time of checking don't have user object can't role check after attempt has succeeded because user has been logged in, , if role wrong need log them out credentials correct, not role; seems slow , not pragmatic. how should go handling this? there alternative auth::attempt can use not log in user,...

c - How can I access members in an array of structures that I passed into a function by value? -

#include <stdio.h> #include "inventorymanager.h" void displayinventory(const struct item items[], const int size) { printf("\n\n"); printf("inventory\n"); printf("=========================================\n"); printf("sku price quanity\n"); int index = 0; (index = 0; index < size; index++) { printf("%-10.0d %-10.2f %-10d\n", items[index].sku, items[index].price, items[index].quantity); } printf("=========================================\n"); } i getting red underlining under "items" when try access structure values within array. i have 3 files, inventorymanger.h, inventorymanager.c, shopping_lab_2.c ... struct called item created in shopping_lab_2.c, , function seeing on stack overflow made in inventorymanager.c. i not sure how call function. program below works without errors or warnings: struct item{ int sku; float price; int quantity; }; void displ...

c++ - get number of the binary % operator iterations -

i trying find out how many times % has substracted number another. for example if 256 % 50 = 6, iterations have been 5? 256 - 50 - 50 - 50 - 50 - 50. if 145 % 40 = 25, iterations have been 3. 145 - 40 - 40 - 40. i looking solution problem without usiong kind of loop, recursion or goto. what you're looking / operator. try division operator instead of modulus operator. works every time. it's fundamental math.

c - For waitpid, how do I know if the child finishes its process? -

first, fork child something, , use waitpid(-1, &child_status, wnohang) ; in parent let parent continue instead of waiting child finish. how know when child finished process? you can set signal handler sigchld gets sent automatically when child process exits. the signal processor can set global flag can periodically checked in other parts of program. if flag set, call wait or waitpid child's exit status. int child_exit_flag = 0; void child_exit(int sig) { child_exit_flag = 1; } ... signal(sigchld, child_exit); ... if (child_exit_flag) { pid_t pid; int status; child_exit_flag = 0; pid = wait(&status); printf("child pid %d exited status %d\n", pid, status); }

rstudio - Rmarkdown doesn't display dots in formulae (pdf output) -

Image
i'm trying recent 1.0 version of rstudio, generated document worked ok, i' having problems dots in formulae when compiling pdf_output. example when write: $a(l) = 1 - 1.6 l + 0.96 l^2 - 0.256 l^3$ i in pdf: i´ve searched in web , found nothing useful. in advance help. babel expects commas decimal separators when using spanish. thus, work out of box (and in opinion proper solution). $a(l) = 1 - 1,6 l + 0,96 l^2 - 0,256 l^3$ however, can still example work. according this tex.se answer , can force babel use dots decimal separator setting language way (notice there no lang option): --- title: "test" output: pdf_document header-includes: - \usepackage[spanish,es-nodecimaldot]{babel} ---

Python Tkinter Apply Filter to Text -

i have simple text widget made tkinter , python 3, this: from tkinter import * def makeupper(): pass root = tk() t = text(root) t.pack() menubar = menu(root) menubar.add_command(label="make upper", command=makeupper) root.config(menu=menubar) when user selects make upper, make selected text uppercase.

swift - How can I return a function that depends on two functions? -

i have following function: private func getfunctiontoplot() -> ((double) -> double) { var function: (double) -> double = sin + cos return function } i return function takes double , returns double, functions should sin + cos . both sin , cos independently take double , return double, how can return sin($0) + cos($0) . your question little broad, line claim doesn't compile does compile; there's nothing wrong you're doing. problem code incomplete. here test example is complete: private func getfunctiontoplot() -> ((double) -> double) { var function: (double) -> double function = {_ in return 2.0} return function } edit revised question, here's test example of sort of thing seem trying do: func sin(_ d:double) -> double {return 1} func cos(_ d:double) -> double {return 1} private func getfunctiontoplot() -> ((double) -> double) { let f1: (double) -> double = sin let f2: (double) -> d...

momentjs - How to parse this time string with Datatables and moment.js? -

so i'm using datatables , moment.js plugin ( https://datatables.net/plug-ins/datarender/datetime ). (the string) "invalid date" returned... { "data": "last_updated", //source: 2016-11-02 10:32pm gmt render: $.fn.datatable.render.moment( 'yy-mm-dd hh:mmtt gmt', 'dd mmm yy' ) } thanks! that plugin takes one, 2 or 3 arguments. testing seems though date valid i'd suggest passing "ss mmm yy" function. quick example seems work: moment("2016-11-02 10:32pm gmt").format("dd mmm yy"); // "02 nov 16" another issue might date isn't set, it's perhaps worth checking nulls , setting default content. in fact, if you've got momentjs available can replace plugin render function: "render": function(data){ return (moment(data).isvalid()) ? moment(data).format("dd mmm yy") : "-"; } hope helps.

Converting a JavaScript code using callbacks and RegEx method to equivalent code in C# -

i've below javascript code, returned function callback related user command, user command used in different ways, hence regex required: (function (undefined) { "use strict"; var root = this; var commandslist = []; var debugstyle = 'font-weight: bold; color: #00f;'; // command matching code modified version of backbone.router jeremy ashkenas, under mit license. var optionalparam = /\s*\((.*?)\)\s*/g; var optionalregex = /(\(\?:[^)]+\))\?/g; var namedparam = /(\(\?)?:\w+/g; var splatparam = /\*\w+/g; var escaperegexp = /[\-{}\[\]+?.,\\\^$|#]/g; var commandtoregexp = function(command) { command = command.replace(escaperegexp, '\\$&') .replace(optionalparam, '(?:$1)?') .replace(namedparam, function(match, optional) { return optional ? match : '([^\\s]+)'; }) .replace(splatparam, '(.*?)') ...

Unique_together and OneToOne field constraints error catching in django form -

i have model: class person(models.model): name = models.charfield(max_length=250) slug = autoslugfield(populate_from='name') birth_date = models.datefield(null=true, blank=true) blood_group = models.charfield(max_length=5) present_address = models.charfield(max_length=250, blank=true) permanent_address = models.charfield(max_length=250, blank=true) user = models.onetoonefield( settings.auth_user_model, related_name='member_persons') class meta: ordering = ['name'] unique_together = ['name', 'birth_date'] you see above model has 2 constraints: 1 unique user , unique_together name , birth_date fields. want when submit create form simultaneously check both unique user same name , birth date people can't submit form. when happens should show appropriate errors in form fields. of other thread of so far write clean method follows: def clean(self): user = get_user(self.re...

c++ - Deleting multiple nodes in a Binary Search Tree -

i'm not quite sure how remove nodes in binary search tree. i've been specified remove student objects grade value of less 50. remove function bool remove(btnode<value_type>* cnode, value_type& data) { if(cnode == null) { return false; } if(data.get_name() > cnode->get_data().get_name()) { remove(cnode->get_right(), data); } else if(data.get_name() < cnode->get_data().get_name()) { remove(cnode->get_left(), data); } else { if(cnode->is_leaf()) { if(root->get_data().get_name() == data.get_name()) { root = null; } else { if(cnode->is_right_child()) { cnode->get_parent()->set_right(null); } else { cnode->get_parent()->set_right(null); ...

python - Create virtual interface for serial port? -

i have new version of device has microusb port, whereas old device had serial port. have python code should, in theory, work sending data new device, except fact code uses pyserial library. there quick hack might able use, emulating serial port , routing data new device, or something, might able allow me use old python software new device? thanks, , sorry being general.

python - Mongoengine few problems with reference field -

i have few problems mongoengine data manipulation. here models: class resource(mongo.document): slug = mongo.stringfield(max_length=255, primary_key=true) name = mongo.stringfield(max_length=150, required=true) meta = { 'allow_inheritance': true, } class linkresource(resource): link_url = mongo.stringfield() class fileresource(resource): file = mongo.filefield() class plan(mongo.document): slug = mongo.stringfield(max_length=255, primary_key=true) name = mongo.stringfield(max_length=150, required=true) subplans = mongo.listfield(mongo.embeddeddocumentfield('self') resources = mongo.listfield(mongo.referencefield(resource)) i need add resource plan , need move resource subplan (field of plan ) or other plan . then i'm add link resource plan next code: res = linkresource.objects().get(slug='mylinkres') p = plan.objects().get(slug='myplan') p.update(add_to_set__resources=[res]) but ...

internet explorer - IE 10 + 11: CSS transitions with calc() do not work -

i animating container on mouseover right left css transitions. works fine in browsers except internet explorer. reason using (and need use) calc() in css left property. i created live demo here: live demo the css looks this: div { background: red; width: 100px; height: 100px; position: absolute; top: 100px; left: 90%; -webkit-transition: left 0.7s cubic-bezier(0.77, 0, 0.175, 1); -moz-transition: left 0.7s cubic-bezier(0.77, 0, 0.175, 1); -o-transition: left 0.7s cubic-bezier(0.77, 0, 0.175, 1); transition: left 0.7s cubic-bezier(0.77, 0, 0.175, 1); } div.translate-less { left: calc(90% - 4rem) } i adding class .translate-less on mouseover jquery: $(document) .on( 'mouseenter', 'div', function(){ $(this).addclass('translate-less') }) .on( 'mouseleave', 'div', function(){ $('div').removeclass('translate-less'); }) now have smooth transition in internet explorer. th...

ios - Xcode 8.1 Not Autocompleting type alias callbacks -

Image
it's weird xcode (version 8.1 (8b62)) act this, not helping me auto complete callbacks, let me give specific example: see photo, when double click or enter in suggested call back, singlerequestcallback , xcode should give me block. it's not. instead xcode completing statement firebasesinglerequest.singlerequestcallback , , if double click on suggested call back, xcode give bug report in editor , making codes white. that happens in firebase library , in uiviewcontroller functions (such dismiss ). see second screenshot. steps made: clean , clean build of project. restart xcode shut down machine. so question is: how fix this? causes issue?

File reading in Java and MySQL Database -

i need project i'm working on. first part of project create utility/tool generates fake data , writes csv text file. part working fine. here's code (if helps) import sys faker import factory fake = factory.create() x = 1 param1 = int(sys.argv[1]) f = open('myfile.txt','w') x in range (0,param1): f.write(fake.first_name() + "," + fake.last_name() + "," + fake.job() + "," + fake.email() + "," + fake.street_address() + "," + fake.city() + "," + fake.state() + "," + fake.state_abbr() + "," + fake.zipcode() + "," + fake.credit_card_provider() + "," + fake.credit_card_number() + "," + fake.phone_number() + "\n") f.close() here's prints out when compiled: william,james,careers information officer,clarkjeanette@hotmail.com,9448 rodriguez brook apt. 796,south lynnbury,south carolina,va,26103,jcb 16 digit,3112583369273283,...