Posts

Showing posts from January, 2011

How to sort strings from a file by giving each line an ordered index using insertion sort in C -

i'm having trouble sorting file, giving each line index. whole point prompt user type in index program can return program line corresponds index number. here code: #include <stdio.h> #include <stdlib.h> #include <stdbool.h> void printunsortedstringfromfile(int amount, char a[]); void printsortedstringfromfile(int amount, char a[]); //bool binsearchnum(int amount, int a[amount], int target, int *current); int main() { file* spdata = fopen("grades.csv", "r"); int ch, number_of_lines = 0; { ch = fgetc(spdata); if (ch == '\n') number_of_lines++; } while (ch != eof); if (ch != '\n' && number_of_lines != 0) number_of_lines++; fclose(spdata); printf("there %d lines in file grades.csv . \n", number_of_lines); int amount = number_of_lines; char a[amount]; printunsortedstringfromfile(amount, a); printsortedstringfromfile(amoun...

haskell - Tuple evaluation -

i'm writing function of following type: match :: [(string,a)] -> maybe (string, a, a) i want function traverse list of tuples, , determine if there tuples in first element (a string) same. if so, want return tuple containing string, second element in each of matching tuples. if there no matching tuples, return "nothing". if there more 1 matching, return first 1 finds. for example: match [("x", 3), ("y", 4), ("z", "5"), ("x", 6)] = ("x", 3, 6) match [("x", 3), ("y", 4), ("z", "5")] = nothing i'm thinking: match (x:xs) = if (fst x) = (fst xs) return (fst x, snd x, snd xs) --if no matches, return nothing thank help! what if there 3 or 4 tuples "x"? can't have variable-length tuples. maybe want return list: match :: [(string, a)] -> maybe (string, [a]) what if there several tuples match? want them all, or first? if want the...

c# - Npgsql run query as readonly -

