Posts

Showing posts from April, 2014

mysql - SELECT n row FROM table1 PER table2 -

have 2 table: cats(category) , post. want select n post per each category. i have tried this: select * cat right join (select * post post.catid=cat.id limit 3 ) ... the problem mysql not recognize cat.id inside sub query. regards select a.id, a.category, b.description category inner join post b on a.id = b.cat_id ( select count(*) post c b.cat_id = c.cat_id , b.id <= c.id ) <= 2 sqlfiddle demo

java.lang.OutOfMemoryError: Java heap space with JSON conversion -

listadecretosingolo = new arraylist<>(); listadettagliodecretosingolo = new arraylist<>(); for(int = 0; < 1022; i++){ decretosingolotemp = new decretosingoloviewobject("roma", "abcde3593cxxe", "decreto singolo", date,new bigdecimal(56000), new bigdecimal(343434), new bigdecimal(55656), new bigdecimal(9999)); for(int j = 0; j < 111; j++){ listadettagliodecretosingolo.add(new dettagliodecretosingoloviewobject(22, date, "numero dec pag", "tipo pag", new bigdecimal(45), "nota dec")); } decretosingolotemp.setdetails(listadettagliodecretosingolo); listadecretosingolo.add(decretosingolotemp); } objectwriter ow = new objectmapper().writer().withdefaultprettyprinter(); string jsonlist = null; jsonlist = ow.writevalueasstring(listadecretosingolo); i want tes...

wordpress - AngularJS - Service return value -

i've app using json user api wordpress plugin. i've service validate user cookie. first call api cookie name try validate cookie. angular.module('app').service('authservice', authservice); authservice.$inject = ['$http']; function authservice($http) { return { isauthenticated: isauthenticated }; function isauthenticated(){ return $http.get('http://somesite/pcookie.php') .then(function (response) { var authcookiename = response.data.response; var authcookie = getcookie(authcookiename); var validity; $http.get('http://somesite/api/user/validate_auth_cookie/?cookie='+authcookie) .then(function (response) { validity = response.data; }); return validity; }); } } the problems are: there other method provide logged_in_cookie cookie name? validity undefined because of nested functions. how can resolve it? because firs...

javascript - My images won't show -

my images won't show when trying load page! trying make traffic light sequence (uk) shows colours when change lights button pressed! <!doctype html> <html> <body> <h1><u><b>changing traffic lights</b></u><h1> <button type="button" onclick="changelights()"> change lights </button> <!-- creates button change lights --> <img id ="trafficlight" src="red.jpg"></img> <!-- creates first visible image on page , gives id can called later --> <script> var trafficlights = ["red-amber.jpg","green.jpg","amber.jpg","red.jpg"] //creates array lights var currentlight = 0 //creates counter variable function changelights () { //calls function , designs document.getelementbyid("trafficlight").src=trafficlights[currentlight] //calls image , enables changed currentlight=currentlight+...

jquery - How to take today's date and onward only not previous date? -

i want insert today's date , onward not previous date insert data base takes date tomorrow , onwards not today's var = moment(new date()); var mdate = moment(new date($('.meetingdate').val())).format("m/d/yyyy"); //now.format("yyyy/mm/dd"); var duration = moment.duration(now.diff(mdate)); var days = duration.asdays(); //alert(now + mdate); alert(days); if (days > 0) { e.preventdefault(); alert("please enter valid date"); $validation = false; } it because when calculate, completes day, , takes next day in account. so, if more 12:00:00 am, need calculate using previous day. so, is: var mydate = new date(); if (mydate.gethours() != 0 && mydate.getminutes() != 0 && mydate.getseconds() != 0 && mydate.getmilliseconds() != 0) mydate.setdate(mydate.getdate() - 1); var = moment(mydate); var mdate = moment(new date($('.meetingdate').val())).format("m/d/yyyy"); //now.format(...

angular - *ngIf and *ngFor on same element causing error -

