Posts

Showing posts from September, 2011

shell - Centos 6 /usr/sbin/sendmail - how to send email with subject? -

trying send email shell (centos 6) using 1 line command, subject empty echo 'body' | /usr/sbin/sendmail x@gmail.com subject:"test send mail" spent hours trying googling , find answer how send email using "/usr/sbin/sendmail" subject, no matter try, subject empty. (echo "subject: test"; echo; echo 'body')|/usr/sbin/sendmail -i x@gmail.com or cleaner script version #!/bin/sh /usr/sbin/sendmail -i x@gmail.com <<end subject: test body end warning : non us-ascii characters require special encoding in headers , custom headers when included in body.

python - Combining multiple parameters for creating SVM vector -

new scikit-learn , working data following. data[0] = {"string": "some arbitrary text", "label1": "orange", "value1" : false } data[0] = {"string": "some other arbitrary text", "label1": "red", "value1" : true } for single lines of text there countvectorizer , dictvectorizer in pipeline before tfidftransformer . output of these concatenated, i'm hoping following caveat: arbitrary text don't want equal in importance specific, limited , well-defined parameters. finally, other questions, possibly related might data structure indicate svm kernel best? or random forest/decision tree, dbn, or bayes classifier possibly better in case? or ensemble method ? (the output multi-class ) i see there upcoming feature feature union , run different methods on same data , combine them. should using feature selection ? see also: implementing bag-of-words naive-bayes classifi

envdte - CodeSmith.Insight.ClientError CodeSmith 5.2 -

can me problem?. have been having codesmith 5.2. not sure if messed visual studio..i right click , manage or generate output , error occurs if try open codesmithapplication , debug separately through codesmith studio, generates .cs , generated.cs files correctly. when in application , right click generate outputs, error occurs. why complaining env_dte? this error getting <?xml version="1.0" encoding="utf-16"?> <casereport xmlns:i="http://www.w3.org/2001/xmlschema-instance" xmlns="http://schemas.codesmithtools.com/insight/v2"> <messagesignature i:nil="true" /> <projectid>24</projectid> <description i:nil="true" /> <isdescriptionhtml>false</isdescriptionhtml> <messagedate>2016-02-02t16:47:53.7606242-06:00</messagedate> <messageidentifier>95e884f0-eb58-42e2-8bcc-e52d23909897</messageidentifier> <attachments /> <casetype>

php - How to display table data ordered by another table data row? -