given user in connection string has write/alter/etc. permissions, there reliable way prevent data modification running user provided query? using (npgsqltransaction transaction = conn.begintransaction()) { using (npgsqlcommand setreadonlycommand = new npgsqlcommand("set transaction read only;", conn, transaction)) { setreadonlycommand.executenonquery(); } using (npgsqlcommand command = new npgsqlcommand(query, conn, transaction)) { using (var reader = command.executereader()) { //... read query results } } transaction.rollback(); } the snippet above has 2 safety nets - running in readonly transaction, , rolling transaction @ end. but both of these can overridden user adding statements "set transaction read write;" , "commit;" is there more sophisticated way of making sure ad-hoc query won't make changes db? please note not have access db itself, cannot create sps, r...

javascript - Only get Object of boxes when using QuaggaJS -

i using quaggajs . when move barcode in front of camera, results got object of boxes below instead of complete results . i tried figure out, failed. may cause this? thanks { "boxes": [ [ [77.4074243622672, 410.9288668804402], [0.050203235235130705, 310.53619724086366], [360.15706727788256, 33.05711026051813], [437.5142884049146, 133.44977990009465] ], [ [248.90769330706507, 415.2041489551161], [198.9532321622869, 352.62160512937635], [339.546160777576, 240.3979259789976], [389.5006219223542, 302.98046980473737] ] ] } the codes here: quagga.init({ inputstream : { name : "live", type : "livestream", target: document.queryselector('#myvideo') }, decoder : { readers : ["code_128_reader"] } }, function(err) { if (err) { console.log(err); return } console.log("initialization finish...

java - Better way to make a thread sleep -

i've been doing tutorial on 2d graphics in java 8, when netbeans gave me hint doing thread.sleep affect performance. however, though i've been able find several better ways, haven't been able find way include them without messing code. package platformer; import java.awt.*; import javax.swing.*; import java.util.scanner; @suppresswarnings("serial") public class platformer extends jpanel { int x = 0;//sets starting coords. of ball int y = 0; private void moveball() {//how ball moves x = x+1; y = y+1; } @override public void paint(graphics g) {//essentially al graphics functions super.paint(g); graphics2d g2d = (graphics2d) g; g2d.setrenderinghint(renderinghints.key_antialiasing, renderinghints.value_antialias_on); g2d.filloval(x, y, 30, 30); } public static void main(string[] args) throws interruptedexception { scanner reader = new scanner(system.in);...

windows - Register-ScheduledJob as the system account (without having to pass in credentials) -

i believe register-scheduledtask can specify -user "system" or like: $principal = new-scheduledtaskprincipal -userid system -logontype serviceaccount -runlevel highest how do register-scheduledjob ? this command running context of local admin have access this. don't see option in cmdlet. here example of how scheduled tasks cmdlet edit: windows make impossible design? if open interactive ps session system (using psexec) , try create schedualed job error: ps c:\windows\system32> register-scheduledjob -name systemsssss -scriptblock {'s dfsdfsdfsd'} register-scheduledjob : error occurred while registering scheduled job definition systemsssss windows task scheduler. task scheduler error is: (32,4):userid:. @ line:1 char:1 + register-scheduledjob -name systemsssss -scriptblock {'sdfsdfsdfsd'} + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : invalidoperation: (microsoft.power...edjobdefini ...

Persisting state to attached disks in Azure Service Fabric -

i can create virtual machine scale set attached disks, thereby adding virtually unlimited cheap storage potential cluster. however, default azure service fabric stores data on os drive. how can override that? correction: azure service fabric stores data on temporary disk (the d: drive), not os disk. still desire ability select different (larger) disk. my service not candidate "packing" yet -- @ time not have mix of compute-heavy , storage-heavy services share larger vm size, , cost primary concern.

HAproxy site failing login -

i have security cam application. ic realtime nvr-604v. nvr has web interface http on port 8888. not trying load balance anything. have number of offices these , using haproxy route based on url specific nvr , use ssl termination on haproxy backend uing port 8888 unencrypted. routing, ssl termination, , https redirect work. i can't login. login failed web application when routing through haproxy, going direct ip works fine. any ideas? global log /dev/log local0 log /dev/log local1 notice chroot /var/lib/haproxy stats socket /run/haproxy/admin.sock mode 660 level admin stats timeout 30s daemon maxconn 2048 # default ssl material locations tune.ssl.default-dh-param 2048 ca-base /etc/ssl/certs crt-base /etc/ssl/private ssl-default-bind-ciphers ecdh+aesgcm:dh+aesgcm:ecdh+aes256:dh+aes256:ecdh+aes128:dh+aes:ecdh+3des:dh+3des:rsa+aesgcm:rsa+aes:rsa+3des:!anull:!md5:!dss ssl-default-...

node.js - How do I resolve these grunt errors in this aws tutorial? -

i'm working way through aws + grunt-aws-lambda + jenkins tutorial at: https://aws.amazon.com/blogs/compute/continuous-integration-deployment-for-aws-lambda-functions-with-jenkins-and-grunt-part-1/ i able complete tasks through grunt lambda_invoke step. however, when try grunt deploy, task fails. here excerpt receive warning , failure messages: running "lambda_package:default" (lambda_package) task verifying property lambda_package.default exists in config...ok **file: [no files]** options: dist_folder="dist", include_time, package_folder="./", include_files=[] reading /users/user/documents/create-thumbs-lambda/package.json...ok parsing /users/user/documents/create-thumbs-lambda/package.json...ok create-thumbs-lambda@1.0.0 ../../../../var/folders/01/xxx/t/xxx.1516/node_modules/create-thumbs-lambda ├── async@0.9.2 └── gm@1.23.0 (array-series@0.1.5, array-parallel@0.1.3, debug@2.2.0, cross-spawn@4.0.2) created package @ ./dist/create-thumbs-la...

service - How do I change a target's wrapper extension in xcode 8.1? -

i developing standalone service outlined here: http://www.notesfromandy.com/2013/04/05/writing-a-service-bundle/ the author recommends change wrapper extension .service under project menu, in xcode 8 functionality has been moved/removed. how go changing setting in xcode 8.1? i found it. click on project name on left hand side under project navigator, select build settings , cmd+f wrapper. listed there editable attribute.

python - Flask server returns 404 on localhost:5000 w/ Twilio -

i'm following this guide (python quickstart: replying sms , mms messages) try , set flask server, when try connect http://localhost:5000 404 error. can ping 127.0.0.1 no problem. code: from flask import flask, request, redirect import twilio.twiml app = flask(__name__) @app.route("/", methods=['get', 'post']) def hello_monkey(): """respond incoming calls simple text message.""" resp = twilio.twiml.response() resp.message("hello, mobile monkey") return str(resp) if __name__ == "__main__": app.run(debug=true) console output: * running on http://127.0.0.1:5000/ (press ctrl+c quit) * restarting windowsapi reloader localhost 404'ing i can connect http://127.0.0.1:5000/ after restarting computer. not sure causing issue.

html - Weird Ghost CSS Bug -

how possible whole website works without css file styles? have line in header: <link rel="stylesheet" type="text/css" href="styles.css" /> i deleted styles.css file server, nothing changed. if delete line header there no styles (as expected) at 1 point noticed none of css changes make have effect, made sure i'm not doing dumb editing or referencing wrong file , there not 2 copies of reason. if change other html files, can see effects, not styles file. i can force work renaming css file, don't want that. has seen happen before? this because caching of css. try clearing cache of browser. you can prevent css caching below way <link rel="stylesheet" type="text/css" href="style.css?v=1" /> using php can trick <link rel="stylesheet" type="text/css" href="style.css?<?php echo date('l js \of f y h:i:s a'); ?>" />

javascript - Error while trying to create a Facebook chat monitor google chrome extension -

i'm trying create extension google chrome allow me read facebook page's conversations(messages). right now, i'm having trouble logging facebook using chrome extension. i'm getting error "can't load url: domain of url isn't included in app's domains. able load url, add domains , subdomains of app app domains field in app settings." don't have clear idea on how proceed. can please point out what's wrong or can suggest better alternative reading facebook page's conversations using graph api in google chrome extension. or is possible firefox add-on? code i'm using manifest.json { "name": "facebook connect chrome extension", "version": "1.0", "description": "this plugin showing how facebook connect/graph api works on chrome extension.", "content_security_policy": "script-src 'self' https://connect.facebook.net; object-src 'self'", ...

javascript - How do I create a constantly updating Geojson server? -

i using leaflet api. coded out map , have code geojson map. don't know code need create on other server. want leaflet api/my code able pull location other server onto map in real time. want use same basic code website doing: http://www.tagkartan.se/ here basic example of code: var map = l.map('map'), realtime = l.realtime({ url: 'https://wanderdrone.appspot.com/', crossorigin: true, type: 'json' }, { interval: 3 * 1000 }).addto(map); realtime.on('update', function() { map.fitbounds(realtime.getbounds(), {maxzoom: 3}); }); ^^but pulling wanderdrone.appspot.com website. how set own website pull location many different phones @ on time , have them sync in real time on map? know need little javascript/html after that. don't understand how pull location 1 server , have leaflet map replicate location on map. in advance!

javascript - Binding the scope with side menu does not work - ionic -

i want show 2 different ion-list on menu according user "role" in app. app.js .state('app', { url: '/app', abstract: true, cache: false, templateurl: 'templates/menu.html', controller: 'appctrl' }) appctrl .controller('appctrl', function($scope) { // example $scope.user = { name: "example", role: "client" }; }) menu.html <ion-list ng-if="user.role == 'manager' "> <ion-item menu-close href="#/app/search"> manager </ion-item> <ion-item menu-close href="#/app/songbook"> item </ion-item> </ion-list> <ion-list ng-if="user.role == 'client' "> <ion-item menu-close href="#/app/search"> client </ion-item> <ion-item menu-close href="#/app/search...

gradle - Android Studio error -

i started learning , trying develop android apps.(total beginner, im in "hello word" stage) android studio keeps hitting errors. error when start new project. error:unable start daemon process. problem might caused incorrect configuration of daemon. example, unrecognized jvm option used. please refer user guide chapter on daemon @ https://docs.gradle.org/2.14.1/userguide/gradle_daemon.html please read following process output find out more----------------------- error occurred during initialization of vm not reserve enough space 1572864kb object heap i cant find way around this. you need change graddle.properties file xmx1024m can find solution in video https://www.youtube.com/watch?v=ht3shxvwjiu

c++ - Having problems creating function that copies linked list while in template -

assignment make list of integers , functions various things. finished one. after figured out how make function searches list specific value , node, have make function duplicates said list. however, i'm having serious trouble doing material have right now. this class i'm working (t template) template <class t> class integerlist{ private: struct listnode { t value; struct listnode *next; }; listnode *head; public: //this constructor. integerlist() {head = null;} //destructor ~integerlist(); void appendnode(t); void insertnode(t); void deletenode(t); void searchnode(t); void duplicatenode(t); void displaylist() const; }; the functions far: //==appendnode definition== template<class t> void integerlist<t>::appendnode(t newvalue) { listnode *newnode; listnode *nodeptr; newnode = new listnode; newnode->value = newvalue; newnode->next =...

c++ - How to fix terminate called after throwing an instance of std::out_of_range -

here message: terminate called after throwing instance of 'std::out_of_range' what(): basic_string::erase: __pos (which 18446744073709551615) > this->size() (which 22) aborted (core dumped) and below code far (it's supposed reformat names , dates , amounts in scrambled data file looks like: foster, jerry lee 1995 329,475 //this program reformats retirement account data file oldretirement.txt , outputs data new file newretirement.txt #include<iostream> #include<cstdlib> #include<fstream> #include<cctype> #include<string> #include<cstring> #include<cstddef> using namespace std; void getridof(string &line); int splitamount(string &line); int splityear(string &line); string splitfullname(string &line); int main(){ ifstream fin; ofstream fout; string line; string finalname; size_t found; int finalamount; int finalyear; fin.open("oldretirement.txt"); if(fin.fail()) {cou...

MRTG and/or rrdtool - one minute interval not working -

i testing mrtg 2.17.4 on ubuntu 16.04. configured use rrdtool log data. have "interval: 1" in /etc/mrtg.cfg. edited cron job @ /etc/cron.d/mrtg be: */1 * * * * root if [ -x /usr/bin/mrtg ] && [ -r /etc/mrtg.cfg ] && [ -d "$(grep '^[[:space:]]*[^#]*[[:space:]]*workdir' /etc/mrtg.cfg | awk '{ print $nf }')" ]; mkdir -p /var/log/mrtg ; env lang=c /usr/bin/mrtg /etc/mrtg.cfg --debug="time,log" 2>&1 | tee -a /var/log/mrtg/mrtg.log ; fi please note added debug option "time,log" troubleshoot. in /var/log/mrtg/mrtg.log, see data logged every 1 minute expected, not try calculate throughput every minute. instead, every 5 minutes. other times, says "got ???/???" --time: prog start sat nov 12 21:54:01 2016 --time: loop start sat nov 12 21:54:01 2016 --time: snmp read start sat nov 12 21:54:01 2016 --time: target loop start sat nov 12 21:54:01 2016 --log: rrds::tune(/var/mrtg/192.168.1.40_24.r...

url rewriting - IIS URL Rewrite Issue, excluding CSS,JS -

i rewriting subdomain remote url. user requests subdomain (e.g., xyz.domainone.com, rewritten domaintwo.com/webdite/xyz/) i can see working fine, css , js files not working have relative paths , searched in subdomain. tried rules no success. rule below: <rewrite> <rules> <rule name="ignore" enabled="true" stopprocessing="true"> <match url="^(.*/)(images|css|js).*"/> <conditions logicalgrouping="matchall" trackallcaptures="false"/> <action type="none"/> </rule> <rule name="domain redirect" stopprocessing="true"> <match url="^(.*)$" /> <conditions logicalgrouping="matchall"> <add input="{http_host}" pattern="^(.+)\.domainone\.com$" /> </conditions> <action type="rewrite" url="http://domain2.com/websit...

objective c - iOS - An NSArray of a single NSData object saved in NSUserDefault come out to be NSData? -

i'm saving customized class deviceinfo in nsdefault. i used nskeyedarchiver archive object nsdata object. as want save array of deviceinfo objects nsuserdefault , put archived objects nsarray . however, seems that, when there's 1 nsdata object in array, nsdata object while should nsarray object when fetch nsuserdefault . why that? here's code. nsdata* data = [nskeyedarchiver archiveddatawithrootobject:_deviceinfo]; nsmutablearray *temp = [nsmutablearray new]; temp = [[sdgriditemcachetool itemsarray] mutablecopy]; //[[sdgriditemcachetool itemsarray]] method fetch array, paste code below. [temp addobject:data]; [sdgriditemcachetool saveitemsarray:[temp copy]]; and code save , fetch data nsuserdefault //sdgriditemcachetool.m + (nsarray *)itemsarray { return [[nsuserdefaults standarduserdefaults] objectforkey:kitemsarraycachekey]; } + (void)saveitemsarray:(nsarray *)array { [[nsuserdefaults standarduserdefaults] setobject:[array copy] for...

angularjs - Angular JS with Dialog, Tabs and fixed footer -

having issue i'm trying use angular material, tabs , dialog. what i'm looking for, have dialog tabs displayed inside. within that, want first tab fill 100% of height (minus tab header, , class added "footer". here plnkr started, stuck can't list items take of height. http://plnkr.co/edit/2szjqpamfxf4utyqo1x1?p=preview if scroll down list on tab 1, you'll see "footer", want not scrollable @ all. item fixed bottom of dialog. <md-dialog aria-label="mango (fruit)"> <md-dialog-content> <div class="md-dialog-content"> <md-tabs> <md-tab label="first tab"> <md-content flex> <md-list flex> <md-item ng-repeat="item in items"> <md-item-content> <div flex class="md-tile-content"> {{item}} </div> ...

ios - Firebase Saving Data Methods Asynchronous or Synchronous -

are firebase saving data methods such childbyautoid , updatechildvalues asynchronous or synchronous? there seems no place pass in completion handler i'm guessing synchronous i'm not sure because seems little weird (for performance purposes) firebase make such commonly needed methods synchronous. as of modern web, interacting firebase database asynchronous operation. that's why methods in firebase database api can take completion block. for write operations block optional, because there cases when may not want specify completion block. for example, here's api reference doc updatechildvalues:withcompletionblock : updatechildvalues:withcompletionblock: swift func updatechildvalues(values: [nsobject : anyobject], withcompletionblock block: (nserror?, firdatabasereference) -> void) parameters values - dictionary of keys change , new values block - block triggered after update has been written on firebase database serv...

java - NDS Open Lane Model -

anybody having working knowledge on nds open lane model? how setup workspace? any further documentation or tuts on nds open lane model apart given link https://olm.nds-association.org/ thanks in advance

c# - Program Issues Going From Unity To HoloLens - Cannot convert from 'string' to 'System.IO.Stream' -

i have program written in unity using c# initializes new streamreader , proceeds read text data text file have stored in unity's resources folder. works fine when click play in unity -everything works , text read , displayed perfectly. however, when try build in order run via hololens emulator (platform: windows store, sdk: universal 10, build , run on: local machine), error: error cs1503: argument 1: cannot convert 'string' 'system.io.stream'. i don't understand why error showing in first place constructor streamreader has overload accepts string parameter. my code follows: string metadata = string.format("/resources/.../metadata.txt", list); if (file.exists(application.datapath + metadata)) { using (streamreader sr = new streamreader(application.datapath + metadata)) { // .... } } i agree others, caused diffence between mono in editor , .net compiling uwp application. try instead: ...

How to create a public cython function that can receive c++ struct/instance or python object as parameter? -

my rectangle.h namespace shapes { class rectangle { public: int x0, y0, x1, y1; rectangle(); rectangle(int x0, int y0, int x1, int y1); ~rectangle(); int getarea(); }; } my rectangle.cpp #include "rectangle.h" namespace shapes { rectangle::rectangle() { } rectangle::rectangle(int x0, int y0, int x1, int y1) { x0 = x0; y0 = y0; x1 = x1; y1 = y1; } rectangle::~rectangle() { } int rectangle::getarea() { return (x1 - x0) * (y1 - y0); } } my rect.pyx # distutils: language = c++ # distutils: sources = rectangle.cpp cdef extern "rectangle.h" namespace "shapes": cdef cppclass rectangle: rectangle() except + rectangle(int, int, int, int) except + int x0, y0, x1, y1 int getarea() cdef class pyrectangle: cdef rectangle c_rect def __cinit__(self, int x0, int y0, int x1, int y1): self.c_rec...

java - One of my Inputs is skipped -

i have assignment need use bufferedreader, system.in.read() thrown exception , system.in.read() catch , try. have far. import java.io.*; public class test { public void bufferedreader() throws ioexception { bufferedreader in = new bufferedreader (new inputstreamreader(system.in)); string expr = new string(); system.out.print("input: "); expr = in.readline(); system.out.println("output: " + expr); system.out.println("------------------------------------------"); } public void throwexception() throws ioexception { int eingabe=20; system.out.print("\ninput"); eingabe=system.in.read(); system.out.println("\n" + (char)eingabe); system.out.println("------------------------------------------"); } public void exception() { int i=32; system.out.print("\neingabe "); try { ...

Curious case of type of 2 in haskell -

what rationale behind assigning general type num => a 2 instead of defaulting specific type int or integer ? secondly have read @ many places 2 polymorphic value definition of polymorphism doesn't admit constrained variables. 2 polymorphic in haskell? 2 polymorphic can use whatever type of number like. num type class has function frominteger , used here. 2 frominteger (2 :: integer) . if 2 not polymorphic have write if wanted non-integer number, because there no automatic coercion in haskell (i.e. can't (1 :: integer) + (1 :: int) ). case fractional fromrational way. polymorphic type variables can have constraints. if not have constraints, called parametric polymorphism , if constrained , bounded parametric or ad-hoc polymorphism . see haskellwiki article on polymorphism . be aware, should not rely on type inference top-level functions or else may fall trap monomorphism restriction . example if write @ top-level of module: polymorphic = 42 ...

java - Regex to match word surrounded by non-alphanumeric characters -

Image
i want match , find index of word either surrounded space or special characters. example: to find: test input test : true is#input_ : true isinput : false thisisinputtest: false @test right: true. how match , find index. current regex fails: (?i)[^a-za-z0-9]test[^a-za-z0-9] i think need use lookarounds in case: (?<!\p{alnum})test(?!\p{alnum}) the negative lookbehind (?<!\p{alnum}) fail match if there alphanumeric char present left of test , , negative lookahead (?!\p{alnum}) fail match if there alphanumeric char right after test . see testing screenshot: java demo : string str = "this is#test_ :"; pattern ptrn = pattern.compile("(?<!\\p{alnum})test(?!\\p{alnum})"); matcher matcher = ptrn.matcher(str); while (matcher.find()) { system.out.println(matcher.start()); } alternative way: match , capture search word, , print start position of 1st capturing group: pattern ptrn = pattern.compile("\\p{alnum}(test)\\p{alnum}...

scala - Specify attribute value on constructor -

i´ve been looking this, not find anything. if have class class a(a1:int, b1:int,c1:int){} i can not create instance specifying 1 of values of constructor in groovy right?. new a(b1:1) you can provide default values class parameters: // add default values class parameters class a(a1: int = 0, b1: int = 0, c1: int = 0) // call constructor passing parameters of choice val = new a(b1 = 1)

c# - Registered Voice Control Definition file doesn't seem to work -

i registering following vcd.xml file in c# windows 10 universal application, can't cortana respond them, bing searches every time. <?xml version="1.0" encoding="utf-8"?> <voicecommands xmlns="http://schemas.microsoft.com/voicecommands/1.2"> <commandset xml:lang="en-us" name="universalappcommandset_en-us"> <appname> spang </appname> <example> tell me time </example> <command name="telltime"> <example> tell me time </example> <listenfor requireappname="beforeorafterphrase"> tell me time </listenfor> <feedback> getting time you. </feedback> <navigate/> </command> </commandset> </voicecommands> i'm registering in onlaunched, per microsoft directions. try { // install main vcd. storagefile psfevcd = await storagefile.getfilefr...

server - Cannot connect to Tigase Admin panel? -

i using tigase xmpp server, server parameters have set are: jabber domain name: chat.example.com >> public dns administrator:admin@chat.example.com admin password: tigase after installation, can access admin panel url: http://localhost:8080/ui/ , unfortunately can't login username , password have created during installation process. makes me crazy, please help. point that, can login server android client above username , pass, when delete , reinstall tigase , set domain ip address of computer in internal network it's working, when use dns looks cannot login admin environment username , password. you can find answer @ post: https://projects.tigase.org/boards/15/topics/6939?r=6942

R: Find optimal sub-matrix -

i have large symmetric matrix , want reduce smaller matrix matrix_small rows(matrix_small) = n. mean of matrix_small should maximized. is there way achieve goal in r better algorithm have? better either faster same mean or higher mean same speed. i feel there should smarter way search min often. i'm not aware of way set sql-like index matrix in r increase performance. library(microbenchmark) set.seed(2016) sym_matrix <- matrix(runif(1e+06), ncol = 1000) sym_matrix[lower.tri(sym_matrix)] <- t(sym_matrix)[lower.tri(sym_matrix)] diag(sym_matrix) <- na rownames(sym_matrix) <- 1:1000 colnames(sym_matrix) <- 1:1000 findnrows <- function(sym_matrix, nrows){ # return matrix rows(matrix) = nrows. # mean(matrix) should maximized set.seed(2017) k <- nrow(sym_matrix) (i in nrows:(k-1)) { #eliminate rows minimum values min_rows <- arrayind(which.min(sym_matrix), dim(sym_matrix)) choose_row <- sample(min_rows, 1) sym_matrix <- sym_matri...

ios - OR statement in the arguments of method -

i have method this: -(void)examplesend:(nsstring *)gateway byparams:(nsdictionary *)params{ ... } now want change params , input argument, support both nsdictionary , nsarray . how can in objective-c ? change type id instead of nsdictionary , make sure should check inside method if nsdictionary or nsarray before performing class specific actions on it, otherwise cause crash. -(void)examplesend:(nsstring *)gateway byparams:(id)params{ if([params iskindofclass:[nsdictionary class]]){ }else{ } ... }

java - how can i create a JSON object from different tables( MySQL database) to consume in android project? -

this api. how can have results converted json object using java? $sql1="select s.* , c.*,u.* schedule_ s,course_t c, u user_t c.course_crn=p.course_crn , s.teacher_id=u.employee_id" ; $result=mysqli_query($con,$sql1); if($result) { while($row=mysqli_fetch_array($result)) { $data[]=$row; } print(json_encode($data)); you need following load mysql driver: class.forname("com.mysql.jdbc.driver"); // need include , load jdbc driver create connection credentials, host , port: string url = "jdbc:mysql://mysql_host:mysql_port/mysql_db"; string user = "mysql_user"; string pass = "mysql_pass"; connection conn = drivermanager.getconnection(url, user, pass); execute sql query: string sql = "select s.* , c.*,u.* schedule_ s,course_t c, u user_t c.course_crn=p.course_crn , s.teacher_id=u.employee_id;"; preparedstatement preparedstatement = conn.preparest...

sql - Rails 4: Multi-level joins with ActiveRecord -

i adding layer of complexity data model. previously: country had many stores, in turn had many products. i introducing cities that: country has many cities have many stores have many products. the data work contains stores may not have products (yet), cities may not have stores (yet) , countries may not have cities (yet). i want query countries in find products. (i.e. can fill landing page countries makes sense user stuff.) previously (with country > store > product), used this, , worked well: country.joins(:stores => :products).group("countries.id").having("count(products.id)>0") but cannot head around additional layer (country > city > store > product). instance, doesn't work: country.joins(:cities => :stores).joins(:stores => :products).group("countries.id").having("count(products.id)>0") ...yielding error: activerecord::configurationerror: association named 'stores' not found on ...

I'm getting this error using Java Mail API -

sun nov 13 16:20:41 pkt 2016 warn: establishing ssl connection without server's identity verification not recommended. according mysql 5.5.45+, 5.6.26+ , 5.7.6+ requirements ssl connection must established default if explicit option isn't set. compliance existing applications not using ssl verifyservercertificate property set 'false'. need either explicitly disable ssl setting usessl=false, or set usessl=true , provide truststore server certificate verification. javax.mail.authenticationfailedexception: [alert] please log in via web browser: https://support.google.com/mail/accounts/answer/78754 (failure) @ com.sun.mail.imap.imapstore.protocolconnect(imapstore.java:665) @ javax.mail.service.connect(service.java:295) @ javax.mail.service.connect(service.java:176) @ sentitems.initialize(sentitems.java:229) @ sentitems.<init>(sentitems.java:111) @ sentitems$1.run(sentitems.java:98) @ java.awt.event.invocationevent.dispatch(unknown sourc...

c - Program cannot match datas in variables -

this question has answer here: how compare strings? 6 answers this part of 'phonebook' program. void viewone(){ char name[25], fname[25]; int n, ncheck, op; fp = fopen("phonebook.txt","r"); printf ("\n search : \n 1: name\n 2: phone number\n"); printf ("enter option : "); scanf ("%d",&op); switch(op){ case 1: printf ("\n enter name : "); scanf ("%s",name); fscanf(fp, "%s %d", fname, &ncheck); while (!feof(fp)){ printf ("\n\n %s \n\n",fname); if (fname == name){ \\ problem in here printf ("\n\n contact found...\n"); printf (" %s +880%d", fname, ncheck); ...