Posts

Showing posts from March, 2014

google app engine - ClassNotPersistableException running Appengine Unit Test (JDO, Gradle) -

Image
when running unit test in appengine, receive following error: the class "biz.bookdesign.librivoxserver.userstars" not persistable. means either hasnt been enhanced, or enhanced version of file not in classpath (or hidden unenhanced version), or meta-data/annotations class not found. org.datanucleus.exceptions.classnotpersistableexception: class "biz.bookdesign.librivoxserver.userstars" not persistable. means either hasnt been enhanced, or enhanced version of file not in classpath (or hidden unenhanced version), or meta-data/annotations class not found. @ org.datanucleus.objectmanagerimpl.assertclasspersistable(objectmanagerimpl.java:5464) @ org.datanucleus.objectmanagerimpl.newobjectid(objectmanagerimpl.java:3425) @ org.datanucleus.api.jdo.jdopersistencemanager.newobjectidinstance(jdopersistencemanager.java:1618) @ org.datanucleus.api.jdo.jdopersistencemanager.getobjectbyid(jdopersistencemanager.java:1740) ... i have copied jdoconfig.xml file test class pat

systemd autossh.service variables -

i want add systemd service file autossh system. skript should ask viables conf-file. tried until now: autossh.service: [unit] description=autossh after=network.target [service] type=simple environmentfile=/usr/local/etc/autossh.conf execstart=/usr/bin/autossh -m 0 -g -c -2 -n -i /home/$tunnel_user/.ssh/id_rsa $tunnel_user@$server_name -p $dest_ssh_port -l $local_port:localhost:$dest_port & restart=always restartsec=60 [install] wantedby=multi-user.target autossh.conf: tunnel_user=tunneluser server_name=host.example.com local_port=10001 dest_port=5001 dest_ssh_port=22 unfortunately variables not resolved properly. tried double quoting "" , things %{local_port} also.

.net - Is It Okay for an Application Layer with a multi-step process to not use the domain layer -

i working on n-layered .net application following layers: presentation application domain infrastructure (contains persistence , common utility functions email) at point in application, request approved. once approved, there 4 steps must performed follows: assign product tag code issued product in request. update request status “being processed” “order completed” send email requester stating product ready pickup send email requester’s manager informing them of employee has been given , copy of request approved product the above steps must part of atomic operation meaning must done or action cancelled. thinking of having application layer directing request repository , persistence layer carry out tasks follows: application layer requests request repository perform steps 1 , 2 unit of work transaction application layer requests infrastructure layer carry out steps 3 , 4. i'm not sure if application layer supposed this. think because first 2 actions requi

python - Using multiprocessing to utilize all cores of the CPU -

i trying calculate number of floating point operations per second cpu can perform, wrote following program: import time import sys multiprocessing import process numofloops = 10000000 if (len(sys.argv) != 2): print "correct usage: python cpu.py 'no_of_processes'" sys.exit() #function each process def fpops(): = float(0.0) in xrange(0, numofloops): += 0.5 #print #for debugging purpose processes = [] numofprocesses = int(sys.argv[1]) numofops = numofloops * numofprocesses in xrange(0, numofprocesses): processes.append(process(target=fpops)) start = time.time() process in processes: process.start() process in processes: process.join() end = time.time() exectime = end - start print "exec time " , exectime flops = (float(numofops/exectime)) print "flops : " , flops the program calculates time (exectime) takes perform 'n' number of floating point operations , 'n / exectime' giv

json - Error with specific name using rest client builder in grails 2.3.4 -

i'm using rest-client-builder:1.0.3 grails plugin communicate rest api dspace. works well: def resp = rest.post("http://10.42.0.239:8080/rest/login"){ contenttype "application/json" json{ email = "myemail@mail" password = "root" } } but need send parameter minus sign in way: def status = rest.get("http://10.42.0.239:8080/rest/status"){ contenttype "application/json" json{ rest-dspace-token = "4506b187-bda8-4db7-801d-635f277d5316" } } minus signs in rest-dspace-token give next error: ((rest - dspace) - token) binary expression, should variable expression @ line how can solve ? in advance. just quote property of delegate: json{ delegate.'rest-dspace-token' = "4506b187-bda8-4db7-801d-635f277d5316" }

html - Extra white space on the side of a site -