i'm having problem trying use angular's *ngfor , *ngif on same element. when trying loop through collection in *ngfor , collection seen null , consequently fails when trying access properties in template. @component({ selector: 'shell', template: ` <h3>shell</h3><button (click)="toggle()">toggle!</button> <div *ngif="show" *ngfor="let thing of stuff"> {{log(thing)}} <span>{{thing.name}}</span> </div> ` }) export class shellcomponent implements oninit { public stuff:any[] = []; public show:boolean = false; constructor() {} ngoninit() { this.stuff = [ { name: 'abc', id: 1 }, { name: 'huo', id: 2 }, { name: 'bar', id: 3 }, { name: 'foo', id: 4 }, { name: 'thing', id: 5 }, { name: 'other', id: 6 }, ] } toggle() { this.show = !this.show; } l...

sql - ora-00936 missing expes -

i can't find what's wrong in code. update order_items o set (discount_amount) = select t.maxdiscount (select customer_id , o.order_id order_id, d.product_id product_id, d.total, e.maxdiscount maxdiscount orders o, (select sum(quantity)as total, order_id, product_id order_items group order_id, product_id) d, (select max(discount_amount) maxdiscount, product_id order_items group product_id) e o.order_id = d.order_id , e.product_id = d.product_id) t exists t.order_id = o.order_id , t.product_id = o.product_id; the message is: 00000 - "missing expression" no idea what's problem. in advance! update order_items o set discount_amount = (select t.maxdiscount (select customer_id, o.order_id order_id, d.product_id product_id, d.total, e.maxdiscount maxdiscount orders o, ...

node.js - Running redux example without nodejs server? -

im newbie node, redux, webpack , react. found examples: http://rackt.org/redux/docs/introduction/examples.html i run universal example. client doesn't want run node.js server on production.. there anyway generate bundle.js @ build time , upload server? all examples found use webpack-dev-server (node express server), possible create bundle file , serve simple static file? i'm facing same issue. wanna migrate jsp views based spring mvc app redux/react client spring data api/backend client webapp, server side rendering benefits (universal javascript). for angular apps (only client side js), it's easy serve bundle browser, , communicate backend via ajax, server side rendering gets more complicated. the 2 questions ask myself is: worth complexity , work on architecture setting , maintaining? innovation turn project daily headaches, caused new development features , possible issues/bugs on production? if client not going appreciate, or value (from non-tec...

regex - Finding whole word only in Java string search -

i'm running problem of finding searched pattern within larger pattern in java program. example, i'll try , find for loops, stumble upon formula . of suggestions i've found talk using regular expression searches string regex = "\\b"+keyword+"\\b"; pattern pattern = pattern.compile(regex); matcher matcher = pattern.matcher(searchstring); or variant of this. issue i'm running i'm crawling through code, not book-like text there spaces on either side of every word. example, miss for( , find. there clever way find whole words only? edit: suggestions. how cases in there keyword starts on first entry of string? example, class vec { public: ... }; where i'm searching class (or alternatively public ). patterns suggested thanga, austin lee, npinti, , kai iskratsch not work in case. ideas? in case, issue \b flag punctuation marks, white spaces , beginning or end of string. opening bracket not fall within of these categories,...

indexing - Why my index is not used in a mysql selection -

table definition: create table `titles` ( `emp_no` int(11) not null, `title` varchar(50) not null, `from_date` date not null, `to_date` date default null, primary key (`emp_no`,`title`,`from_date`), ) engine=innodb default charset=utf8 the query is: explain select * employees.titles emp_no < '10010' , title='senior engineer'; +----+-------------+--------+-------+---------------+---------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | | +----+-------------+--------+-------+---------------+---------+---------+------+------+-------------+ | 1 | simple | titles | range | primary | primary | 4 | null | 16 | using | +----+-------------+--------+-------+---------------+---------+---------+------+------+-------------+ my question why first column can use index? know many article/doc give conclusion i'd know detail explanation. my understandin...

css - iFrame Border Showing in WebView React Native -

Image
in attempts dynamically add youtube videos react native app, chose use combination of webview , iframe since current react-native-youtube component doesn't work rn 16^. ultimately, solution work, iframe border still shows , not go away (even css or frameborder = 0), nor can change it's color css. ideas? here's code: video-preview component (where users can see video, title, etc before tapping): module.exports = react.createclass({ render: function() { return ( <touchablehighlight style={styles.touchcard} underlaycolor={'transparent'} onpress={this.props.onpress} > <view style={styles.card}> <webview style={styles.videopreview} automaticallyadjustcontentinsets={true} scrollenabled={false} style={styles.videopreview} html={this.props.source} renderloading={this.renderloading} ...

java - How do I import protobuf files from one folder in another folder in Eclipse? -

i have existing eclipse project including google protocol buffers. i'm trying add new .proto in new folder , include .proto in original folder. when try build get: ..\shared\panicshared.proto: backslashes, consecutive slashes, ".", or ".." not allowed in virtual path how reference .proto in different folder in eclipse? if use absolute file path project not portable. if import "panicshared.proto" without path import line not error inside panicshared.proto have: enum paniclevel { normal = 0; etc. } when try use in message though: import "panicshared.proto"; message panicpremium { repeated paniclevel panicpremiumlevels = 11; } i error: [protoc] panicpremium.proto:9:12: "paniclevel" not defined. [protoc] [libprotobuf warning google/protobuf/descriptor.cc:5411] warning: >unused import: "panicpremium.proto" imports "panicshared.proto" not used. i have solv...

ios - Get phone (GSM) signal strength without use of private API -

i developing ios app in swift , need know gsm signal strength. aware can done private api's coretelephony's ctgetsignalstrength , app has go in app store, can't use private api's. does 1 know of way check signal strength without use of private api's? just quick idea if worried data transfer speed via cellular. place file on server (can image) , download it. measure time before , after has been downloaded. can repeat. if know download time connection, can decide time not ok. you can request server few times headers , determine similar ping in miliseconds. func evaluatedownloadtime() -> double { let start = nsdate(); // start time // download process measure let end = nsdate(); // end time let timeinterval: double = end.timeintervalsincedate(start); // difference in seconds (double). may need miliseconds. return timeinterval } print("time measured: \(evaluatetime()) seconds");

Input numbers without using Enter [c] -

how input number of digits without using enter can enter: scanf("%4d",&num); so how can without press enter? to avoid need hit enter need disable icanon mode using ioctl system call (or stty command - assuming using linux). want use getchar instead of scanf , own input processing. difficult. you can maybe @ post: how avoid press enter getchar()

activerecord - Rails check if field value is the default value for that field -

i have field named number on address model, has default of 0 set @ database level. if address.new.number , 0 back. now, want trigger before_create callback if number != <default value> . so, have before_create :callback, unless: <condition> . how can check using rails "logic"? know can compare 0 , i'd rather compare dynamical value, retrieved rails. default values accessible in address.column_defaults hash of {"column" => default} : address.column_defaults #=> {"number" => 0, "street" => nil, ...} you can use <attribute>_changed? methods rails provides. false unless initialize object non-default value. address.new.number_changed? #=> false address.new(number: 1).number_changed? #=> true so before_create can like: before_create :callback, if: :number_changed?

python - matplotlib make histogram fill plot area -

Image
i doing plot using matplotlib , bothered fact plot area bigger area occupied histogram patches. here problem: you see, rid of empty space between "23" patch end plot's right border. here code: lines = (' '.join(line.strip().split()) line in open(filename) if line.strip()) #prepare date strings local_dates = ( pytz.utc.localize(datetime.datetime.strptime(dt, "%y-%m-%d %h:%m:%s.%f")).astimezone(localtz) dt in lines ) local_dates = list(local_dates) #plot hour of day bins = range(25) n,bins,patches = plt.hist([ t.hour t in local_dates], bins=bins ) xticks_pos = [0.5*patch.get_width() + patch.get_xy()[0] patch in patches] plt.xticks(xticks_pos, range(25), ha='center') plt.xlabel('ora') plt.ylabel('numar de evenimente') plt.title(filename, y=1.03) fig = plt.gcf() fig.set_size_inches(12,8) plt.subplots_adjust(left=0, right=1, top=0.9, bottom=0.1) plt.savefig(filename+'.by_hour.png', dpi=100,bbox_inches=...

wpf controls - WPF application has one more processes -

in wpf application, used 1 graphics application control. graphics control/tool run in separate process , wpf application run in separate process. problem when navigating 1 screen other screen, wpf application window minimized or going behind other applications times. i want problem rectify. please give me solution this.

ios6 - How to minimize iPhone App on button click action? -

on button click want app minimize.. i try use exit() ,but apple reject application when exit being used. what perfect solution this? you not allow without using home button. exit() terminates app. apple surely reject app if achieve anyhow. alternatively, take user screen. don't minimize app. quitting application or sending background programmatically violation of [ios human interface guidelines]

cmd - error "\.. was unexpected at this time" -

i have created .reg add delete empty folders command in context menu. when right click on folder, should delete empty child folders. i have "delete empty folders" in context menu when select this, cmd windows open , error: .. unexpected @ time. idea why? windows registry editor version 5.00 [hkey_classes_root\directory\shell\delete empty folders] [hkey_classes_root\directory\shell\delete empty folders\command] @="cmd /c /f \"usebackq delims=\" %%d in (`\"dir \"%1\" /ad/b/s | sort /r\"`) rd \"%%d\"" the code comes @mmj ( here ) edit : josephz here solution: windows registry editor version 5.00 [hkey_classes_root\directory\shell\delete empty folders] [hkey_classes_root\directory\shell\delete empty folders\command] @="cmd.exe /k /f \"usebackq delims=\" %%d in (`\"dir \"%v\" /ad/b/s | sort /r\"`) rd \"%%~d\"" i don't apprehend why code fails. debugg...

php - Symfony2 Doctrine Metadata Cache with Redis Issue -

i'm trying use redis driver caching doctrine metadata, query , results. follwing configuration. auto_generate_proxy_classes: "%kernel.debug%" naming_strategy: doctrine.orm.naming_strategy.underscore auto_mapping: true result_cache_driver: type: redis host: %redis_host% instance_class: redis query_cache_driver: redis #metadata_cache_driver: redis when remove comment line #metadata_cache_driver: redis, error running test have following error. typeerror: argument 1 passed doctrine\orm\mapping\classmetadatafactory::wakeupreflection() must implement interface doctrine\common\persistence\mapping\classmetadata, string given, called in vendor/doctrine/common/lib/doctrine/common/persistence/mapping/abstractclassmetadatafactory.php on line 214 my functional test looks following: public function testx() { //the data in prepared in setup.. $param1 = 'test-id'; $param2 = 'test-key'; $result =...

networking - How to get Android OS download and upload speed programmatically -

Image
how can current upload , download speed of android device ? i not talking app specific download or upload system. want : how can determine device speed way? know, how show info in notification bar. want know procedure download , upload speed.

sendmail.php - send email to variable AND email address -

this question has answer here: php send mail multiple email addresses 10 answers i have php sendmail script sends email address user input: $to = $_post['email']; how add actual email address go alongside - example: $to = $_post['email', 'foo@bar.com']; thanks you can , using array: $to = array($_post['email'],'foo@bar.com');

typescript - create Observable<T> from result -

i'm trying angular2. i noticed http service use obserable object instead of promise (i don't choice.. asyc/await arriving) in service download list of plants webservice. clicking on plant show details using routing. in way when go back, plants downloaded again (becouse constructor called again). to avoid want like: public getplants():observable<plants[]> { if (this._plants != null) return observable.fromresult (this._plants); //this method not exists return this._http.get('../../res/heroes.json')... } is there way that? how can import observable class in ts file? thanks! this working solution: if (this._heroes != null && this._heroes !== undefined) { return observable.create(observer => { observer.next(this._heroes); observer.complete(); }); } i hope best solution.

c - Cannot find header files -

i working on lwip tcp/ip stack on ti microcontroller board. explain, have 2 source folders "ipv4" , "ipv6". both have corresponding folders header files in "include" folder. both have functions , structs same name. have included paths both. however, giving me errors in of functions in files in "ipv6" folder if cannot find folder header files , instead goes "ipv4" folder header files has same functions different number of arguments. what doing wrong? straight lwip wiki : support ipv6 being added lwip. up version 1.4.x lwip can use either ipv4 or ipv6, not both . code dual stack operation in current development version (which can downloaded git). released version 1.5.0. consider lwip ipv6 quite stable. so unless you're using unstable / dev version, can't use both. sounds attempting what's causing problems.

Draw lines with CSS over an image - responsive behaviour -

i want draw lines on image using css3, preferably html5 canvas. have found tutorial , demo uses html div: http://www.monkeyandcrow.com/samples/css_lines/ however, when try effect on image, line positioned outside of image. how can line drawn directly on top of image? also need line width responsive, i.e., if re-scale browser window, image re-scaled (this have been able using javascript, resizing image dinamically), , need pixel width of image re-scale well. should give , use canvas html5 instead? browser compatibility? the complete code here: <!doctype html> <html lang="es"> <head> <meta charset="utf-8"> <title>lines css</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script> <style> div.line{ -webkit-transform-origin: 0 50%; -moz-transform-origin: 0 50%; transform-origin: 0 50%;...

sql server - SSIS Package stalls when run as a SQL Job -

here short version of problem: have discrete dtsx file works fine on our production server, doesn't on our new dev server. symptom: when run sql-server job, job starts , nothing @ happens, , never finishes... hangs, using little system resources. some info: prod, packages developed on sql-server 2012 , run on nt 2008 server. new dev server sql-server 2012, runs on nt 2012 server (in case matters). have duplicated folder/file structure exactly, including drive name. package uses external dtsconfig file, said - folder/file structure identical. the ssis service, sql-server agent, , remote login same, , member of server administrator group on dev box. if copy command line text sql job , run in cmd window using dtexec.exe, package executes correctly. job owner login, , "run as" sql-agent, - mentioned - same login. since in package uses integrated security, should running using same login whether on command line or via sql-agent, should eliminate user permission/crede...

powershell - Converting a text file with one column to multiple column -

i have file data in 1 column format. need use file input file , output file should in multi column format. need script conversion. not matter powershell or batch. input file content:input.txt store1: apple orange peach the end store2: tree park pond bird the end store3: building road peach store grocery the end the output file should be: store1:,store2:,store3: apple, tree, building orange, park, road peach, pond, peach , bird, store , , grocery i know gimmie, took learning opportunity myself, , since have code maybe else can learn it $text = gc c:\temp\input.txt $groups = ($text | out-string) -split 'the end' | ? {$_ -notmatch '^(?:\s+)?$'} $columns = $groups | % {$_.trim().split("`n")[0]} $rows = $groups | % {$_.trim().split("`n").count - 2} | sort -desc | select -f 1 $result = 0..$rows | % { $row = $_ $obj = new-object psobject 0..$($columns.count-1) | % { $column ...

How to keep formats when I copy a range from Excel to outlook -

hello have excel table formats 10(red) -> 15(green) , @ end loose formats have in excel. use next code send , email range outlook sub email() dim outapp object dim outmail object dim fname string dim hoja string dim rng range dim celdas string set outapp = createobject("outlook.application") set outmail = outapp.createitem(0) set rng = range("c3:q22") on error resume next outmail .to = "juan" .cc = "maria" .bcc = "" .subject = "xxxx" .htmlbody = "hey" & rangetohtml(rng) .display 'or use .display end on error goto 0 'kill fname set outmail = nothing set outapp = nothing end sub and next function, copied next link how send mails excel function rangetohtml(rng range) ' changed ron de bruin 28-oct-2006 ' working in office 2000-2010 dim fso object dim ts object ...

java - Run specific JMH benchmarks from jar -

i have several heavy benchmark classes annotated @benchmark. after bulding jar benchmarks can run of them following command java -xmx4g -jar benchmarks.jar -f 1 -wi 3 -i 10 how specify benchmarks run, if don't want run of them? when in doubt, ask command line help. in fact, running jar -h yields: usage: java -jar ... [regexp*] [options] [opt] means optional argument. <opt> means required argument. "+" means comma-separated list of values. "time" arguments accept time suffixes, "100ms". [arguments] benchmarks run (regexp+). so, supplying regular expression filter helps.

Ruby on Rails externalising Views -

i'm lamp developer making switch ruby development. in php, can split page segments (to maximise code re-use) using separate php files each section. example of being wordpress, have separate header / sidebar / content file etc. is possible using ruby on rails? equivalent of embedding controller / view view? far i'm bit stumped on way embedded because seems there controller has route view, i'm unsure bit try include. what looking called partials . can create partial, such sidebar or footer, render template. the official rails guide contains information using partials . essentially, create file name prefixed underscore such posts/_form.html.erb , render view <%= render partial: "form" %> you can specify absolute path views folder <%= render partial: "/posts/form" %> the same naming conventions of template (e.g. format suffixes) apply.

ios - CoreData, NSPredicate and fetchRequest puzzling behaviour - or is it just me? -

i have encountered odd scenario when using coredata, nspredicate , fetchrequest. my predicate is: predicate = nspredicate(format: "(status == %d) , (watched == no) , (user_id == %@)", argumentarray: [int(itemstatus.shortlisted.rawvalue), false, userid]) if run fetchrequest above predicate, 0 results. if swap user_id clause watched clause, expected result. if use nscompundpredicate, individual clauses broken down sub-predicates, using: request.predicate = nscompoundpredicate(type: .andpredicatetype, subpredicates: [subpredicate1, subpredicate2, subpredicate3]) the outcome expect. i not clear why why there discrepancy between 3 approaches. thoughts? taking guess, (my core data little rusty) looks have specified 3 arguments in argument array, predicate using 2 of them. with (watched == no), you've specified value inline rather "%" delimited format, won't use "false" argument array.

python - Best practice: prepopulate SlugField in Django (without Admin module) -

in days of django possible prepopulate slugfield within model. in admin module use prepopulated_fields = {'slug':('title',),} i found snippet handles unique slugify doubt best way. so best practise autogenerate slugfield without using admin module? id use modelform integrade form in frontpage, should autogenerate unique slug url. this cut , paste 1 of older (as in less coded) models. should show idea, little polish, should work. from django.template.defaultfilters import slugify def get_nickname(self): nick = self.name vowels = ('a','e','i','o','u') first_letter = nick[:1] nick = nick[1:] vowel in vowels: nick = nick.replace(vowel,'') nick = first_letter + nick if len(nick) > 8: nick = nick[:7] return nick def save(self, force_insert=false, force_update=false, using=none): if not self.nickname: self.nickname = self.get_nickname() if len(self...

excel - VLOOKUP based conditional formatting highlights the cell above the intended one -

i'm trying apply conditional formatting column in excel using "use formula determine cells format" feature. in sheet 1 have list of names in column corresponding reference numbers in column b. in sheet 2 have longer list of reference numbers in column c. want conditional formatting rule reference numbers in sheet 1 against in sheet 2 , highlight cell overlap. i have found apparent solution using vlookup formula: =$b2=vlookup($b2,sheet2!$c:$c,1,false) this works in cells in sheet 1 have correct formatting applied, cells have been shifted 1 ( image ). have copied highlighted reference numbers out , done lookup against reference numbers in sheet 2 double-check , top 1 highlighted isn't in sheet 2 1 below filled cells ( image ). i have tried replacing vlookup in conditional formatting index/match function in case there problem vlookup result same: =$b2=index(sheet2!$c:$c,match($b2,sheet2!$c:$c,0)) i've tried removing spaces between xx , numbers in refe...

multithreading - Opening and running a python script in spyder from tkinter -

i hoping there way open '.py' file in spyder , run in correlating ipython console tkinter window. have been able scripts run using threading , os.system, run spyder in ipython here code wrote, run1 works, not open spyder run it. know if exists run2. (i know run_in_spyder not function). perhaps there cmd commands spyder not know of. to_run example script. here backbone of code. import tkinter tk import ttk import tkfiledialog pil import imagetk, image collections import ordereddict import os, sys shutil import copy threading import thread to_run import make_df root_dir = os.getcwd()+os.sep class lippy_ui: def __init__(self, master): self.master = master self.master.geometry('450x300+200+200') self.frame = ttk.frame(self.master) self.style = ttk.style() self.style.theme_use('vista') self.title = master.title('title') self.labeltext = tk.stringvar() self.labeltext.set('w...

javascript - requirejs timing issue - some bootstrap js doesn't work -

i running odd issue ever since starting use requirejs. issue seems happen on sidebar menu items can expanded see sub-menu items. requirejs module called @ end, before body tag, , other js on page works fine, not sidebar menu. appreciated since have been battling days! layout view: <body> ...ouput ommited brevity <ul class="nav nav-list"> <li> <a href="#" class="dropdown-toggle"> <i class="menu-icon fa fa-desktop"></i> <span class="menu-text"> devices </span> <b class="arrow fa fa-angle-down"></b> </a> <b class="arrow"></b> <ul class="submenu"> <li> <a href="#" class="dropdown-toggle"> <i class=...

html - Scrolling Right Div Unknown Width -

i want have scrolling div right don't know width of box needs be. if set auto, stops @ maximum width 100%, when give 100% doesn't either. want inside div go long needs create scrollbar @ bottom. way found working give actual width cannot interpret width of inside div be... here example: https://jsfiddle.net/n0kzm82d/ in example entered width each insider element in theory though know each box's width be, don't know how many divs there. <div style="width: 100%;height: 250px;overflow-x: scroll;overflow-y: hidden;"> <div style="width: 3000px;height: 250px;"> <div style="width:300px;height:250px;float:left;background:red;"> 1 </div> <div style="width:300px;height:250px;float:left;background:blue;"> 2 </div> <div style="width:300px;height:250px;float:left;background:red;...

sql - How to compare varchar parameter to null in a natively compiled stored procedure? -

i migrating tables , stored procedures in-memory optimized tables , natively compiled stored procedures , getting stuck on null comparison. here code: create table [dbo].[myinmemtable] ( [myid] int not null identity(1,1), [mydata] varchar(900) collate latin1_general_100_bin2 not null constraint [pk_myinmemtable] primary key nonclustered ([myid]) ) (memory_optimized = on, durability=schema_only) go create procedure [dbo].[sp_insertintomyinmemtable](@mydata varchar(900)) native_compilation, schemabinding, execute owner begin atomic (transaction isolation level = snapshot, language = n'english') if @mydata not null begin insert dbo.[myinmemtable] (mydata) values (@mydata) select scope_identity() end else select 0 end i following error: msg 12327, level 16, state 101, procedure sp_insertintomyinmemtable, line 306 comparison, sorting, , manipulation of character strings not use *_bin2 collation not supported nat...

Proper user of strong parameters, assignments, and validators in Rails 4? -

what proper way set strong parameters in rails controller , using validators them? i've seen several examples of doing several different ways. this typical controller def looks me: # user model class user < activerecord::base validates :first_name, length: { in: 2..50 }, format: { with: /[a-za-z0-9\s\-\']*/ } validates :last_name, length: { in: 2..50 }, format: { with: /[a-za-z0-9\s\-\']*/ } validates :email, presence: true, length: { 5..100 }, format: { with: /**email regex**/ }, uniqueness: { case_sensitive: false } end # controller def def valid_email # strong parameters defined here? when error thrown unmatched requires/permits? params.require(:user) params[:user].permit(:email) # how prevent blank params[:user][:email] making unnecessary database call if it's blank? @user = user.find_by(email: params[:user][:email]) unless @user.nil? # should work because in permit whitelist? @user.assign_attributes(email: params[:user][:ema...

loops - Javascript interval looping -

how can loop proceed : i have variables : var array = [1,2,3,4,5,6,7,8,9,10] var maximunnumbers = 6 var eachround = 2 i want print numbers : in round 1 : print array[0] , array[1] in round 2 : print array[2] , array[3] in round 3 : print array[4] , array[5] in round 4 : print array[0] , array[1] //numbers repeat here in round 5 : print array[2] , array[3] , on ... var array = [1,2,3,4,5,6,7,8,9,10]; var maximunnumbers = 6; var eachround = 2; var i, k; for( = 0; < 10; ++i ) { var result = 'in round ' + + ' : '; for( k = 0; k < eachround; ++k ) { var array_index = ( ( * eachround ) + k ) % maximunnumbers; result += ' array[' + array_index + '] = ' + array[array_index]; } console.log( result ); } in round 0 : array[0] = 1 array[1] = 2 in round 1 : array[2] = 3 array[3] = 4 in round 2 : array[4] = 5 array[5] = 6 in round 3 : array[0] = 1 array[1] = 2 in rou...

Function to Return Name of HTML Element Containing PHP Code -

i have form in html5 on php page. of form elements contain php code things such populating drop-down menu options. different options put in each menu, populated same php code (called query.php). i want pass name of html element query.php determine query execute. query.php coded generally: <?php $connection = pg_connect(...); $query = "select name table order name asc;"; $results = pg_query($connection, $query); $rows = pg_num_rows($results); ($i=0; $i < $rows; $i++) { ?> <option><?php echo pg_fetch_result($results, $i, 0); ?></option> <?php } ?> i want 'table' in $query variable coming html. here example line of html: <p>select city: <select name="city"><?php include("query.php"); ?></select> i've been trying use http method replacing 'query.php' query.php?table=$this.name . understand should able use $_get['table'] in query.php , passed value,...

c# - LinqToExcel Duplicate Column Names -

i have machine generated excel file has few columns same name. e.g.: b c d group 1           group 2 period | name     period | name and got dto this: [excelcolumn("period")] public string firstperiod { get; set; } [excelcolumn("name")] public string firstname { get; set; } [excelcolumn("period")] public string secondperiod { get; set; } [excelcolumn("name")] public string secondname { get; set; } i use following command read lines: var excel = new excelqueryfactory(filepath); excel.worksheetrange<t>(begincell, endcoll + linescount.tostring(), sheetindex); it reads file fine, when check content of dto saw 'second' properties have same values of 'first' ones. this post closest thing found in searches , think problem solved this: excel.addmapping<mydto>(x => x.firstperiod, "a"); excel.addmapping<mydto>(x => x.firstname, "b"); excel.addmapping...

linux - Hadoop daemons can't stop using proper command -

running hadoop system run daemon jobs namenode, journalnode, etc. use namenode example. when start namenode can use command: hadoop-daemon.sh start namenode when stop namenode can use command: hadoop-daemon.sh stop namenode. but here comes question, if start namenode yesterday or couple of hours ago, stop command work fine. if namenode has been working 1 month. when using stop command, show: no namenode stop. but can see daemon namenode running using command jps. have use kill command kill process. why happen? way make sure stop command can work? thanks the reason why hadoop-daemon.sh not working after time because in hadoop-env.sh there parameters called: export hadoop_pid_dir export hadoop_secure_dn_pid_dir stored pid number of daemons. default location of directory /tmp. problem /tmp folder automatically cleaned after sometime(red hat linux). in case pid file deleted, when run daemon command, command can't find process id stored in file. same reson ya...

authentication - Deploy SQL Server Database to Hosting Environment -

i want deploy web application including sql server 2008 database local machine hoster. so far used windows authentication, necessary switch username , password when want make application public on internet? and if that's case, what's best practice hide information if saved strings in web.config ? side note: use linq entities object mapper , within code use httpcontext.current.user authenticate user if not using shared hosting, can keep using windows authentication more secure having sql server user. you should disable remote connections no 1 can directly access sql server make more secure. for encrypting connection string check site .

c++ - Language feature to apply function to each element of a parameter pack -

does know, if there exists standards proposal c++ language feature allow me replace (thanks yakk): template<class... args> void bar(const args& ... args) { auto t = { (foo(args),0)... }; (void) t; //<- prevent warning unused variable } with more natural this: template<class... args> void bar(const args& ... args) { foo(args)...; } foo being e.g. function, function template and/or overloaded set of those, return type might void (or in general don't care about). btw, if knows more concise way write in c++14, feel free share, think, handled in this question use fold expression comma operator: ( void(foo(args)) , ...); i didn't see proposal change further in recent mailings.

c++ - Converting std::vector to char* -

i c++ student working on project receive , encode message simple cipher. so, program accepts each word string, converts string vector of characters, , modifies each character before storing in file. in line returns encoded message main function, error message: < cannot convert std::vector<char, std::allocator<char> >' to char*' argument 1' to char* cipher(char*, int)' . despite error, program run, however, stop after word has been entered , end program. code using: // cipher.cpp // program accepts message , encodes // written grindle #include<iostream.h> #include<string.h> #include<iomanip.h> #include<math.h> #include<fstream.h> #include<vector.h> using namespace std; string get_message(); // function prototypes char* cipher(char broken[], int length); int main() { int index, length; // declare index vectors string message; // declare string ofstream outfile; // declare filestream outfile.open(...

php - laravel socialite error when user cancels -

i'm creating laravel 5 app, has social authentication inbound, have code user, register or log in in case user exists, works fine. issue when user not agreed login social provider app(eg, press cancel button), knows how handle that. now if press cancel button on social login window throws 400 client error. thanks in advance you can use try-catch. move login/registration code inside try block & inside catch block, redirect user login page & show appropriate message

java - hibernate table per concrete class @AssociateOverride still using parent attribute to join -

i implemented hibernate table per concrete class. , model following, @entity @inheritance(strategy=inheritancetype.table_per_class) @tablegenerator(name="baseform", table="baseform_sequence", allocationsize=1) public abstract class baseform implements serializable { @id @generatedvalue(strategy = generationtype.table, generator="baseform") @xmltransient protected long id; public long getid() { return id; } public void setid(long id) { this.id = id; } @joincolumn(name = "form_id") @onetomany(cascade = cascadetype.all, fetch = fetchtype.eager) @cascade(value = org.hibernate.annotations.cascadetype.delete_orphan) @fetch(fetchmode.subselect) @orderby("id") protected list<casenumber> casenumberlist = new arraylist<casenumber>(); public list<casenumber> getcasenumberlist() { return casenumberlist; } public void setcasenumber...

symfony - ManyToMany relationship with extra fields in symfony2 orm doctrine -

Image
hi have same question here: many-to-many self relation fields? cant find answer :/ tried first manytoone , @ other site onetomany ... not use like public function hasfriend(user $user) { return $this->myfriends->contains($user); } because there problem: this function called, taking user type $user variable , use contains() function on $this->myfriends. $this->myfriends arraycollection of requests (so different type user) , doctrine documentation contains(): the comparison of 2 elements strict, means not value type must match. so best way solve manytomany relationship fields? or if go , set onetomany , manytoone relationship how can modify hasfriend method? example check if id in array collection of id's. edit: have table... , need is: 1. select friends... , followers ...check if friend him or not. (because can friend me , dont have him... on twitter). make manytomany need fields like: "viewed" "time when subscribe me...

java - Add list of files in a folder -

i developing application , need save files in directory each user. half i've writen, i'm unclear how add files directory. public boolean addfiles(string name,list<file> files){ string path = "d:\\server repository\\usersfiles\\"; file folder = new file(path + name); if(!folder.exists()) folder.mkdirs(); for(file file:files){ //my code //if ended success return true } return false; } if don't want 3rd party libs fileutils, , want simple code copy files, can this: public boolean addfiles(string name, list<file> files) { string path = "d:\\server repository\\usersfiles\\"; file folder = new file(path + name); if (!folder.exists()) { folder.mkdirs(); } try { (file file : files) { fileinputstream fisorigin; fileoutputstream fosdestiny; //channels filechannel fcorigin; filechannel...