Posts

Showing posts from January, 2011

Sorting a String Array Alphabetically C++ -

i'm trying write program given following structures: struct aplayer { string name; // name of player int wins; // number of wins player has }; struct acompetition { string name; // name of match int numplayers; // number of players in club aplayer player[10]; // list of players in club }; from there want write function sort players name alphabetically. function declaration follows: void sortbyname(acompetition & c){} note: using loops, while loops, , if statement(s). way think compare 2 strings compare ascii values. i'm not sure how input appreciated. thanks! assuming homework (and if it's not, doing lot more seeing answer,) i'm going give few pointers out. compare ascii values: aplayer player1, player2; player1.name = "bill"; player2.name = "john"; if (player1.name[0] < player2.name[0]) { // true, in case, because b less j on ascii table. } http://www.

Firebase Admin SDK causing build error in React -

i added firebase admin sdk react project (i used create-react-app if makes difference). i'm testing out initialize firebase in index.js import react 'react'; import reactdom 'react-dom'; import app './app'; import './index.css'; var admin = require("firebase-admin"); var serviceaccount = require("./serviceaccountkey.json"); admin.initializeapp({ credential: admin.credential.cert(serviceaccount), databaseurl: "https://<app-name>.firebaseio.com/" }); reactdom.render( <app />, document.getelementbyid('root') ); everything else in project untouched. go run npm run build can deploy project firebase hosting , following failed compile error module not found: error: cannot resolve module 'request' in /home/ubuntu/workspace/shelf/node_modules/firebase-admin/lib/database any ideas issue here or should solve it? thanks!

javascript - Ajax on Rails How to use Ajax append method for render HTML? -

i not english speaker.i ask of understanding.sorry /app/views/sale/index.html.erb want ajax here <div class="col-lg-4" style="padding:5px;" id=reply_preview> <%= render 'sale/billpreview'%> </div> this button sending data <button type="submit" class="btn btn-defalut reply_sale" value="<%= m.id %>" name="menuid" script <script> $(".reply_sale").click(function(){ send_value=this.value; $.ajax({ method: "post", url: "/sale/billpreview", data: { menuid : send_value }, datatype : 'json' }) .done(function() { $( "#reply_preview" ).append( "<%= render 'sale/billpreview'%>");// <-- error point }); }); </script> here error point $( "#reply_preview" ).append( "<%= render 'sale/billpreview'%>");// <-- error point wha

javascript - FullCalendar moment.js. When check if clicked date (tomorrow) isBefore() today, return true -

i'm doing calendar full calendar , moment. j's. when click on past day or today, it's supposed return true". if clicked date in future, return false. so, when click on current date (2017-04-06), it's returning true. if click on date after tomorrow (2017-04-08), it's returning false. but, if click on tomorrow date (2017-04-07), it's returning true. there code: ... dayclick: function(date, allday, jsevent, view) { var currentdate = moment(); var clickeddate = date; if(clickeddate.isbefore(currentdate)){ console.log(clickeddate.date()); console.log(currentdate.date()); console.log("true"); } else { console.log(clickeddate.date()); console.log(currentdate.date()); console.log("false"); } }, ...

'hasOwnProperty' in javascript -

i use obj.hasownproperty judge whether object has property, when replaced obj[prop] !== undefined , not normal implementation, ask, why behind method can not use it? object.hasownproperty(prop); object[prop] !== undefined; obj[prop] !== undefined wrong 2 reasons: you can explicitly set property undefined , obj[prop] = undefined; . obj.hasownproperty(prop) return true in case. obj[prop] follow prototype chain, return property that's inherited. obj.hasownproperty(prop) returns true if property exists directly in object, returns false inherited properties.

azure - Is it normal to return actor's proxy from service -

i have service accepts data , then, think, should return actor initialized values. public class myservice : statefulservice, imyservice { public imyactor dothings(data data) { var actor = actorproxy.create<imyactor>(new actorid(guid.newguid())); actor.init(data); //some other things return actor; } } another service this: var service = serviceproxy.create<icommandbrokerservice>(new uri("fabric:/app"), servicepartitionkey.singleton); var actor = service.dothings(data); var state = actor.getstate(); //... so, okay return actor in such way, or should return actor's id , request proxy on call sight? upd: according @loekd 's answer did wrapper little type-safety. [datacontract(name = "actorreferenceof{0}wrapper")] public class actorreferencewrapper<t> { [datamember] public actorreference actorreference { get; private set; } public actorreferencewrapper(actorreference acto

html - PHP Contact Form 403 Error -

in process of setting website myself, i've hit bit of road block php contact form. believe coded correctly, whenever upload site , try use contact form "page forbidden 403". i'm using hostinger way, i've set permissions of public_html file 755. not sure problem be. included code, appreciated. contact code of html index: <div class="row stay-behind" id="contact"> <h4 class="right-name">contact</h4> <div class="col-md-1"></div> <div class="col-sm-12 col-md-4 feature-image"><img alt="vx1k" height="510" src="images/ux/004.jpg" width="374"> <img alt="vx1k" class="mobile-only" src="images/ux/mobile/004.jpg"></div> <div class="col-sm-12 col-md-6 main"> <h3 class="title">contact</h3> <form class="contact-form" id=&quo

python - Merge two dataframe in pandas -

i merging 2 csv(data frame) using below code: import pandas pd = pd.read_csv(file1,dtype={'student_id': str}) df = pd.read_csv(file2) c=pd.merge(a,df,on='test_id',how='left') c.to_csv('test1.csv', index=false) i have following csv files file1: test_id, student_id 1, 01990 2, 02300 3, 05555 file2: test_id, result 1, pass 3, fail after merge test_id, student_id , result 1, 1990, pass 2, 2300, 3, 5555, fail if notice student_id has 0 appended @ beginning , it's supposed considered text after merging , using to_csv function converts numeric , removes leading 0. how can keep column "text" after to_csv? i think to_csv function saves again numeric added dtype={'student_id': str} while reading csv.. while saving to_csv .. again convert numeric solution join , first need read_csv parameter dtype convert student_id string , remove whitespaces skipinitialspace : df1 = pd.read_csv(file1, dtype={'stu

performance - JS DOM elements’ content-string properties: memory management and computation in current engines -

in dom, node , element types have many dynamic properties, e.g., node.textcontent , element.innerhtml , return string representations of nodes’ contents. the dom specifications state these methods “return” domstrings , i.e., string s. they, of course, not specify when , how these strings allocated , computed. text nodes, implementation can return plain-text string content directly. element s must create new strings contain tags , contents of descendant elements. as far can tell, implementation may allocate memory these strings , compute values @ 4 points: immediately, when element first created; lazily, scheduled sometime after element ’s creation; lazily, on demand @ point when getting string property element ; or lazily, on demand whenever string first used (i.e., returned string uses special, externally indistinguishable implementation returned element ’s string properties dynamically generates value when needed). these methods determine when strings’ memory fre

vba - Goalseek over range of values not running -

i have problem code. when hit run, nothing happens. whats wrong? i'm changing variables on range g53:n53 , f54:f64 , looping change c54 0 while changing c59, , i'm pasting around matrix g54:n64. but not running! private sub checkgoalseek() dim integer, j integer = 54 64 j = 7 14 cells(60, 3).value = cells(53, j).value cells(61, 3).value = cells(i, 6).value range("c54").goalseek goal:=0, changingcell:=range("c59") cells(59, 3).copy cells(i, j).pastespecial paste:=xlpastevalues next j next end sub

c# remove trailing 0 for INR currency conversion? -

i use following code convert input comma separated string in inr: decimal input = 1111111111.59m; string result = input.tostring("c", new cultureinfo("en-in")); i want remove trailing 0s now, how do this? for example: decimal input = 1111111111.00m; output should 1111111111 string result = input.tostring("c0", new cultureinfo("en-in")); update: so want output "123.45" input 123.45 , output "123" input 123.00. can't achieve these 2 different formats without conditional operator, string.format() produce 1 output format you. the code simple though: string format = decimal.round(input) == input ? "c0" : "c"; string output = input.tostring(format);

javascript - Facebook Graph API /me/accounts not working in code -

i trying update page details sample site. implemented same previously. got access token of page /me/accounts. now, /me/accounts returning empty set in javascript code. getting correct response in graph api explorer. ps: able page details using auth token. problem /me/accounts returning empty array.

I wrote a code to upload file using spring mvc.not showing any errors or warning but still getting 404 error after compiling it -

i wrote code upload file in directory named images. every time run on eclipse using apache tomcat 7 gives me http status 404 - /fileupload/. using maven plugin in eclipse build spring framework. gives build success. while compiling apache , running on server there http error 404. have attached jsp codes , xml codes along question. please help pom.xml <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion> <groupid>com.upload</groupid> <artifactid>fileupload</artifactid> <version>0.0.1-snapshot</version> <packaging>war</packaging> <build> <sourcedirectory>src</sourcedirectory> <plugins> <plugin> <artifactid>maven-compiler-plugin</ar

Can somebody help me to access facebook SCIM api in asp.net application for custom integration -

public string getuserdata(string access_token, string scimurl) { string endpoint= scimurl; string userdatainjson = getpageddata(access_token, endpoint); return userdatainjson; }private string buildheader(string access_token) { return "authorization:bearer " + access_token; }public string getpageddata(string access_token, string endpoint) { httpwebrequest http = (httpwebrequest)httpwebrequest.create(endpoint); string header = buildheader(access_token); http.headers.add(header); httpwebresponse response = (httpwebresponse)http.getresponse(); string responsejson = ""; using (streamreader sr = new streamreader(response.getresponsestream())) { responsejson = sr.readtoend(); } return responsejson; } this code using access facebook scim api user data facebook workplace, not able access scim api

html - Applying attributes to a video -

html, body { height: 100%; width: 100%; margin: 0; padding: 0; } .wrap { height: 100%; width: 100%; background-size: cover; position: relative; overflow: hidden; background: #000; color: #000; text-align: center; font-family: arial, san-serif; } header { background: #3e474f; box-shadow: 0 .5em 1em #111; position: absolute; top: 0; left: 0; z-index: 900; width: 100%; } header label { color: #788188; cursor: pointer; display: inline-block; line-height: 4.25em; font-size: .677em; font-weight: bold; padding: 0 1em; } header label:hover { background: #2e353b; } h1 { font-size: 300%; } .slide { height: 100%; width: 100%; position: absolute; top: 0; left: 100%; z-index: 10; padding: 8em 1em 0; background-color: #120103; background-position: 50% 50%; background-size: cover; } .slide-one { background-image: url('jupiter.jpg'); }

html - PHP Contact form not sending email. Not sure if syntax or Server -

hey guys have html document contact form created , not working. have php in seperate php file so: html: <form class="form-horizontal" action="form_process.php" method="post" name="contact_form"> <div class="form-group"> <label class="col-sm-2 control-label white-color">email</label> <div class="col-sm-10"> <input type="email" class="form-control" name="email" placeholder="email" required> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label white-color">name</label> <div class="col-sm-10"> <input type="text" class="form-control" name="name" placeholder="first name" required> </div> </div> <div cla

Sum of n numbers result is wrong in Scala -

i reading comma-separated numbers text file , performing addition of numbers in file - sum i'm getting wrong. input file 1,2,3 source code val file=source.fromfile("d:/scala/test.txt") val f1=file.foldleft(0)((a,b)=>a+b) println(f1) output 238 i can perform addition on array , works fine, can't correct answer when reading data file. a source iterator[char] , foldleft operating on char s. when add 2 chars + , you're adding decimal values. your source reading every character file, including commas. if @ ascii chart, you'll see decimal value of comma (i.e. , ) 44, , 1, 2, , 3 49, 50 , 51 respectively. this gives 44 + 44 + 49 + 50 + 51 = 238 , result you're seeing. what want this: read file string split string on commas convert each of result strings int sum resulting integers which can written as source.fromfile("d:/scala/test.txt").mkstring.split(',').map(_.toint).sum or source.fromfi

css - image-block and title-block are not responsive -

i have responsive problem on wordpress website. when website on fullscreen, products centered ( http://prnt.sc/et1k5q ). when put smaller products no longer in middle ( http://prnt.sc/et1klx ). i'm using "col-xs-12 col-sm-6 col-md-4 col-lg-3 col-centered" this. products not image, "image-block" , "title-block". what need change? *the template using bootstrap just add class 'text-center' , center align things.

ios - Xcode 8.3 breaks my app -

the official release of xcode 8.3 causes app freeze after apparently random amount of time. causes network connections never finish (which may reason eventual freeze? deadlock waiting resources released maybe?). the exact same code works fine when compiled xcode 8.2.1. anyone has same problem? xcode 8.3.1 available. https://developer.apple.com/news/?id=04062017a due resolved app archives issue listed below, deprecating xcode 8.3, @ time app archives built xcode 8.3 no longer accepted app store. try updating xcode there number of issues in previous version.

r - Pass population to Genetic Algorithm -

i have started learning ga in r . given have below function: f <- function(x) (x^2+x)*cos(x) min <- -10; max <- 10 curve(f, min, max, n = 1000) i know, can call ga on using below code: library(ga) ga <- ga(type = "real-valued", fitness = f, min = min, max = max,monitor =false) summary(ga) but now, i wondering if can pass vector containing 300 values, and ask ga to randomly select 100 out population(300)? point: have read ga_lrselection , don't know how use them

Circular dependency c++ fails with forward decleration -

Image
i have 2 classes, meassurementiteration , meassurementset. meassurementiteration has vector of sets, , set has pointer iteration. meassurementiteration #pragma once #include <vector> #include "meassurementsetrepo.h" #include "meassurementset.h" class meassurementiteration { public: meassurementiteration(const int id, const long start, const long end, const bool active) : id_(id) , start_(start) , end_(end) , active_(active) {} meassurementiteration(); ~meassurementiteration() = default; std::vector<meassurementset>& getmeasurementset() { /** magic **/ return this->mssets_; } private: const int id_; const long start_; long end_; bool active_; meassurementsetrepo mssetrepo; std::vector<meassurementset> mssets_; }; meassurementset

javascript - AWS get secret key from an environment variable -

i using aws.config.update in javascript file config security key access s3 bucket. program reads file client , uploads aws s3 bucket. how change credentials set in environment variables? want js script read credentials env variables better security.. backend project developed in java.

How to set output file from another gradle build script's task from GradleBuild task? -

i have project gradle build. have project b gradle build also. want include project b's jar project a's war. can call project b's build script project a's build script (see below). can not set project b's jar output file of task buildb . is there way set project b's jar (which output file of task jar) output file of task buildb? task buildb(type: gradlebuild) { buildfile = "../bproject/build.gradle" tasks = ["clean", "jar"] // jar task produce xxx.jar it's outputs.files // here, script set xxx.jar outputs.files of task buildb??? } war { (buildb) { // can not xxx.jar buildb "web-inf/classes" } } you need configure multi module project , define project -scope dependency. since answer full answer lengthy, here can find demo shows how can done. the demo consists of 2 projects. 1 project built war , has dependency project built war. if build a proj

c# - Replace part of a LINQ to SQL query with a reusable method -

we have introduced new feature in our application, affects hundreds of queries. have set bool field indicate if license valid, in complicated way. i create method returning bool value, , i'd use in every query. problem is, if use in way shown below, executes separate query each result. how use expression in way compiled sql , executed single query? original query, in need of improvement iqueryable<deviceminimal> devices = device in db.devices device.accountid = accountid select new deviceminimal { id = device.id, name = device.name, licenseisvalid = !checkforlicense || device.license != null && ( !device.license.trialstarted // && 12+ licensing rules ) }; checkforlicense bool indicates license not need checked. used in cases , necessary considered. code, solves problem, provokes separate query each device iqueryable<deviceminimal>

intellij idea - Get Application path in grails controller -

i'm use intellij idea grails project. i want upload, user profile picture project directory. e.g. e:\myproject\useruploads currently i'm trying path using following code def filepath = request.getsession().getservletcontext().getrealpath("/") but when print filepath get: c:\users\rahul.mahadik\appdata\local\temp\tomcat-docbase.2236924879274963579.8080\ also tried "servletcontext.getrealpath("/")" path of current directory getting same path above thanks you should understand flow of building , running web application in grails. when start run-app command, grails compiles code , creates war file - web application archive . in order run war file need web server. grails has embedded tomcat server, gets war file , deploys tomcat. tomcat has own folder web application archive deployed. path application path folder tomcat server running application. that's why see c:\users\rahul.mahadik\appdata\local\temp\tomcat

javascript - owl carrousel items with autoWidth -

i trying use latest carousel docs achieve need, want show 3 images in big screens 2 in tablets , 1 in mobile devices, thing achieve before, 1 of images got stretched, tried use auto width, image stopped being stretched, occurs issue carousel don't display items set in responsive object, tries fit container items, can have image ratio, , images continue being responsive: code: <section class="content_section bg_gray border_b_n"> <div class="content row_spacer clearfix" style="max-width:939px"> <div class="owl-carousel"> <div class="item"> <img src="image1.png" width="112" height="112" alt="client name"> </div> <div class="item"> <img src="image2.png" width="210" height="40" alt="client name"> </div

Specifying Http headers in Elm -

my elm program works fine code (excerpt) below using http.get , had changed custom request specify jwt in header, , following error due type mismatch. i think need change type of request http.request (list qfields) not sure how to. apparently, can't make { verb = "get" ...} decoder because { verb ... } not function. the 2nd argument function `send` causing mismatch. 264| http.send fetchhntopstories request ^^^^^^^ function `send` expecting 2nd argument be: http.request (list qfields) is: request <working code> request : http.request (list qfields) request = let decoder = jd.at [ "data", "qqry" ] <| jd.list qdecoder in http.get ("http://localhost:3000/graphql?query=" ++ encoded) decoder type msg = sendmessage | fetchhntopstories (result http.error (list qfields)) ... initmodel : taco -

c# - When do I need to worry about tasks leading to multithreading? -

say have code this: ... var task1 = doworkasync(1); var task2 = doworkasync(2); await task.whenall(task1, task2); ... private async task doworkasync(int n) { // async http request configureawait(to determined). // cpu-bound work isn't thread-safe. } so if i'm in wpf app , don't configureawait(false) on http request, safe here? 2 http requests can made concurrently, tasks have resume on ui thread, cpu-bound work isn't multi-threaded? if configureawait(false) , tasks can resume cpu-bound work in parallel on different thread pool threads i'm in trouble? if i'm in asp.net can happen either way because synchronization context doesn't have thread wpf? and if i'm in console app? how talk doworkasync ? 'it's not safe doworkasync s concurrently'? is there normal way redesign it? important part concurrently http request, not cpu-bound work, use lock or (never used before)? so if i'm in wpf app , don't conf

javascript - Unable to get statistics of some youtube videos using json link -

am trying statistics of youtube video using api not able videos here link used https://www.googleapis.com/youtube/v3/videos?id=osy4szdiv5s&key=apikey&part=statistics https://www.googleapis.com/youtube/v3/videos?id=kdvvpqvbi_e&key=apikey&part=statistics am able stattistics second video not first video can 1 me out there seems issue api @ moment, issue has been opened @ google's tracker - https://issuetracker.google.com/issues/37107133

angular - jasny input mask doesn't allow to pick field values up -

Image
i've created form: this.cardform = this.fb.group({ card_number: ['', validators.required], holdername: ['', validators.required], expiry: ['', validators.required], cvc: ['', validators.required] }); into template: <form [formgroup]="cardform" novalidate="novalidate"> <div class="form-group"> <label for="card_number">card number</label> <input type="tel" id="card_number" name="card_number" class="input-transparent form-control" formcontrolname="card_number" placeholder="____-____-____-____" data-mask="9999-9999-9999-9999" data-parsley-creditcard="" required="required"> </div> <div class="form-group"> <label for="holdername">holder name</label> <in

How to get cross section of 3 dimensional array c# -

say have 3-dimensional array in c# int space[width, height, depth]; and implement method public int[,] getcrosssection(int position, int dimension) where 'position' point along 'dimension' specified extract slice. important not use fact dealing 3 dimensions, in examples below fix them adding if statements , assume matrix not grow beyond 3 dimensions. my first attempt (commented problem areas): public int[,] getcrosssection(int position, int dimension) { int[] dimensioniterationinterval = new int[] { width, height, depth }; var dims = new list<int>(dimensioniterationinterval); dims.removeat(dimension); dimensioniterationinterval = dims.toarray(); int[,] crosssection = new int[dimensioniterationinterval[0], dimensioniterationinterval[1]]; int[] itr = new int[2]; (itr[0] = 0; itr[0] < dimensioniterationinterval[0]; itr[0]++) { (itr[1] = 0; itr[1] < dimensioniterationinterval[1]; itr[1]++) {

angularjs - Should i learn Vuejs / Angular / React because i'm use Laravel right now? -

i have been 2 months laravel. considering learn javascript frawework increase skills. found laravel shipped vuejs, there angular & reactjs more popularity & jobs. so choose laravel: vuejs or angular or reactjs ? there no: "good answer". question opinion , many people framework based on experience. depends want achieve application. the thing can laravel has vuejs installed in clean project , laracast provides vuejs tutorials well. maybe can take their. and devsk suggest: react , angular more popular choices might want learn if want job developer.

JMeter groovy pre-processor throws exception when trying to empty “Custom SOAP Sampler”'s list of registered attachments -

i'm trying create groovy-based pre-processor ( jsr223preprocessor ) **custom soap sampler* plugin, intended cover following tasks: read list of file attachments csv input file; empty list of attachments registered custom soap sampler ; register attachments read csv file custom soap sampler . after quite extensive research on net--i'm new whole groovy, java, jmeter topic--, managed assemble groovy script shown below. // read data csv input file arraylist reclst = new arraylist(); string fldsep = vars.get("fldsep"); string fldhd = vars.get("fldhd"); new file(vars.get("indat")).eachline('utf-8') { if ((it != null) && (fldhd != null) && (!it.trim().equals(fldhd.trim()))) { reclst.add(it.trim()); } // if } // file.eachline // extract relevant parts , feed custom soap sampler (registered attachments) // csv format: tmstmp;prodid;tenid;fnam;mdat if (reclst.size() > 0) { // empty current att

c# - XML Deserialize with same element name and different attributes​ name -

i want deseralize following xml in c# <test> <testdata> <abc name = "fname"> test</abc> <abc name = "lname"> name</abc </testdata> </test> i have small example, have larger xml needs deseralize .net objects!! below object have public class employee { public string lastname {get; set;} public string firstname {get;set;} } how deseralize such xml using either linq or xml serializer. currently using xdocument, getting node name abc , using if else ladder constructing object not right way. test first name name last name in xml.. any appreciated!! the mapping describe not 1 supported xmlserializer . cannot serialize employee in way without 1 of: implementing ixmlserializable - not recommend; easy make mess of this, particularly deserialization code doing manually via xdocument or xmldocument (again, quite bit of work) creating dto model usable xmlserializer matches schema fr

Loan Amortization returns only the last item java -

this question has answer here: why arraylist contain n copies of last item added list? 3 answers i stuck loan amortization list gives me last item multiple times. method: public list<amortizationschedulelineitem> calculateamortizationschedule() { list<amortizationschedulelineitem> lineitems = new arraylist<amortizationschedulelineitem>(); amortizationschedulelineitem item = new amortizationschedulelineitem(); long balance = amountborrowed; int paymentnumber = 0; long totalpayments = 0; long totalinterestpaid = 0; item.setpaymentnumber(paymentnumber++); item.setpaymentamount(0d); item.setpaymentinterest(0d); item.setcurrentbalance(((double) amountborrowed) / 100d); item.settotalpayments(((double) totalpayments) / 100d); item.settotalinterestpaid(((do