@font-face { font-family: 'open sans'; font-style: normal; font-weight: 300; src: local('open sans light'), local('opensans-light'), url(https://fonts.gstatic.com/s/opensans/v13/dxi1orhcpsqm3vp6mxoatrampu5_7cjhw5spxoen3vs.woff2) format('woff2'); unicode-range: u+0000-00ff, u+0131, u+0152-0153, u+02c6, u+02da, u+02dc, u+2000-206f, u+2074, u+20ac, u+2212, u+2215, u+e0ff, u+effd, u+f000; } @font-face { font-family: 'raleway'; font-style: normal; font-weight: 300; src: local('raleway light'), local('raleway-light'), url(https://fonts.gstatic.com/s/raleway/v9/-_ctzj9b56b8rgxw8fariqzydmxhdd8saj6oajtfsbi.woff2) format('woff2'); unicode-range: u+0000-00ff, u+0131, u+0152-0153, u+02c6, u+02da, u+02dc, u+2000-206f, u+2074, u+20ac, u+2212, u+2215, u+e0ff, u+effd, u+f000; } .place { height: 100vh; width: 100vw; } body { min-height: 200vh; max-width: 100%; margin: 0px; } h1 {

git - Use sonar to prevent a commit if code coverage QG is not met -

i have added sonarqube plugin maven project in conjunction jacoco unit , integration test coverage. things working , can see on sonar dashboard current rate of code coverage , if miss quality gate code coverage on new builds. what prevent git commits based on qg result. example workflow: make changes git commit pre-commit git hook fires causes build , sonar check code coverage not > 80% new code fail , prevent commit is possible or have commit code , wait until can see detail in dashboard? something end result seek possible different workflow. take @ github plugin . comments on pull requests . if instead of committing master commit branch , create pull request, plugin scan , comment on code new issues*. human reviewer can decide whether or not merge. *not rules run in scan. e.g. rules duplications , coverage not included

Visual Studio C++ difference between Managed Test Project and Native Unit Test Project -

i'm new visual studio, of differences between managed test project , native unit test project. of unit test information available on internet says make native unit test, what's actual difference? in visual studio managed .net , native pure c++.

php - Function in array executed before calling it -

i have array this: $cmds = array( 'info' => call_user_func('_info', $cmd1), 'e1' => 'something' ); the func itself: function _info($cmd1){ if(strlen($cmd1) < 2){ die('invalid username'); }else{ echo 'cmd1 > 2';} } the problem being executed before call giving undefined variable error because $cmd1 not exist yet, exist when call in foreach function. been searching solution hours didn't find. tried setting array 'info' => _info($cmd1) , 'info' => '_info' , putted $cmd1 directly in func function _info(){ if(strlen($cmd1) < 2){die('invalid'); } but still same error being called before want be. you can send parameters executed later $cmds = array( 'info' => [ '_info', '$cmd1' ], // single quotes 'e1' => 'something' ); in meantime cmd1 defined $cmd1 = "hello"; foreach ($cmds $key =>

reactjs - Uncaught Error: Invariant Violation: FluxStore has not overridden FluxStore.__onDispatch(), which is required -

this code store: var store = require("flux/utils").store; var apiutil = require("../util/api_util"); var appdispatcher = require('../dispatcher/dispatcher'); var _users = apiutil.getusers() || []; var change_event = "change"; var userstore = new store(appdispatcher); userstore._ondispatch = function(payload){ switch(payload.actiontype){ case userconstants.users_received: console.log(payload); userstore.changed(); break; } }; i'm getting error mentioned in title (viz. "uncaught error: invariant violation: fluxstore has not overridden fluxstore.__ondispatch(), required") when apiactions method hits this: appdispatcher.dispatch({ actiontype: userconstants.users_received, users: users }); i have added fluxstore overwrite _ondispatch method requested, still getting error. overwriting incorrectly? any appreciated. fluxstore.__ondispatch() has 2 __ and have

server - Does phpstorm has it's own php interpreter? -

i using phpstorm 10.0.2 on windows 10. have wamp installed barely open since know phpstorm has it's own local server installed. knowing when run / debug page, link goes localhost:63342 when run php scripts it'll interpreter isn't set yet have no idea find php folder. (i able set using php in wamp) wondering if don't have wamp installed, should still able use set php interpreter without installing right? if true, php folder? no,use xammp(rec),ampps,wamp,or download php site php interpreter.

java - JRException: Error retrieving field value from bean: bornDate -

this question has answer here: unable retrieve value javabean while generating reports using jasperreports api 2 answers borndate java.util.date field in class, used fill collection represented list of employees. so, when second line read: jrbeancollectiondatasource beancollectiondatasource = new jrbeancollectiondatasource(lista); jasperprint jasperprint = jasperfillmanager.fillreport(relatorio, parametros, beancollectiondatasource); this message appears: jrexception: error retrieving field value bean: borndate yes, understand type mismatch. how can solve this? in jrxml file or in java class? in both, since class , name need's match in java need method public java.util.date getborndate(){return borndate}; in jrxml need the correct field declaration <field name="borndate" class="java.util.date"> <fielddes

python - How to change line width of a pandas plot if another variable satisfies a condtition -

Image
i want plot series of data: s = pd.dataframe(np.random.randn(5,2)) ind = pd.dataframe({'ind0':np.random.random_integers(0,1, 5), \ 'ind1':np.random.random_integers(0,1, 5)}) data = pd.concat([s,ind], axis=1) where "0" , "1" series plot , line width increases "0" when "ind0" 1, , likewise "1". 0 1 ind0 ind1 0 2.029756 -1.211402 1 0 1 0.428830 0.508613 1 0 2 1.964346 1.032110 0 1 3 1.424997 -0.363719 1 0 4 -0.581283 0.774375 1 0 i'm not familiar how pandas dataframe s work on small scale, it's enough compatible numpy ndarray s. i'll assume have latter, point should mask values based on variables ind0 , ind1 . suggest using plt.plot markers, (or, equivalently, plt.scatter ): import numpy np import matplotlib.pyplot plt n = 10 s = np.random.randn(n,2) ind0 = np.random.random_integers(0,1, n) ind1 = n

elasticsearch - Create multi field in elastic search -

i want create index , here mapping.i want create multi field on field - 'findings' 1 default mapping(analzyed) , other 1 'orig'(not_analyzed). put nto { "mappings": { "_default_": { "properties": { "date": { "type": "string", "index": "not_analyzed" }, "bo": { "type": "string", "index": "not_analyzed" }, "pg": { "type": "string" }, "rate": { "type": "float" }, "findings": { "type": "multi_field", "fields": { "findings": { "type": "str

C segmentation fault using structures -

#include<stdio.h> #include<stdlib.h> #include<string.h> #define max_sub_commands 5 #define max_args 10 struct subcommand { char *line; char *argv[max_args]; }; struct command { struct subcommand sub_commands[max_sub_commands]; int num_sub_commands; }; void readcommand(char *line, struct command **command); void printcommand(struct command **command); void read_args(char *in, char *argv[max_args], int size); void print_args(char *argv[max_args]); int main() { char s[200]; printf("enter command:"); fgets(s,200,stdin); s[strlen(s)-1]='\0'; struct command *command; readcommand(s,&command); printcommand(&command); } void readcommand(char *line, struct command **command) { const char *delim ="|"; const char *k; char *copy; char *l; int i=0; (*command)->num_sub_commands=0; k=strtok(line,delim); while(k!=null) { l=strdup(k); (*command)->sub_commands[i]

What is the method variable? in C# -

i use c#. when defined hoge method below, void hoge(bool isbar){} i hoge method below var methodname = this.hoge action<bool>).method.name; however, can't understand this.hoge type. because, can assign , casting. but, can't give me method name directly. this.hoge.method.name; and, error. typeof(this.hoge) what method variable exactly? the code provided isn't valid c# code, it's difficult understand you're asking. think you're trying understand how expression this.hoge translated can provide name of method. if so, code example should this: var methodname = ((action<bool>)this.hoge).method.name; and implicitly create instance of delegate type (in case, of type action<bool> ), if you'd written this: var methodname = new action<bool>(this.hoge).method.name; and of course, once have delegate type, type has method property , returns methodinfo object in turn, of course, has name property. if

php - Debugging the famous - FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream -

so has many articles mentioning error code: fastcgi sent in stderr: "primary script unknown" while reading response header upstream... that means error message more or less useless. the message telling fastcgi handler doesn't whatever sent reason. problem have no idea reason is. so i'm re-stating question -- how debug error code? consider situation have simple site, phpinfo.php file. additionally, there simple nginx config, follows: server { server_name testsite.local; root /var/local/mysite/; location / { index index.html index.htm index.php; } location ~ \.php$ { include /etc/nginx/fastcgi_params; fastcgi_pass fastcgi_backend; fastcgi_index index.php; fastcgi_param script_filename $document_root$fastcgi_script_name; } } how can see output/log fastcgi_params got sent script? how can see actual error message? in case, i'm using php-fpm. has no info in log error. logs no

c - Program working fine for smaller values but throwing Segmentation Fault for bigger values -

in following program when value of n less 100 program executing bigger values of n showing segmentation fault.i sit because of less memory or wrong program?? #include<stdio.h> int main() { int n,iteration,max_iteratons; int i,j,k,n,index,boundary1,boundary2; double h[2][100][100]; int current = 0; int next = 1; printf("enter number of points\n "); scanf("%d", &n); boundary1=0.4*n; boundary2=(0.6*n); printf("the boundary between %d , %d .\n",boundary1,boundary2); for(k=0;k<2;k++) { for(i=0;i<n;i++) { for(j=0;j<n;j++) { if((i==0)&&(j>=boundary1&&j<boundary2)) h[k][i][j]=100; else h[k][i][j]=20; } } } printf("initial values\n"); index = n/10; for(i=0;i<n;) { for(j=0;j<n;) { printf("%.2f\t",h[0][i][j]); j=j+index; } i=i+index; printf("\n");

python - Websockets — Invalid UTF-8 bytes -

i'm trying build simple echoing server websockets, can connection stay alive few seconds before error. reason i'm getting websocket closing "invalid utf-8 bytes", i'm not sure invalid bytes coming from. here websocket client: // websocket-client.es6 this.ws = new websocket(`ws://localhost:8080/websocket-test/ws`); this.ws.onopen = (event) => { this.ws.send('opening'); setinterval(() => { this.ws.send('heartbeat'); }, 5000); }; this.ws.onmessage = (event) => { console.log(event); }; this.ws.onclose = (event) => { console.log('websocket closing: %o', event); }; this.ws.onerror = (event) => { console.error('error: %o', event); } my server cherrypy ws4py: # websocket-server.py class mywebsocket(websocket): def received_message(self, message): cherrypy.log('received %s' % message) self.send(message.data, message.is_binary) def closed(self, code, reason=none):

javascript - If user came from previous page on site then this, else do this -

what viable way accomplish following: a website has 2 pages; parent page , inside page. if user came inside page directly typing in address or following link page other parent page, show "foo". if user came inside page parent page, show "bar". i need done in js if possible. if not, php secondary choice. please try this this code in second page jquery(window).load(function() { if (sessionstorage.getitem('dontload') == null) { //show bar } else{ //show foo } }); this code in parent page jquery(window).load(function() { sessionstorage.setitem('dontload','true') });

java - How expand a jframe in left side? -

i have 3 jpanel s. left , right panels hidden. center panel visible default. when press 1 button, frame width increased right panel's width , right panel becomes visible. my problem left panel because frame cannot increased in left direction. my solution is: public void mousepressed(mouseevent e) { int framewidth = frame.getbounds().width; int frameheight = frame.getbounds().height; int panelwidth = leftpanel.getpreferredsize().width; point currcoords = frame.getlocationonscreen(); if(!_leftpanelopened) { frame.setsize(new dimension(framewidth + panelwidth, frameheight)); leftpanel.setvisible(true); frame.setlocation(currcoords.x - panelwidth, currcoords.y); _leftpanelopened = true; } else { leftpanel.setvisible(false); frame.setsize(new dimension(framewidth - panelwidth, frameheight)); frame.setlocation(currcoords.x + panelwidth, currcoords.y); _leftpanelopened = false; } }

ruby on rails - Regexp in format: validation isn't stopping the right characters -

i'm new regex , i'm trying allows letters, numbers, quotes , following characters: !.:?!_+=, - i have validation below in guide modal. can name guide '&' if want , accepts it, understanding validation should stop me. validates :name, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, format: { with: /[a-za-z 1-9 0!.'":?!_+=, -]/, message: "only allows letters, numbers, quotes , !.:?!_+=, -" } not sure going wrong, tested out regex in rubular.com , works in there. edit after testing it, turns out stops '&' lets '&11' pass. if invalid key valid key passes. maybe i'm using format: wrong or shouldn't using format: this? i've simplified bit regex, added proper starting/ending line markers , added + @ end match if there 1 or more char in input. here's looks like: /\a[a-za-z0-9 !.'":?!_+=,-]+\z/ if want have cleaner one: /\a[\w !.'"

c# - Autofac with xml / json configuration -

i'm little lost on examples @ http://autofac.readthedocs.org/en/latest/configuration/xml.html#configuring-with-microsoft-configuration after poking around ages not realising had add microsoft.extensions.configuration.json package (and in pre-release), error on: var module = new configurationmodule(config.build()); i compile error not being able instantiate abstract class. there's no mention in docs having ref other package. ideas? right, had instal pre release version solved issues i using current stable.

Android Show Contacts that have Telegram account -

Image
how programmatically extract contacts have telegram account , show in app? contacts have telegram account displayed shown below. follow below steps get account mime type telegram. have content cursor query telegram contacts. for details on how it. check out link

matlab - Calculating condition numbers for hilbert matrices -

okay, first off feel silly asking question since seems answer should simple can't figure out. i have vector n: n=[2:13] i pass vector through elementwise returns vector calculated values: condition=cond(hilb(n)) hilb(n) returns hilbert matrix dimension n. cond() calculates condition number, scalar value. currently, matlab returning condition single value using first value n, 2 instead of vector equal in length n. i aware of using .* , sin.() , other commands compute things elementwise, can't find how function such this. you can't pass vector hilb that, unfortunately. should use loop, or simpler, arrayfun : condition = arrayfun(@(x) cond(hilb(x)), n) note arrayfun disguised loop, offers no performance benefit compared explicitly writing loop. condition = zeros(1,numel(n)); ii = 1:numel(n) condition(ii) = cond(hilb(n(ii))); end keep in mind hilb ill-conditioned matrix, values high ( cond(hilb(13))=8.3042e+19 . means resulting vector like

c# - How to get DataTable From DataSet? -

i have dataset ds contains 10 datatables, each have 1 column only. how make datatable contains columns dataset ds ? public static dataset readxmlusingbufferedstream(string pathofxmlfile) { dataset ds = new dataset(); ds.enforceconstraints = false; if (file.exists(pathofxmlfile)) { using (filestream filestream = file.openread(pathofxmlfile)) { bufferedstream buffered = new bufferedstream(filestream); ds.readxml(buffered); } } ds.enforceconstraints = true; return ds; } here have marged datatabes available in dataset . if set condition that, add columns of table, should enhanced. namespace consoleapplication1 { class program { static void main(string[] args) { //building dataset having 10 different datatable contains 1 column each dataset ds = new dataset(); (int = 0; <= 9; i++) { datatable dt = n

sql server - SQL Query for Max records for Multiple dates -

hi looking sql query select max records based on specific criteria customers. current situation below customer activity date 1 1 01/02/2015 1 1 02/02/2015 1 1 03/02/2015 1 2 05/02/2015 1 2 07/02/2015 1 3 06/02/2015 2 1 01/01/2015 2 2 05/01/2015 2 3 11/01/2015 my required resultset should customer activity1maxdate activity2maxdate activity3maxdate 1 03/02/2015 07/02/2015 06/02/2015 2 01/01/2015 05/01/2015 11/01/2015 the activities here limited 4 or 5 therefore ther e no requirement of dynamic column making any please chee

excel - How to loop through rows, save these as variables and use them as variables VBA -

i'm trying store values in sheets variable, , go on reference sheet using variable use filter by. this looped through until program reaches first empty cell. the relevant code have far is: sub program() dim integer = 2 until isempty(cells(i, 1)) debug.print sheets("button").activate dim first string first = cells(i, 1).value debug.print first dim second string second = cells(i, 2).value debug.print second 'filters data sheet , copies data sheets("data").activate sheets("data").range("a1").autofilter _ field:=2, _ criteria1:=first 'filters relevant organisation sheets("data").range("a1").autofilter _ field:=6, _ criteria1:="=" 'filters no response sheets("data").range("a1:h6040").copy 'this should loop through each separate group sheets(cstr(second))

How can I download a OneDrive file with Office365 REST API into a Ruby variable? -

i'm building ruby on rails app, , i'd integrate office365 features. for instance : download file onedrive , attach email in order send via outlook rest api. i found get item content onedrive rest api dont understand how use it. i understand have send request (formated explained in msdn.microsoft.com) rails, provide me " a pre-authenticated download url " download file. then have send second request a pre-authenticated download url start download, don't understand how deal response in order save file variable. how can retrieve file variable of ruby on rails app, can attach email outlook rest api send own rail controller ? also workflow not optimized in term of bandwidth , processing (3 rest api request + 1 download + 1 upload), work. however if exist single rest api direclty attach onedrive file email send it, ease lot life, save energy, save money microsoft datacenter, , spare planet ecology . any tutorial, examples, or more explanatory doc a

php - Pass user id in a mail form for registered user -

i pass user id (which email, in case) in email form. here php registered users only: $login_information = array( 'zubrag' => 'root', 'admin' => 'adminpass', 'phuket@iceagethai.com' => 'phuket' ); here use in form: <input type="hidden" name="email" value="<?php global $id; ?>"> how should write form field? googled around confused... what importance of inserting user id on input field? if want reuse user id after user login system, assign user id on session variable , user id session variable.

c# - Xamarin - Could not load assembly 'PCLStorage.Abstractions -

after adding flurlhttp nuget package pcl project app no longer deploy emulator due assembly loading error error exception while loading assemblies: system.io.filenotfoundexception: not load assembly 'pclstorage.abstractions, version=1.0.0.0, culture=neutral, publickeytoken=286fe515a2c35b64'. perhaps doesn't exist in mono android profile? file name: 'pclstorage.abstractions.dll' @ xamarin.android.tuner.directoryassemblyresolver.resolve(assemblynamereference reference, readerparameters parameters) @ xamarin.android.tasks.resolveassemblies.addassemblyreferences(icollection 1 assemblies, assemblydefinition assembly, boolean toplevel) @ xamarin.android.tasks.resolveassemblies.addassemblyreferences(icollection 1 assemblies, assemblydefinition assembly, boolean toplevel) @ xamarin.android.tasks.resolveassemblies.addassemblyreferences(icollection`1 assemblies, assemblydefinition assembly, boolean toplevel) @ xamarin.android.tasks.

java - Test POST request on PlayFramework 2.4.x -

good morning, i'm trying test post requests on controllers. i have no problems request : @test public void testgetall() { testmodel test = new testmodel(); test.done = true; test.name = "pierre"; test.save(); testmodel test2 = new testmodel(); test2.done = true; test2.name = "paul"; test2.save(); result result = new controllers.ressources.testressource().get(null); assertequals(200, result.status()); assertequals("text/plain", result.contenttype()); assertequals("utf-8", result.charset()); asserttrue(contentasstring(result).contains("pierre")); asserttrue(contentasstring(result).contains("paul")); } but when have test post request, can't give post params controller. here method want test : public result post() { map<string, string> params = requestutils.convertrequestforjsondecode(request().querystring()); t model = json.fromjs

javascript - Arithmetic with variables not working -

for reason, arithmetic in function updatescore(result) doesn't work (the function called later on in code). wins , ties , losses printed should, lives printed nan . know nan means. i've identified variables, reason or other, created strings. appears strange me, it's working 4 out of 5 variables. there's no consistency. i've tried number conversions using number(lives) , doesn't work either. suggestions how can ensure variables created numbers, , aritmethic operations work? var wins = 0, ties = 0, losses = 0, lives = 5, previouscpuchoice = 0; $("#startknapp").click(function(){ var spiller = prompt("hva heter du?"); $("#userselect").html(usermenu); $("#result").html("<h4>velg figur, " + spiller + "</h4>"); $("#status").html('<h4>liv: <span id="life">' +lives+ '</span> - seire: <span id="win&qu

Rails unpermitted parameters files when uploading using carrierwave -

i trying upload using carrierwave facing error ..when select file , click on upload still says it can't blank , on console says unpermitted parameters files . [upload_controller.rb] class uploadscontroller < applicationcontroller before_action :authenticate_user! def index @uploads=upload.all end def new @upload=upload.new end def create @upload=upload.new(params_abc) if @upload.save upload.upload(params[:upload][:files]) redirect_to @upload else render 'new' end end private def params_abc params.require(:upload).permit(:title,:description) end end [upload.rb] class upload < activerecord::base validates :description, presence: true validates :title, presence: true validates :tageline, presence: true mount_uploader :upload, uploaduploader def self.upload(files) files.each |file| #@file_extension=file.content_type.spli

How to automatically collect analytics events for button click in android? -

i have implement automatic event tracking in android need automatically collect analytics data on button clicks , page views has done in generic way don't need write analytics code again every click. example: have 2 buttons on activity each of them having click listener. want call analytics.track(string buttonname) not have add in every click listener. data should passed in tracking button name. a way (probably not ultimate way) extending button (or view ), , putting analytics code view#performclick() method. as buttonname , can a field of custom view class, can set programmatically or via xml custom attribute. global implementation : create custom xml attribut : create file named attrs.xml in ressource folder : <resources> <declare-styleable name="tracking"> <attr name="tracking_name" format="string" /> </declare-styleable> </resources> create custom button (or view ) class,

c# - Most efficient way to compare two lists and delete the same -

i want compare 2 lists , valid words new list. var words = new list<string>(); var badwords = new list<string>(); //this example list. actual list contain 700 records words.add("apple"); words.add("moron"); words.add("seafood"); words.add("cars"); words.add("chicken"); words.add("twat"); words.add("watch"); words.add("android"); words.add("c-sharp"); words.add("fool"); badwords.add("idiot"); badwords.add("retarded"); badwords.add("twat"); badwords.add("fool"); badwords.add("moron"); i looking efficient way compare lists , put 'good' words new list. finallist shouldn't contain "moron", "twat" , "fool". var finallist = new list<string>(); or unnecessary create new list? happy hear ideas! thank in advance use enumerable except function storing in system.lin

html - php/datatables generate table using foreach but need an additional <td></td> at end -

i using datatables , generating table using foreach, need 1 last contain options (edit, etc). cannot think how efficiently this, can think using counter , when output has ended place if statement (rows = rows then) put these last td's in... hoping has better way using current syntax? <?php foreach($results $row):?> <tr> <?php foreach($row $cell): ?> <td> <?php echo $cell ?> </td> <?php endforeach; ?> </tr> <?php endforeach; ?> you can put after internal this: <?php foreach($results $row):?> <tr> <?php foreach($row $cell): ?> <td> <?php echo $cell ?> </td> <?php endforeach; ?> <td>edit <

python - Extract block from CSS by Regular expression or any other method? -

i have extract text between /*custom-d start*/ , /*custom-d end*/ , , there maybe spaces after /* , maybe spaces before */ i did in 2 steps: regular expression extract start , end text. string find method text between start , end text. following code: data ="""/* highlighting edits text on tib , not on pdf output. .main-igp selector makes style apply tib. */ .main-igp .edit1 {color: rgb(235, 127, 36)} .main-igp .edit2 {color: rgb(0, 0, 180);} /*custom-d start */ .main-igp .edit3 {color: rgb(0, 180, 180);} .main-igp .edit6 {color: rgb(200, 200, 0);} /* custom-d end */ /* production note ===== */ p.production-note-rw { display: none;} /* production note end ===== */""" def extractcustomd(): """ extract custom-d block css data. starting text /*custom-d start*/ , ending text /*custom-d end*/ there may space after /* , before */ """ import re try:

java - Call getNextException to see the cause : How to make Hibernate / JPA show the DB server message for an exception -

i using postgresql, hibernate , jpa. whenever there exception in database, not helpful not show went wrong on db server. caused by: java.sql.batchupdateexception: batch entry 0 update foo set alert_flag='3' aborted. call getnextexception see cause. @ org.postgresql.jdbc2.abstractjdbc2statement$batchresulthandler.handleerror(abstractjdbc2statement.java:2621) @ org.postgresql.core.v3.queryexecutorimpl.processresults(queryexecutorimpl.java:1837) @ org.postgresql.core.v3.queryexecutorimpl.execute(queryexecutorimpl.java:407) @ org.postgresql.jdbc2.abstractjdbc2statement.executebatch(abstractjdbc2statement.java:2754) @ com.mchange.v2.c3p0.impl.newproxypreparedstatement.executebatch(newproxypreparedstatement.java:1723) @ org.hibernate.jdbc.batchingbatcher.doexecutebatch(batchingbatcher.java:70) @ org.hibernate.jdbc.abstractbatcher.executebatch(abstractbatcher.java:268) ... 82 more i want exception message database appear in application's lo

Virtual function or virtual method, which one is appropriate? -

i have been many interviews, question interviewers used ask "do know virtual function?" wonder why experienced programmer/developer use function virtual. know.. not functions can virtual, functions part of class/struct can virtual. so think "function superset , method subset. not functions can methods but, methods functions. therefore appropriate use "virtual method" not "virtual function". can explain, why of experienced programmer , technical books write use "virtual function" not "virtual method"? technically methods belong classes , functions ones don't, other things general , common, people end mixing terminology , in end "function" , "method" can both refer 1 thing or other. that's pretty answer question... in end, terminology defined how people use it, not original intended meanings.

gis - Regd. map grid structure in GPS data mining -

i have been exploring gps data mining literature esp. problems anomalous trajectory detection, time travel prediction, etc , 1 common method see dividing data or map grids. can 1 please explain logic of this? coordinates euclidean in case? grid decomposition necessary? grateful if can give/ quote links or materials should explore. new field, please pardon me if question obvious. thanks & regards, lesnar no not euclidean. don't have be. grids not rectangles anymore, can treated such operations. if create lat/long grid, each cell means of meters not rectangular. defines zone add counter, has clear inside/outside definition. , can use cartesian operations (rectangle.inside()) so lat / lon span constant each cell, not longitudinal meters span, shrinks cos(latitude). if 1 needs grid equal grid cells sizes means of meters, 1 has transform geo coordinates before.

mysql - Convert Inner Join to Left Join in rails -

i have rake file , , have code on . . if circle[:conference2_total_channels].present? conf = confbridge.find(:all, :conditions => ["confbridges.cid = ?",circle.circle_number], :joins => [:confbridge_participants], :select => 'confbridges.id, confbridges.confno, confbridges.max_member, (confbridges.max_member - 5) additional , (confbridges.max_member - ifnull(confbridge_participants.active,0)) vacant') end the return of code select confbridges.id, confbridges.confno, confbridges.max_member, (confbridges.max_member - 5) additional , (confbridges.max_member - ifnull(confbridge_participants.active,0)) vacant `confbridges` **inner join** `confbridge_participants` on `confbridge_participants`.`confbridge_id` = `confbridges`.`id` (confbridges.cid = '0090000092') it inner join how can change left join like select confbridges.id, confbridges.confno, confbridges.max_member, (confb

symfony - Dealing with FOSUserBundle PlainPassword field -

i've created user custom class in bundle. inherits baseuser class of fosuserbundle. in class, i've defined several attributes entities of bundle, adress, avis etc. i have defined formtype of forms data_class user. allows me retrieve interesting user information username (!) , displaying in forms. when validate forms asks me fill plainpassword field of user class mandatory attribute. first wanted retrieve password database fill in form before displaying seems impossible security measure. i've tried stock in session (ugly know) after registration seems not possible force form data value (surely because password type field)... so question : ? but purpose of retrieving it? want modify of user's data username or email? remember can have /profile 'module' in fosuser bundle, used modifing example username , email. changing password have separate 'module' change password (i don't remember path). maybe that's looking for? of course w

Python/SQL - How the cursor functions -

in code have function needs return either string or none depending on present in database. @ moment result list string answer inside, or none. there change made result in string or none being returned, rather having index list? here code: def retrieve_player_name(username): param = [(username)] command = (""" select username players username = ? """) result = cur.execute(command, param).fetchone() if result not none: return result[0] thanks in advance. a database cursors fetches entire rows, not values. row single value inside still row. if don't want write row[0] multiple times, create helper function execute_and_return_a_single_value_from_query() .

php - how to update the price of a product in eshopping -

i m making shopping cart in php & mysql. have problem update price of product. code below. plz tell me m wrong. echo statement not working , boxes products prices displayed. <?php include("includes/db.php"); include("includes/functions.php"); if(isset($_post['update_price'])){ //print_r($_post['price']); foreach($_post['price'] $priceup => $prvalue){ echo $sql = "update products set price='$prvalue' serial = '". $_post['product_data'][$priceup] ."'"; echo $result=mysql_query($sql);} } ?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" />