i have videos , watch_later mysql tables, , want display videos data in page ordered watch_later date, current videos table looks this id | name | views 1 | funny video | 40 2 | sad video | 20 and current watch_later table looks this id | video_id | date 1 | 2 | 2016-02-01 2 | 1 | 2016-02-02 i've tried selecting ids watch_later table ordered date , selecting data videos table id in (previous ids), doesn't me videos data ordered watch_later date. (if didn't make sense, want watch later system youtube.) you have perform query join syntax: "select videos.*, watch_later.date videos join watch_later on videos.id=watch_later.video_id order watch_later.date desc" if prefer sorting in ascendant order, replace desc asc . with query, select either videos fields , date watch_later table. there various join methods: if want study it, @ w3schools edit: i choose select fields o

physics - Simple 3D particle gravity in javascript? -

i'm trying simple gravity handling in 3d environment (i'm using three.js). i've got code, doesn't work. i'm hoping it's silly bug somewhere. edit: replaced old code function handlegravity() { for(var j = 0; j < spheres.length; j++) { for(var = 0; < spheres.length; i++) { var r1 = new array( spheres[j].position.x, spheres[j].position.y, spheres[j].position.z); var r2 = new array( spheres[i].position.x, spheres[i].position.y, spheres[i].position.z); var r12 = new array(r2[0]-r1[0], r2[1]-r1[1], r2[2]-r1[2]); var r12unitvector = new array( r12[0]/math.abs(r12[0]), r12[1]/math.abs(r12[1]),r12[2]/math.abs(r12[2]) ); var m1 = masses[j]; var m2 = masses[i]; var r12squared = r12[0]*r12[0] + r12[1]*r12[1] + r12[2]*r12[2]; var a12 = new array( -(gravconst*m2/r12squared)*r12unitvector[0], -(gravconst*m2/r12squared)*r12unitvector[1], -(gravconst*m2/r12s

asp.net - ObjectDisposedException While using Include - why? -

my page calls services layer method uses generic repository "find" method. in services layer method, following: using (iunitofwork unitofwork = new dbcontext()) { genericrepository<operator> operatorrepos = new genericrepository<operator>(unitofwork); { try { var oper = operatorrepos.find(o => o.operatorid == operatorid).include(o => o.cmn_address).single(); return oper; } catch (invalidoperationexception exc) { //handle exception } } } the find method repository: public iqueryable<t> find(func<t, bool> predicate) { return _objectset.where<t>(predicate).asqueryable(); } on page, try acc

With Elasticsearch function score query with decay against a geo-point, is it possible to set a target distance? -

it doesn't seem possible based on https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html , i'd confirmation. in plain english, i'm asking score results (with geo-point locations) how close 500km latitude, longitude origin. it's confusing because there parameter called "offset" according documentation doesn't seem offset origin (eg. distance) instead seems mean "threshold" instead. i see few ways accomplish this: a. 1 way sort distance in reverse order origin. you'd use geo_distance query , sort distance . in following query, distant documents come first, i.e. sort value distance origin , we're sorting in decreasing order. { "query": { "filtered": { "filter": { "geo_distance": { "from" : "100km", "to" : "200km", "location": {

ruby on rails - Rspec or Rake which one is better -

i have 1 simple question rspec or rake 1 better , more reliable. regards, ab rake tool used manage various tasks related application such updating database schema or adding sample data it. rspec tool helps write tests applications.

java - How to play HTML5 video in webview in android? -

how play html5 video in webview in android? embed video tag below in yoru webview <video id="video" autobuffer width="320" height="240"> <source src="movie.mp4"> <source src="movie.ogg"> browser not support video tag. </video> set event below click . var video = document.getelementbyid('video'); video.addeventlistener('click',function(){ video.play(); },false); though using type="video/mp4" accepted html5 standard, andorid browsers seem mess it. don't use it.

java - meaning of action-response style web framework (Spring MVC 3) -

i learning spring mvc. in springsource blog author colin sampaleanu says "spring mvc, part of core spring framework, mature , capable action-response style web framework". in effort understand meaning of action-response style web framework did little research dint seem find exact meaning of it. action-response style web framework mean? there specific technical significance it? thanks. i believe distinction making is not exclusively request-response (i.e. straight http webserver) in post, put, etc (other http methods) may alter data in system or influence response application.

c# - Hex string to binary in webApp -

i have code converts hex string binary! on winform app works charm! if try implement in aspx strange happens. file should half of size hexstring file keeps growing , growing without end. allso, if stop debugging stays highjacked in vs2010 , can't delete without completly shutting down vs2010. the method conversion goes this: public static byte[] stringtobytearray(string hex) { int numberchars = hex.length; byte[] bytes = new byte[numberchars / 2]; (int = 0; < numberchars; += 2) bytes[i / 2] = convert.tobyte(hex.substring(i, 2), 16); return bytes; } and code: string filename1 = (@"some hex text file"); using (streamreader sr1 = file.opentext(filename1)) using (binarywriter bw = new binarywriter(file.open("new binary file", filemode.append))) { string hexstring = (sr1.readline()); while (hexstring != null) { bw.write(stri

osx - dtrace OS X thread name -

i'm trying thread name in dtrace script on os x. the script should record context switches of threads in application. #!/usr/sbin/dtrace -s #pragma d option quiet begin { printf("start dtrace script: time %ul\n\n", walltimestamp); } proc:::exec-success / execname == "myapplication" / { trace(execname); } sched:::off-cpu / execname == "myapplication" / { printf("tid: %ul (%s), off-cpu at: %ul\n", tid, curthread->td_name, walltimestamp); } sched:::on-cpu / execname == "myapplication" / { printf("tid: %ul, on-cpu at: %ul\n", tid, walltimestamp); } but error: dtrace: failed compile script dtrace_test.d: line 20: td_name not member of struct thread how can name of thread? or analysis tried generated intermediate code dtrace script (with -s ). sudo dtrace -s ./dtrace_test.d but same error: dtrace: failed compile script dtrace_test.d: line 20: td_name not member of s

c# - AddDictionary object to list of objects -

i have list of objects: public list<idnamepair> languages { { return languages; } set { languages = value; } } how add languages list above dictionary of same idnamepair ? protected dictionary<int, list<idnamepair>> countrylanguages { get; set; } i'm trying this: subjectbaseinfo.languages = countrylanguages; but error: cannot implicitly convert type 'system.collections.generic.dictionary>' 'system.collections.generic.list' idnamepair contains id , name . the 2 types different. subjectbaseinfo.languages single list<idnamepair> , whereas countrylanguages series of list<idnamepair> indexed int . so assignment have couple of possibilities. if assume subjectbaseinfo has id property might wanting this: subjectbaseinfo.languages = countrylanguages[subjectbaseinfo.id]; however, if subjectbaseinfo doesn't have id might want of idnamepair of lists in countrylanguages new singl

PyCUDA: syntax for function that calls a function -

when using function sourcemodule depends on function in sourcemodule, how pass in function call, i.e. "???" in following code: import numpy import pycuda.autoinit import pycuda.driver drv pycuda.compiler import sourcemodule mod = sourcemodule(""" __global__ void make_square(float *in_array, float *out_array) { int i; int n = 5; (i=0; i<n; i++) { out_array[i] = pow(in_array[i],2); } } __global__ void make_square_add_one(float *in_array, float *out_array, void make_square(float *, float *)) { int n = 5; make_square(in_array,out_array); (int i=0; i<n; i++) out_array[i] = out_array[i] + 1; } """) make_square = mod.get_function("make_square") make_square_add_one = mod.get_function("make_square_add_one") in_array = numpy.array([1.,2.,3.,4.,5.]).astype(numpy.float32) out_array = numpy.zeros_like(in_array).astype(numpy.float32) make_square_add_one(drv.in(in_array), drv.out(out_array), ??? , block

php - Display attribute by atribute id not on product page in magento -

i trying show attribute html attribute id in magento...the thing note don't have show on product page on phtml of custom module.....please me out have spent near 8 hours , important me try out $attributes = mage::getsingleton('eav/config') ->getentitytype(mage_catalog_model_product::entity) ->getattributecollection() ->addsetinfo(); foreach ($attributes $attribute) { if ($attribute->usessource()) { echo "{$attribute->getfrontendlabel()}:\n"; foreach ($attribute->getsource()->getalloptions() $option) { echo " {$option['label']}\n"; } echo "\n"; } } or try below code $attributemodel = mage::getsingleton('eav/config') ->getattribute('catalog_product', $attributecode); where $attributecode attribute code e.g. color,manufacture. for further info can refer link

google drive sdk - Python import pyDrive library error -

i installed google api, pydrive, , httplib2. got token app in google , saved client_secret.json file in project's folder. i'm trying run following print(sys.path) pydrive.auth import googleauth gauth = googleauth() gauth.localwebserverauth() # creates local webserver , auto handles authentication but throws syntax error invalid syntax (auth.py, line 160) in line from pydrive.auth import googleauth i can authenticate app using google drive api (without pydrive) i'm unable use pydrive because of described error, i've tried append following lines @ beginning of script: import sys if "c:\\users\\giovanni.sumano\\appdata\\local\\continuum\\anaconda3\\lib\\site-packages\\pydrive" not in sys.path: sys.path.append("c:\\users\\giovanni.sumano\\appdata\\local\\continuum\\anaconda3\\lib\\site-packages\\pydrive") because c:\\users\\giovanni.sumano\\appdata\\local\\continuum\\anaconda3\\lib\\site-packages\\pydrive path i've found pyd

android - Loading a BIG SQLiteDatabase in a ListActivity -

i'm working on android project need finish fast. one of app's features loading sqlite database content , listing in listview inside listactivity. the database contains few tables, among 2 large. each item in database has many columns, out of need display @ least 2 (name, price), although preferably 3. this might seem pretty easy task, need in part of app read database , list it. did without problems, testing app versus small sample database. in first version, used cursor query, arrayadapter list's adapter, , after query loop cursor start end, , each position add cursor's content adapter. the onitemclicklistener queries database again versus other parameters (basically open categories) clears adapter, loops cursor , adds content adapter on again. the app worked charm, when used real-life, big database (>300mb) got app taking long display contents, , blocking. so did research , started using simplecursoradapter automatically links contents of cursor

titan - Gremlin-Server Cassandra -

i starting work titan , using cassandra backend store. when start titan.sh cassandra , elasticsearch started gremlin server did not. i looking @ titan.sh , have seen start gremlin server conf/gremlin-server/gremlin-server.yaml. problem gremlin-server.yaml configured this: graphs: { graph: conf/gremlin-server/titan-berkeleyje-server.properties} using berkeleydb. have not seen cassandra.yaml gremlin server. how can configure cassandra ? thanks a fix stephen has been checked in address https://github.com/thinkaurelius/titan/commit/89c0a2b30e798a13e098949c219730b228bcc82a

python - OpenERP - modules import error -

i'm using openerp without installation - running source: get openobject-server, openobject-addons , openerp-web launchpad place /opt/openerp/ add path config file addons_path = /opt/openerp/openobject-addons/,/opt/openerp/openerp-web/addons/ start openerp server config all works but want install new addon (aeroo reports): get aeroo sources place /opt/openerp/ change config addons_path = /opt/openerp/openobject-addons/,/opt/openerp/openerp-web/addons/,/opt/openerp/aeroo/ it doesn't work file "/opt/openerp/aeroo/report_aeroo/check_deps.py", line 33, in <module> osv import osv importerror: no module named osv same thing when try run sources under windows (using eclipse+pydev) how can make see modules without changing code? from osv -> openerp.osv tools -> openerp.tools not first time see module import without leading 'openerp.' how can fix ? use command 7.0 openerp folder find . -type f -print0 | xargs

ruby - Selecting Options one by one Using watir-webdriver- -

b.select_list(:id, "maincontent_drpvehicletype").when_present.options.each |option| option.select b.select_list(:id, "maincontent_drpmake").when_present.options.each |option| option.select b.select_list(:id, "maincontent_drpmodel").when_present.options.each |option| option.select b.button(:id,"maincontent_imgbtnsearch").click end end end i'm having 3 dropdown each dropdown depends on previous values have select each option 1 one , click button . * while doing getting following error * element no longer attached dom (selenium::webdriver::error::staleelementreferenceerror) also tried: b.driver.manage.timeouts.implicit_wait = 3 assuming each option unique, try: get last option in dependent list make selection in current list wait option in step 1 no longer appear the following implements idea (though has not been tested since not have similar page test a

asynchronous - Async, Azure and program flow -

i have searched forum problem didn't find suited, im having problem program flow. i have mobileservice on azure has question table, app has main menu , quiz button takes user quiz page, on quiz page have start quiz button shows first question in list. this code im using questions database, placed in pages constructor , when user presses quiz button there delay in page opening isn't bad not long wait, few seconds, there better way this? task<imobileservicetable<question>> getdatafromdatabase = new task<imobileservicetable<question>>(getquestions); getdatafromdatabase.start(); questionlist = await getdatafromdatabase; in same function have code modifies start quiz button isenabled attribute. stops quiz going forward unless data has came through server, not working time , start button isenabled set true , nullreference mobileservicecollectionview questionlist though task has completed. task<bool> assigndata = new task<bool>(assignt

C# detect TCP client disconnection -

i working on tcp multithread server c# window application form, , trying detect if machine of client shutdown , disconnects server. have read posts , have ideas: how determine if tcp connected or not? instantly detect client disconnection server socket but i'm not sure call function isconnected my code following: public bindinglist<tablet> tabletlist = new bindinglist<tablet>(); private socket socket_server = null; private thread mythread = null; private socket socket_connect = null; private dictionary<string, socket> dic = new dictionary<string, socket> { }; private string remoteendpoint; socket_server = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp); ipaddress serverip = ipaddress.parse("192.168.2.146"); ipendpoint point = new ipendpoint(serverip, portnum); socket_server.bind(point); socket_server.listen(50); mythread = new thread(listen_disp);

How to avoid response timeout of my webpage in ASP.NET? -

i'm importing large amount of data excel(100.000 rows etc), , necessary values excel(it took 1 minute approximately) then loop within these records , database insert/update statements. approximately after 90 seconds response stops. page stops in background database goes on , insert/update jobs. but can't give user feedback(your process complete or such) because response ended(timedout). i try increase timeout in web.config: <httpruntime maxrequestlength="10240" executiontimeout="36000"/> also try increase executiontimeout specific page this: <location path="homepage.aspx"> <!--excel import takes long--> <system.web> <httpruntime executiontimeout="360000" maxurllength="10000" maxquerystringlength="80000" maxrequestlength="10240" /> </system.web> </location> they didnt work! suggestions? protected void page_load(object sender, eventa

ruby - Rails Server will not run -

typing $ rails server in terminal on mac yields these 2 errors i've tried troubleshooting uninstalling , installing ruby & rails again , same error. typing localhost:3000 on browser brings broken webpage meaning rails not running properly. as complete beginner, how troubleshoot these problems below step step rails run? ignoring binding_of_caller-0.7.2 because extensions not built. try: gem pristine binding_of_caller --version 0.7.2 ignoring byebug-8.2.2 because extensions not built. try: gem pristine byebug --version 8.2.2 ignoring debug_inspector-0.0.2 because extensions not built. try: gem pristine debug_inspector --version 0.0.2 ignoring executable-hooks-1.3.2 because extensions not built. try: gem pristine executable-hooks --version 1.3.2 ignoring gem-wrappers-1.2.7 because extensions not built. try: gem pristine gem-wrappers --version 1.2.7 ignoring mysql2-0.4.2 because extensions not built. try: gem pristine mysql2 --version 0.4.2 ignoring nokogi

bash - parse CSV, Group all rows containing string at 5th field, export each group of rows to file with filename <group>_someconstant.csv -

need in bash. in linux directory, have csv file. arbitrarily, file have 6 rows. main_export.csv 1,2,3,4,8100_group1,6,7,8 1,2,3,4,8100_group1,6,7,8 1,2,3,4,3100_group2,6,7,8 1,2,3,4,3100_group2,6,7,8 1,2,3,4,5400_group3,6,7,8 1,2,3,4,5400_group3,6,7,8 i need parse file's 5th field (first 4 chars only) , take each row 8100 (for example) , put rows in new file. same other groups exist, across entire file. each new file can contain rows group (one file rows 8100, 1 file rows 3100, etc.) each filename needs have group# prepended it. the first 4 characters numeric value, can't check these against list - there 50 groups, , maintenance can't done on if group # changes. when parsing fifth field, care first 4 characters so we'd start with: main_export.csv , end 4 files: main_export_$date.csv (unchanged) 8100_filenameconstant_$date.csv 3100_filenameconstant_$date.csv 5400_filenameconstant_$date.csv i'm not sure rules of site. if have try m

is it possible to read mp3 id3 tags in php using ffmpeg? if so then how? -

hi have few mp3 files in server change , need mp3 id3 tags people know song being played @ moment preferably via php . complete noob @ helpful. while there several possibilities, fan of using pipes. ffprobe should included in ffmpeg. <?php $output = shell_exec("ffprobe -print_format json -show_entries stream=codec_name:format -select_streams a:0 -v quiet test.mp3"); echo "<pre>$output</pre>"; ?> output: { "programs": [ ], "streams": [ { "codec_name": "mp3" } ], "format": { "filename": "test.mp3", "nb_streams": 1, "nb_programs": 0, "format_name": "mp3", "format_long_name": "mp2/3 (mpeg audio layer 2/3)", "start_time": "0.000000"

gruntjs - Passing arguments from command line to grunt copy task -

var pathvalue=""; module.exports = function(grunt) { grunt.initconfig({ copy: { main: { files: [{ cwd: 'srcpath', // set working folder / root copy src: '**/*', // copy files , subfolders dest: 'pathvalue', // destination folder expand: true }] } } }); grunt.loadnpmtasks('grunt-contrib-copy'); grunt.registertask('copy', function(n) { var target = grunt.option('target'); pathvalue = target; // useful target here }); }; i'm trying pass destination path copy task command line. tired command grunt copy --target=destpath it says "done without errors" new folder not getting created in destination directory. can please tell me what's error in code? try changing dest qualified js file path.

Android - query all Customer Orders from odata service -

i have wcf data service (from sample ms northwidth database), android app requesting data service code: northdataservice service = new northdataservice(); query<customers> query = service.createcustomersquery("/customers"); (customers cust : query){ log.d(log_tag, "customer name - " + cust.getcustomerid()); } i try query customer orders: log.d(log_tag, "orders - " + cust.getorders()); and see orders - null also know data on orders can request: http://server:82/northdata.svc/customers('alfki')/orders i try query: for (customers cust : query){ log.d(log_tag, "customer name - " + cust.getcustomerid()); string custname = "/customers" + "('" + cust.getcustomerid() + "')" + "/orders"; try{ query<customers> cquery1 = service.createcustomersquery(custname); (customers orders : cquery1){ log.d(log_tag, &qu

Adding words into string array from file C++ -

basically i'm doing reading words file, taking letters out of it, putting them array , counting how many have. problem way i've written it, when there 2 non-letters next each other word created. should change here? #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string str[10000]; string temp = ""; char c; int = 0, count = 0; //open file fstream sample; sample.open("sample.txt"); while (!sample.eof()){ sample.get(c); //convert character lowercase , append temp. string if ((c>=65 && c<=90) || (c>=97 && c<=122)){ c = tolower(c); temp += c; } //when word ends, add array , add 1 word count else if (c<65 || (c>90 && c<97) || c>122){ str[i] = temp; count++;

How do you test for departure from linear trend across ordered categorical variables with logistic regression using R? -

i'm testing linear trend in log odds of binary outcome across ordered categorical independent variable. straightforwardly achieved treating independent variable continuous. i'm trying test departure linear trend. understand comparing (a) model independent variable categorical (b) model independent variable treated continuous. i'm not sure how in r. can help? i've created reproducible example below. first 7 lines create dataset. model1 treats independent variable categorical; model2 continuous. model2 provides strong evidence linear trend explains trend better no trend @ all, linear trend not explanation in case. # create dataset 'a' n <- 200 ngroups <- 7 <- data.frame(group = rep(letters[1:ngroups], n), group2 = rep(1: ngroups, n), n = runif(n * ngroups, 0, 1)) y <- data.frame(group = letters[1:ngroups], fac = 1/(1 + exp(-1 * 1:ngroups))) <- merge(a, y, = "group") a$n2 <- a$n * a$fac a$ind <- ifelse(a$n2 > quan

xamarin.ios - Type Casting for uitextfield in montouch? -

i need create uitextfield name of string i'm getting service. tried following way string name = "sample"; uitextfield name = new uitextfield(); but i'm getting defined data type error. please give me solution. thank in advance, you can't have 2 variables named same. general c# syntax issue. does work if this: string name = "sample"; uitextfield namefield = new uitextfield();

python - Scrapy, Parse items from 1st page then a follow link to get additional items -

update: able moving, doesn't return subpage , iterate sequence again. data trying extract in table this: table date_1 | source_1 | link article_1 | date_2 | source_2 | link article_2 | etc.... and need first collect date_1, source_1 , go link article , repeat... any appreciated. :) from scrapy.spiders import basespider, rule scrapy.selector import htmlxpathselector scrapy.contrib.linkextractors import linkextractor dirbot.items import websiteloader scrapy.http import request scrapy.http import htmlresponse class dindexspider(basespider): name = "dindex" allowed_domains = ["newslookup.com"] start_urls = [ "http://www.newslookup.com/business/" ] def parse_subpage(self, response): self.log("scraping: " + response.url) il = response.meta['il'] time = response.xpath('//div[@id="update_data"]//td[@class="stime3"]//text()').extract() il.add_value('publish_date

c# - Can i use RouteLink to change the parameter of the route depending on link clicked, MVC3 -

in global.asax.cs routes.maproute( "default", // route name "{controller}/{action}/{id}", // url parameters new { controller = "home", action = "menu", pagename="index" } // parameter defaults ); routes.maproute( "newroute", // route name "{controller}/{action}/{pagename}", // url parameters new { controller = "home", action = "menu", pagename = urlparameter.optional } // parameter defaults ); i want parameter pagename " index " first home page loading. after on menu link click need transfer value of parameter pagename corresponding link , not value "index".hence wrote new maproute, pagename optional , not "index". so in _layout.cshtml foreach(...) { @html.actionlink(item.title, "menu", "home", new { pagename = item.pagename, role = "adm

amazon web services - Using AWS Lambda to transform files on S3 -

i have simple scenario. use lambda load multiple 100mb files s3 (every 1-10 seconds new file(s) land on s3), transform them (minor changes) , store them on different s3 bucket. the problem in java program (running on aws lambda) giving memory overflow errors though allocated 1024md ram. load complete files in ram. not sue why happens. i have following questions: without filling ram, approach read, transform , write 100mb files on s3 repeatedly , concurrently? lambda choice case? why memory getting full though allocated 1024 memory through web ui?

ruby on rails - How to eager load in this case? -

class model runningtracks < activerecord::base has_many :achievements has_many :runners, through: :achievements class model runner < activerecord::base has_many :achievements has_many :running_tracks, through: :achievements class model achievement < activerecord::base belongs_to :runner belongs_to :running_tracks on homepage there each do list display runningtracks. next track display button mark run. eager loading solution includes , references (rails 4) in query in controller: class runningtrackscontroller def index @running_tracks = runningtracks.includes(:achievements).references(:achievements) end to improve usability, button next each record should not visible if had been marked. (will refactored in helper method) @running_tracks.each |track| . - unless track.achievements.map(&:user_id).include? current_user.id = button_to "done", running_track_mark_as_done_path(track) this works...but... database gets more rec

java - Getting Permissions required by installed apps : Application Force Closes -

i trying make app gives list of installed apps , when item clicked , starts activity states permissions required installed apps. got installed application list, when click app instead of starting new activity , application force closes. following tutorial mainactivity package com.example.appslist; import java.util.list; import com.example.appslist.adapter.apkadapter; import com.example.appslist.app.appdata; import android.os.bundle; import android.app.activity; import android.content.intent; import android.content.pm.packageinfo; import android.content.pm.packagemanager; import android.view.view; import android.widget.adapterview; import android.widget.adapterview.onitemclicklistener; import android.widget.listview; public class apklistactivity extends activity implements onitemclicklistener { packagemanager packagemanager; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.

asp.net mvc 4 - fortnightly C# logic -

anyone please me fortnightly c# mvc 5 calendar logic. i've implemented weekly dates. this weekly code. working. var day = (from o in db.suburbs.asenumerable() ..etc select new { dt.deliveryday, }).tolist(); foreach (var temp in day) { if (type == "weekly") { int weeklylogic = ((int)enum.parse(typeof(dayofweek), temp.deliveryday) - (int)today.dayofweek + 7) % 7; datetime nextweeklylogic = today.adddays(weeklylogic); firstweek = nextweeklylogic; int weekly2 = (((int)enum.parse(typeof(dayofweek), temp.deliveryday) - (int)today.dayofweek + 7) % 7) + 7; datetime secondweek = today.adddays(weekly2); int weekly3 = (((int)enum.parse(typeof(dayofweek), temp.deliveryday) - (int)today.dayofweek + 7) % 7) + 14; datetime thirdweek = today.adddays(weekly3); etc.. } else if (type == "fortnightly") { } } for example, type == "fortnightly" , example t

vb.net - Error while Obfuscation -

we have developed project using vb.net our internal purposes , obfuscated it. throwing error mentioned below. “public member ‘var1’ on type ‘e’ not found.” code: public sub get_constants_from_dblist(byref frm object, byref sdbname string) each row datarow in commonobj.dscommonproc.tables("dblist").rows if strcomp(row("dbname").tostring, sdbname, comparemethod.text) = 0 prg_id = row("prgid").tostring frm.var1= row("changesdbname").tostring frm.var2 = row("loadtablename").tostring frm.var3 = row("servername").tostring exit sub end if next end sub a form (named frmmain) passed parameter ‘frm’ calling procedure sub-routine. var1, etc public variables in form. obfuscation tools tried – smartassembly 6 preemptive dotfuscator , analytics ce (which has come visual studio 2012) without obfuscation exe working fine. err

java - EHCache configuration in WebApplication -

i have written below code getting cachemanager object public class ehcacheutil implements serializable{ /** * */ private static final long serialversionuid = 1l; public static cachemanager cachemgr = null; private static ehcache getcache(string cachename) throws exception{ if(cachemgr == null){ file file = new file("f:\\projectworkspace\\src\\java\\ehcache.xml"); // use environment or vm variable cachemgr = cachemanager.create(new fileinputstream(file)); system.out.println("cachemgr.cacheexists(cachename)"+cachemgr.cacheexists(cachename)); } ehcache cache = null; if(cachemgr!=null){ //cache = cachemgr.addcacheifabsent(name); cache = cachemgr.getehcache(cachename); } return cache; } ehcache.xml <?xml version="1.0" encoding="utf-8"?> <ehcache xmlns:xsi="htt

performance - is it more optimal to assign and then multiply with *= ? in this case? -

in interest of being light weight possible in code must run potentially 60 times per second or more in animation scenario, became curious on seemingly insignificant 2 lines of code. i know performance benefit nil, in interest of understanding better how code works in cpu, ask following question: does 1 of these sequences generate more optimal (even minimally) set of cpu operations, , why? (or possibly, "why not?") assume un-optimized compilation scenario, obviously. obja.scalex = _inversionfactor * value; obja.scaley = value; vs. obja.scalex = obja.scaley = value; obja.scalex *= _inversionfactor; assume un-optimized compilation scenario, obviously. since interested in performance , optimization , not obvious, rather schizophrenic assume that. i know compiler/performance people on these channels, how cpu sees these operations. the cpu not see these operations @ all, sees compiler has made of them, , depends on compiler, obviously.

Google Maps API - Find matching place between two points? -

Image
i explain issue in below image (i'm sorry speak english not well). i'm using google maps directions api calculate directions between start point , destination , there place between them (you see in map). how can know place on route? the way can think of (and have used method) thus: when make directions request, receive directionsresult object. if drill down result can latitudes , longitudes. if using javascript api, example: // every step 22 latlngs per mile; we'll try 1 latlng per 3 // miles or so: var specroute = directionresult.routes[0].legs[0].steps[i]; (var j = 0; j < specroute.path.length; j = j + 171) { var lattotal = latarr.push(specroute.path[j].lat()); var lngtotal = lngarr.push(specroute.path[j].lng()); } in example formatting arrays of lats , lngs compared lot of other lats , lngs in php file elsewhere. sounds need check 1 latlng should simpler. what did thereafter (and do) determine how close path point

asp.net - Return HttpStatusCode in API method -

how return httpstatus code api methods in asp.net core 1.0 if there's problem? if method supposed return particular object type, when try return http status code, error saying can't convert object status code. [httppost] public async task<someobject> post([frombody] inputdata) { // detect error , want return badrequest httpstatus if(inputdata == null) return new httpstatuscode(400); // well, return object return myobject; } return iactionresult controller action instead: public async task<iactionresult> post([frombody] inputdata inputdata) { if(inputdata == null) { return new httpstatuscoderesult((int) httpstatuscode.badrequest); } //... return ok(myobject); } if instead want remove such null checks controller define custom attribute: public class checkmodelfornullattribute : actionfilterattribute { public override void onactionexecuting(actionexecutingcontext context) { if (co

python - How to make geopy requests? -

i have csv file few thousands of addresses, , want use geopy respective coordinates. using code right coordinates import pandas pd geopy.geocoders import nominatim geolocator = nominatim() geolocator = nominatim() location = geolocator.geocode(some_address) so have function: def get_geo(address): location = geolocator.geocode(address) return location.latitude, location.longitude df['address'].apply(get_geo) but when try used list more 2 two requests error? geocoderunavailable: service not available

android - problems with CountDownTimerWithPause -

i'm trying use timer, on question suggested: https://stackoverflow.com/questions/13806545/how-to-extend-countdown-timer-with-pause, but doesn't work expected. pause/resume works fine, if cancel , recreate timer, counting starts last paused time. need start initial value. eg counter's intial value 3 minutes. if paused @ 2 minutes, when i'm trying create again starts 2 minutes. help? public class mainactivity extends buttonmethods implements onclicklistener { private countdowntimerwithpause timerpausable = null; int milis = 180000; @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.main); timerpausable = new countdowntimerwithpause(milis, 1000, true) { @override public void ontick(long millisuntilfinished) { timer.settext("" + millisuntilfinished / 1

gcdwebserver - GCWebServer on tvOS appears to stop responding to requests -

i've got gcdwebserver , running, bridged swift. observing, via several tests, although network connection hasn't changed, web server hasn't stopped (not logged, dealloc breakpoints not hit, requests queue raised, stopped not called, delegate methods not hit) stops responding incoming requests. this on tvos 9.1.1, repeatable. trying debug why happening, nothing being logged indicate cause. last thing logged like: [debug] did open connection on socket 9 [debug] did connect [debug] did start background task [debug] connection received 339 bytes on socket 9 [debug] connection on socket 9 preflighting request "get /" 339 bytes body [debug] connection on socket 9 processing request "get /" 339 bytes body [debug] connection sent 182 bytes on socket 9 [debug] connection sent 44 bytes on socket 9 [debug] did close connection on socket 9 [verbose] [fe80::...] fe80::... 200 "get /" (339 | 226) [debug] did disconnect [debug] did end background tas

node.js - Difference between a server with http.createServer and a server using express in node js -

what's difference between creating server using http module , creating server using express framework in node js? thanks. ultimately, express uses node's http api behind scenes. express framework the express framework provides abstraction layer above vanilla http module make handling web traffic , apis little easier. there's tons of middleware available express (and express-like) frameworks complete common tasks such as: cors, xsrf, post parsing, cookies etc. http api the http api simple , used to setup , manage incoming/outgoing ,http connections. node of heavy lifting here provide things you'll commonly see throughout node web framework such as: request / response objects etc.

C++ mysql error - undefined reference -

i include #include "include/mysql.h" and try connect mysql db mysql_res *result; mysql_row row; mysql *connection, mysql; int state; mysql_init(&mysql); connection = mysql_real_connect(&mysql,"localhost","root","pass","workerproject",0,0,0); i included files project. use eclipse , linked mysql bin, include , lib files preporties of project. however, error in these 2 lines: mysql_init(&mysql); connection = mysql_real_connect(&mysql,"localhost","root","pass","workerproject",0,0,0); undefined reference error. why? error: /home/mert/workspace1/project484/debug/../src/main.cpp:99: undefined reference `mysql_init' /home/mert/workspace1/project484/debug/../src/main.cpp:100: undefined reference `mysql_real_connect'

ios - Do I have to hard-code / localise myself the "OK" button when generating an alert in swift? -

i have convenience method in swift (ios 8+) displaying error message. far looks this: // supplied category code , error code, generates error dialogue box. // codes rather strings because needs localisable. func showerrordialogue(categorycode: string, _ errorcode: string) -> () { // fetch actual strings localisation database. let localisedcategory = nslocalizedstring(categorycode, comment: categorycode) let localisederror = nslocalizedstring(errorcode, comment: errorcode) // create alert box let alertcontroller = uialertcontroller( title: localisedcategory, message: localisederror, preferredstyle: .alert ) alertcontroller.addaction( uialertaction( title: "ok", // fixme: why isn't localised? style: .default, handler: { (action) in return } ) ) self.presentviewcontroller(alertcontroller, animated: true) { return } } it seems o

ruby - remove an element in an array of Hash in rspec -

here rspec code:- "should match valid address" :index, devise.token_authentication_key => @user.authentication_token, business_id: @business2.id expect(response.status).to eq(200) expect(response.body).to eq([@location].to_json(locationfinder::api_params.merge(:root => false))) end expected: "[ { \"address\":\"1120 milky way\", \"business_id\":1, \"city\":\"cupertino\", \"latitude\":\"2.4\", \"longitude\":\"2.9\", \"name\":\"joe's diner\" } ]" got: "[ { \"address\":\"1120 milky way\", \"business_id\":1, \"city\":\"cupertino\", \"latitude\":\"2.4\", \"longitude\":\"2.9\", \"name\":\"joe's diner\", \"distance\":712.7948793 } ]" how

push notification - Gcm device registration issue in android -

currently working push notification in android.its working fine.but issues getting multiple notification instead of single notification.then check device registration table , find strange fact ,after each 30 minutes device id changing,so multiple device resisted same user_id , getting number of notification .i don't know why happen.i using samsung galaxy s2 testing. please me . i'm not sure why registration id changes every 30 minutes. perhaps if post registration code i'll able tell. regardless issue, server should able handle multiple registrations same device. when send registration id server, send unique id created app or server, , allow identify when new registration id existing device, in case you'll replace old registration id new one. another thing should @ server handle case gcm server returns canonical registration id, in case should replace id used sending message canonical one.

One development profile for Xcode on multiple computers -

my friend signed developer @ apple developer portal , itunes connect portal. want run our project @ , devices. send me provisioning profile , added xcode organizer. after added iphone "use development"(it's udid added profile). have profile in organizer unfortunately not in xcode->build settings->code signing choose. when try run project receive "no unexpired provisioning profiles found contain of keychain's signing certificates" issue. tried delete , install profile several times can't add particularly xcode code signing. tried synchronize iphone via itunes install profile on device unsuccessfully. how can use profile on both , mine machines? ask him send assicated certificate (as .p12 file) provisioning profile install certificate in key chain access double clicking , entering password has created while exporting certificate .p12 file . if profile made certificate should able select code signing identity in build settings

list - Sequence of dictionaries in python -

i trying create sequence of similar dictionaries further store them in tuple. tried 2 approaches, using , not using loop without loop dic0 = {'modo': lambda x: x[0]} dic1 = {'modo': lambda x: x[1]} lst = [] lst.append(dic0) lst.append(dic1) tup = tuple(lst) dic0 = tup[0] dic1 = tup[1] f0 = dic0['modo'] f1 = dic1['modo'] x = np.array([0,1]) print (f0(x) , f1(x)) # 0 , 1 with loop lst = [] j in range(0,2): dic = {} dic = {'modo': lambda x: x[j]} lst.insert(j,dic) tup = tuple(lst) dic0 = tup[0] dic1 = tup[1] f0 = dic0['modo'] f1 = dic1['modo'] x = np.array([0,1]) print (f0(x) , f1(x)) # 1 , 1 i don't understand why getting different results. seems last dictionary insert overwrite previous ones, don't know why (the append method not work neither). any welcomed this happening due how scoping works in case. try putting j = 0 above final print statement , you'll see happens. also, mi

c# - Converting text content in a variable to pdf -

i have string variable named teststring , contains content like teststring="<span>hi test content</span>" is there c# code copy contents in pdf file? you can use itextsharp library produce pdf file html page. itext ® library allows create , manipulate pdf documents. enables developers looking enhance web- , other applications dynamic pdf document generation and/or manipulation. developers can use itext to: serve pdf browser, generate dynamic documents xml files or databases, use pdf's many interactive features, add bookmarks, page numbers, watermarks, etc. split, concatenate, , manipulate pdf pages, automate filling out of pdf forms, add digital signatures pdf file, itext available in java in c#. here simple tutorial started, export-html-div-contents-to-pdf-using-itextsharp

Ruby Multidimensional Array - Remove duplicate in first position, add number in second position -

for array: items = [[60, 3], [60, 3], [276, 2], [276, 2], [48, 2], [207, 2], [46, 2], [60, 2], [280, 2], [207, 1], [48, 1], [112, 1], [60, 1], [207, 1], [112, 1], [276, 1], [48, 1], [276, 1], [48, 1], [276, 1], [276, 1], [278, 1], [46, 1], [48, 1], [279, 1], [207, 1]] i want combine common numbers in first positions of each sub-array, , add numbers in second positions together. for instance, you'll see first 4 sub-arrays here are: [60, 3], [60, 3], [276, 2], [276, 2] this become: [60,6], [276,4] , on. try this items. group_by {|i| i[0]}. map{|key, value| [key,value.inject(0){|sum, x| sum + x[1]}]} firstly, use group_by create hash keys first element of each array. have { 60=>[[60, 3], [60, 3], [60, 2], [60, 1]], 276=>[[276, 2], [276, 2], [276, 1], [276, 1], [276, 1], [276, 1]], 48=>[[48, 2], [48, 1], [48, 1], [48, 1], [48, 1]], 207=>[[207, 2], [207, 1], [207, 1], [207, 1]], 46=>[[46, 2], [46, 1]], 280=>[[280, 2]], 112=>