Posts

Showing posts from February, 2013

dependency injection - ASP.NET 5 DI Connection String into ADO.NET -

good morning, we migrating away ef using ado.net our backend. ef, easy inject connection string. however, unable figure out how standard service. code is: services.addscoped<idatacatalogrepository, sqldatacatalogrepository>(); currently going through dependency injection test project on github not seeing need. want is: services.addscoped<idatacatalogrepository, sqldatacatalogrepository>("connectionstring") sqldatacatalogrepository have connectionstring 1 of constructor properties. using beta 4, ideas? steven m. what need factory. addscoped method use have few overloads including ones implementationfactory parameter. your code this: private static readonly func<iserviceprovider, idatacatalogrepository> repofactory = (_) => { var connectionstring = "get connection string somewhere"; return new sqldatacatalogrepository(connectionstring); } and calling addscoped this: services.addscoped<idatacatalog...

python - Matching range of timestamps in pandas -

i having trouble doing in pandas df1 (my left join): name | timestart | timeend | values | order john 12/24/2014 08:10:32 12/24/2014 08:14:21 2 1 john 12/24/2014 08:15:03 12/24/2014 08:22:49 2 2 df2 name | timestart | timeend | values john 12/24/2014 08:12:57 12/24/2014 08:13:31 8 timestart in df2 greater timestart in df1 (this typically happens during interaction). , match, have less next row of data individual. here thought process. shift row columns see if match. compare df2 timestart > initial timestart on df1 less next row timestart (same name). df1.sort(['name', 'timestart'], ascending=[1, 1], inplace = true) df1['name_r'] = df1['name'].shift(-1) df1['matching row'] = np.where((df1['name_r'] == df1['name']), 1, 0) df1['next timestamp'] = np.where(df1['matching row'] == 1, df1['timesta...

regex - htaccess 301 redirect -- remove a string -

i trying htaccess 301 redirect, stuck. what want remove string in url, string is: style=5& i want redirect pages may string in url removed. -- in advance. from: /viewtopic.php?style=5&f=45&t=1980&p=19136 to: /viewtopic.php?f=45&t=1980&p=19136 you can use code in document_root/.htaccess file: rewriteengine on rewritecond %{query_string} ^(.+?&)?style=5(?:&(.*))?$ [nc] rewriterule ^viewtopic\.php$ %{request_uri}?%1%2 [r=302,nc,l]

objective c - iOS Messages App UITableViewCell Insert Animation -

what wondering how can go achieving animation ios messages app animation whenever send message. animation takes text text field inside inputaccessoryview , animates uitableviewcell. you may wanna try cocoacontrol, gives full messaging ui ios one. i tried find animation code , achieved (is not close solution, didnt find observer called): - (void)finishsendingmessageanimated:(bool)animated { uitextview *textview = self.inputtoolbar.contentview.textview; textview.text = nil; [textview.undomanager removeallactions]; [self.inputtoolbar togglesendbuttonenabled]; [[nsnotificationcenter defaultcenter] postnotificationname:uitextviewtextdidchangenotification object:textview]; [self.collectionview.collectionviewlayout invalidatelayoutwithcontext:[jsqmessagescollectionviewflowlayoutinvalidationcontext context]]; [self.collectionview reloaddata]; if (self.automaticallyscrollstomostrecentmessage) { [self scrolltobottomanimated:animated]; ...

excel - Matching a cell to the closest highest value in another range -

i have number on "buildup" tab of excel workbook , list of random numbers on "oh" tab of same workbook. trying match number on buildup tab closest highest value on oh tab. found formula online , tweaked cell references , sheet names, seems match closest number , not highest closest number: =index(oh!$b$2:$b$250,match(min(abs(buildup!ac8-oh!$b$2:$b$250)),abs(buildup!ac8-oh!$b$2:$b$250),0)) oh sheet list of random numbers. buildup!ac8 cell reference of number i'd match closest highest value on oh tab. i use array formula small or min function, entered ctrl + shift + enter : using small : =small(if(oh!$b$2:$b$250>=buildup!ac8,oh!$b$2:$b$250),1) using can increment 2nd highest, 3rd highest, etc. based on second parameter. return #num! if no match found. using min : =min(if(oh!$b$2:$b$250>=buildup!ac8,oh!$b$2:$b$250)) as @byron pointed out, will return 0 when there no large number match, small might preferred.

java - Comparing current date time(live) with file last modified -

Image
i want program output such that, whenever receives text file client, print "a new file has been received!". text files store in c:/users/%userprofile%/desktop/ad. the code below check whether new text file has been received directory. import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.io.file; import java.text.dateformat; import java.text.simpledateformat; import java.util.calendar; import java.util.date; import javax.swing.timer; public class test { final dateformat dateformat = new simpledateformat("yyyy/mm/dd hh:mm:ss"); static int count = 0; static file[] f = null; static date date = new date(); static calendar = null; public static void main(string[] args) { dateformat dateformat = new simpledateformat("yyyy/mm/dd hh:mm:ss"); while(true) { try { thread.sleep(2000); } catch (interruptedexception e1) { e1.print...

Generics C# No Boxing Conversion - No Implicit Conversion -

i'm going try make clear possible! the end goal being able access protected method within abstract class. method inherited abstract class too. the abstract class has generic, need class generic (ie creating generic adapter). here abstract class (well similar structure). public abstract class myabstract<t> : abaseclass<t> t : someclass { } here base class inherited abstract class(has method need) public abstract class abaseclass<t> : anotherbase, idisposable t : someclass, someclass2 { protected void foo(t somevar); } the classes above within dll, not have access to. here's trying do, need in right direction! public mainclass<t> : myabstract<t> t : someclass { public void somefunct() { this.foo(avariable); } } your class should this: //uncomment ", new()" if want create new instance within somefunct method public class mainclass<t> : myabstract<t> t : someclass//, new() {...

sql server 2008 r2 - Access denied SSIS w/ Parameters via xp_cmdshell -

i have searched , down solution , cannot find helps. have tried doesnt seem work. i have 2 database. cannot modify database adding table or that. cannot enable cross-database access. believe cant use sp.start_job because need pass parameters. able enable xp_cmdshell. my database definition: database - order table database b - email notification table what need do: any time order entered database a, need enter row database b values of order. need have parameters what have tried: - xp_cmdshell @query='dtexec /f "\\server\folder\ssis packages\order confirmations\order confirmations\package.dtsx" /decrypt password' 1. error saying access denied. tried setting sp_xp_cmdshell_proxy_account (##xp_cmdshell_proxy_account##) account has access network drive file stored, no luck. 2. whoami.exe shows nt/authority \system instead of proxy account. 3. grant execute on xp_cmdshell [mydomain\myaccount] didnt have affect. whoami results ...

Automapper mapping 2 entities to a single class -

just wondering if possible: say have viewmodel comparing old , new entity. public class foocomparison { public string name {get;set;} public string oldname {get; set;} public int age {get; set;} public int oldage {get; set;} ... } i want load 2 instances of foo database , populate foocomparison details both instances. for now, have mapper.createmap<foo, foocomparison>() populate name, age etc first entity - there easy way populate oldxxx properties second entity without looping , manually updating them? my suggestion define mapping tuple<foo, foo> foocomparison : mapper.createmap<tuple<foo, foo>, foocomparison>() .convertusing(x => new foocomparison { name = x.item2.name, oldname = x.item1.name, age = x.item2.age, oldage = x.item1.age, ... }); then use this: foo oldfoo = ...; foo newfoo = ...; foocomparison comparison = mapper.map<foocomparison>(tuple.create(oldfoo, newfoo)...

django - Using a custom reverse manager in Filter -

given have: class publisher(model): pass class author(model): name = models.charfield(...) publisher = models.foreignkey(publisher) is_alive = models.booleanfield(...) objects = models.manager() # default manager alives = alivemanager() # custom manager right can filter using: publisher.objects.filter(author__name='xxx', author__is_alive=true) my question there anyway take advantage of custom reverse manager in filter statement? publisher.author_set(manager="alives") gives me given publisher. i guess relevant bit in docs: [...] default filtering in get_queryset() method, filtering apply all() call. class alivemanager(manager): def get_queryset(self): qs = super(alivemanager, self).get_queryset() return qs.filter(is_alive=true) class author(model): name = models.charfield(...) publisher = models.foreignkey(publisher) is_alive = models.booleanfield(...) objects = models.manager() # ...

jquery - How to add custom message in Highchart's printed image? -

basically want image exported highchart should display custom message along chart i see 2 options, both based on load event. one check chart.options.chart.forexport flag. when flag set true , add elements on chart using chart.renderer . see demo , more info renderer . second option, same, in exporting.chartoptions.chart.events.load callback. callback used when exporting chart.

c# - Custom delivery UI extension generates "Invalid Class Name" error -

i've done nothing more compile sample ssrs delivery extension , deploy server per instructions. when make call reportservice2010 listextensions web service method, extension shows in list of results. however, when go create subscription in report manager , choose printer delivery sample drop-down list of available delivery extensions, error: invalid class name i'm running ssrs 2012 sp2 (11.0.5569.0) on windows server 2012 r2. edit: found in logs: it turns out reportmanager (the asp.net ui) does log c:\program files\microsoft sql server\msrsxx.mssqlserver\reporting services\logfiles directory. saw subscription- (i.e. service-)related events in files , assumed if reportmanager did log, files must elsewhere. extensionfactory!reportmanager_0-3!53c!06/02/2015-16:27:40:: e error: exception caught instantiating printer delivery sample report server extension: system.security.securityexception: request permission of type 'system.web.aspnethostingper...

mysql - How to write database migration in sails.js application -

i tried using https://github.com/building5/sails-db-migrate module creating migrations did not run correctly. table used generated few columns missing. there better way create , run migrations? sorry new sails, migrated php. so, turn out stupid think need module write migration in sails. turn out on sails lift application automatically creates table attributes of model. but on trying realized waterline module takes care of not create foreign-key constraints of now.they still working on it. if using nosql db can use associations http://sailsjs.org/#!/documentation/concepts/orm

big o - Intro to Algorithms (chapter 1-1) -

just reading book fun, isn't homework. however confused on first main assignment: 1-1 comparison of running times for each function f(n) , time t in following table, determine largest size n of problem can solved in time t, assuming algorithm solve problem takes f(n) microseconds. what mean? the next table shows bunch of times along 1 axis (1 second, 1 minute, 1 hour, etc), , other axis shows different f(n) such lg n, sqrt(n), n, etc. i not sure how fill in matrix because can't understand question. if f(n) = lg n, it's asking largest n can solved in, example, 1 second, problem takes f(n) = lg n microseconds solve? last part mean? don't know how set equations / ratios solve problem because literally can't put meaning of question. my hangup on sentence "assuming algorithm solve problem takes f(n) microseconds" because don't know refers to. time what algorithm solve what problem takes f(n) microseconds? if call f(100) it'll take lg...

php - Generating unique numbers that pass Luhn algorithm verification -

i trying generate unique numbers can verified luhn algorithm. aim provide account numbers, speak, members on p2p lending platform. i've been looking luhn algorithm , couple of other check digit algorithms, information on verifying numbers these algorithms i'm looking pointers on generating numbers pass check digit algorithm. i'm using php project. any pointers or recommendation appreciated. the luhn algorithm generates additional checksum digit arbitrary number. means can turn number n digits luhn-compatible number n  + 1 digits. the wikipedia article on luhn algorithm explains how generate such check digit: set rightmost digit, check digit, zero. work right left , add digits. alternate between digit , digitsum of 2 times digit. determine check digit whole sum's last digit zero. if have unique number can make luhn compatible with: function luhnify($number) { $sum = 0; // luhn checksum w/o last digit $even = true; //...

Weceem plugin and Grails regarding Content publishing workflow -

i published content user. admin want modify content , don't want publish until it's approved. in case save draft , not want user see it. but when user try access page, can see changes saved draft. how can restrict user see these changes saved in draft. if saved content draft should not available user role 'role_guest' example, available user-admin ('role_admin') because of default weceem security policy. try login guest , check once again. weceem security police config can read there http://jcatalog.github.io/weceem-plugin/guide/4.usersguide.html#26.controllingaccess , here http://jcatalog.github.io/weceem-plugin/guide/5.weceemsecuritpolicy.html

plot - RStudio creates the graph, but Markdown will not -

i'm running short snippet of code , can create graph in rstudio plot window, when run markdown, following error: error in hist(p.rating): object 'p.rating' not found here code i'm using: {r loading data, include=false} setwd("~/google drive/new leaders/data/knowngroups") mydata <- read.csv("copy of gates study data download (052815_v2).csv") attach(mydata) colnames(mydata)[5] <- "p.rating" {r fig.width=7, fig.height=6} hist(p.rating) thanks! the histogram statement @ end has column name without data set. should help: hist(mydata$p.rating)

file - Python, open for writing if exists, otherwise raise error -

is there option can pass open() cause ioerror when trying write nonexistent file? using python read , write block devices via symlinks, , if link missing want raise error rather create regular file. know add check see if file exists , manually raise error, prefer use built-in if exists. current code looks this: device = open(device_path, 'wb', 0) device.write(data) device.close() yes. open(path, 'r+b') specifying "r" option means file must exist , can read. specifying "+" means can write , positioned @ end. https://docs.python.org/3/library/functions.html?#open

jquery - Javascript hide content in label tag and label tag after -

i want hide text based on text in label tag , want hide text in next label tag to. know how make hide username cause text same, don't know how make hide users message. here's code looks like: <div id="chatbox"> <label id="cnick">otherusers:</label> <br> <label id="cmsg">some random text</label> <div id="cspc"></div> <br> <label id="cnick">blockme:</label> <br> <label id="cmsg">some random text</label> <div id="cspc"></div> <br> <label id="cnick">blockme:</label> <br> <label id="cmsg">some random text</label> <div id="cspc"></div> <br> <label id="cnick">otherusers:</label> <br> <label id="cmsg">some random text</label> <div id=...

Google Maps initialize() with new JSON mapOptions won't work -

this standard google code , loads map fine. var mapoptions = { center: { lat: -34.397, lng: 150.644 }, zoom: 8 }; function initialize() { var map = new google.maps.map(document.getelementbyid('map-canvas'), mapoptions); } google.maps.event.adddomlistener(window, 'load', initialize); but, after search xml file values , set them mapoptions, won't initialize god of me. i've tried everything. $(xml).find("location").each(function(){ var lat = $(this).find("lat").text(); var lng = $(this).find("lng").text(); mapoptions.center.lat = lat; mapoptions.center.lng = lng; initialize(); }); i added alerts inside initialize() , work new coordinates xml. why won't map load beyond me... function initialize() { alert(mapo...

excel - VBA if then function always returning 0 -

my friend , have searched internet answer. new vba , function returning 0. great. below code: function onlineabs(x date, y date, z date) if x > 0 if y > 0 result = "online - images" else if z > 0 result = "online - dt images" else result = "online - no images" end if end if else result = "abstract" end if end function function returns in vba little different . setting value want returned function name return value. function onlineabs(x date, y date, z date) if x > 0 if y > 0 onlineabs = "online - images" else if z > 0 onlineabs = "online - dt images" else onlineabs = "online - no images" end if end if else onlineabs = "abstract"...

Swift - sprite kit - make SKPhysicsJointPin have less motion -

i'm trying create snake multiple body parts moves left , right. im using pin, upon snake stopping, body keeps moving , doesn't stop. i've messed around max , min angles, , torque, nothing seems work. should use different type of joint? sorry cant log other account, heres code. second part wobbles lot. wish add 7-8 parts, keep on wobbling, after moving "head". fluid "swoop" motion when move snake. self.physicsworld.gravity = cgvectormake(0, -100) self.physicsworld.contactdelegate = self head.size = cgsize(width: 25,height: 25) head.physicsbody = skphysicsbody(texture: head.texture, size: head.size) head.position = cgpointmake(100,400) head.anchorpoint = cgpoint(x: 0.5, y: 1) head.physicsbody!.dynamic = false head.zposition = 3 self.addchild(head) var p1 = skspritenode(imagenamed: "snakebodypart.png") p1.size = cgsize(width: 25,height: 25) p1.physicsbody = skphysicsbody(texture: p1....

c# - TextBox binding is not working -

i have 2 usercontrols : 1) contactdetailsview . 2) searchbarview . in the searchbarview , have search button, raises command when clicked: command="{binding searchcommand}" in searchbarview code behind, have following code: datacontext = new searchbarviewmodel(); in contactdetailsview have following code: xmlns:viewmodel="clr-namespace:accounts_manager.usercontrols.searchbar" in definition of usercontrol , code underneath it: <usercontrol.datacontext> <viewmodel:searchbarviewmodel /> </usercontrol.datacontext> i have textbox following definition: <textbox x:name="contactnametextbox" fontfamily="times new roman" foreground="darkred" horizontalalignment="stretch" horizontalcontentalignment="center" isenabled="false" grid.column="0" text="{binding contactid, mode=twoway, updatesourcetrigger=propertychanged}"/> i have class called sea...

c# - Delete statement conflicts with Reference constraint -

i assume has simple answer. brand new entity framework , creating test application consisting of contacts , groups objects/entities. here code delete group: private void button_deletegroup_click(object sender, eventargs e) { var _selectedgroup = datagridview_groups.selectedrows[0].databounditem group; try { cgcontext.groups.remove(_selectedgroup); cgcontext.savechanges(); populategroupgrid(); messagebox.show("successfully deleted group database!"); } catch(exception ex) { messagebox.show("failed delete group database.\r\n\r\n" + ex); } } if delete group contact belongs to, test referential integrity, exception thrown (as should): "the delete statement conflicted reference constraint "fk_dbo.contacts_dbo.groups_group_id". conflict occurred in database "contactgroups", table "dbo.contacts", column 'group_id...

browser - XPages: Notes-Object of type org.openntf.domino.impl.Document is used across threads -

can explain means? don't have clue... not when it's happening. i'd happy supply code, wouldn't know start. thanks. more on message: com.ibm.xsp.exception.evaluationexceptionex: error while executing javascript computed expression error while executing javascript computed expression erreur d'interpréteur de script, ligne=1, colonne=17 : [typeerror] exception lors de l'appel de la méthode notesxspdocument.getitemvaluestring(string) notes-object of type org.openntf.domino.impl.document used across threads! thread: thread[thread-8,5,main] correct thread: thread[thread-11,5,main] notes-object of type org.openntf.domino.impl.document used across threads! thread: thread[thread-8,5,main] correct thread: thread[thread-11,5,main] java.lang.illegalstateexception: notes-object of type org.openntf.domino.impl.document used across threads! thread: thread[thread-8,5,main] correct thread: thread[thread-11,5,main] the document opens normally. error occurs wh...

javascript - Performance limitations of angular filters on mobile -

i have 3000 objects each number of properties creating 72,000 line 2mb json file. the json database of objects need filtered text search filter , matching values against array of values. in initial view perform in service : this.loadjsonfile = function(url, process) { var defer = $q.defer(); if (angular.isdefined(cache[url])) { if (angular.isdefined(cache[url]['then'])) { return cache[url]; } defer.resolve(cache[url]); return defer.promise; } $http.get(url).success(function(data) { if (process) { data = process(data); } cache[url] = data; defer.resolve(data); }).error(function(err){ defer.reject(err); }); cache[url] = defer.promise; return defer.promise; }; this.getexercises = function() { return this.loadjsonfile('data/exercises.json'); }; and in controller results exposed $scope by: api.getexcercises().then(function(data) { $scope.allexe...

javascript - Style SVG with CSS -

i using chartist plugin generating charts. i've noticed different element generations through browsers. in internet explorer, uses <text> element, offset on left 70px. want move element on right 70px, can't achieve this. i've tried text-anchor , transform , letter , word spacing hacks, none of them work. here code trying modify: <text class="ct-label ct-horizontal ct-end" x="25" y="205" width="179" height="20">feb-2015</text> so, instead of x-20, want x-90. here live demo correct (but possibly slow) solution this is bug of chartist library. calculating label position not center-aligned category. for permanent solution, need take them, bug fixed on side. you can find author's contact details on this github page . temporary solution in interim, can apply dirty fix shifting whole labels block right. as ie11 ignores transform properties applied via css, need apply direc...

c# - How to know if application insights telemetry client is functional? -

this code execute without errors, not log in applicationinsights. foobar key not valid. var client = new telemetryclient { context = { instrumentationkey = "foobar" } }; client.trackevent(telemetryevent); i understand may thing. dont want application crash because appinsights not avalaible. nice know somehow not reachable, can else instead. possible errors think append : the api not reachable the event malformed the api key invalid etc. some of these may transcient (api temporary not available), others may not (invalid api key). is there way "test" client react these cases? something : if (!client.isappinsightreachable) { //send email can check if ok } if wanted it, could, might lot of work re-inventing wheel. you'd have lot of work yourself, implementing or wrapping things itelemetrychannel want. much of source various application insights sdks on github :

android - Execute code every time the application begins -

i execute code every time application begins (not first time application begins getsharedpreferences doesn't help ). i've tried write code in onstart() of main activity, code executed everytime entered activity including times activity other activities (so onstart() doesn't help ). if can direct me this, i'll appreciate that. thanks. create application class - everytime application opens execute oncreate method. //note extends application , not activity. public class myapplication extends application { @override public void oncreate() { super.oncreate(); //put code here. } make sure register in manifest - <application android:name=".myapplication" any code put in oncreate execute when app opened.

jquery - Javascript Parent/ Child Id Control -

can name of window opened using window.open changed dynamically main parent? we have menu system opens new windows when link clicked. new window has other windows can opened it. method works fine in 1 session environment. when users try open second window same option first window replaced. know due them both using same name. can main menu program coded change name each time menu item clicked? can same menu program change name of children windows first window? the best method can think of finding way javascript listener opened , triggers each time link clicked, within each separate parent/child tree. don't know if possible. i know have option append unique number each window.open command name, looking way allow menu program handle this. i looking method won't require changing child programs. thank you.

vb.net - VirusTotal API Usage Example? -

i'm trying use virustotal api. doesn't works can show me example how upload , link of output scanned file? there documentation @ https://www.virustotal.com/en/documentation/public-api/ then @ bottom of page there 3rd party scripts in every language lots of examples.

winapi - c++ PE injecting additional functionality -

for example have simple c++ main function int main () { (int = 0; < 10; i++) sleep(10); return 0; } so exe shuts down after 10 seconds start. question: there way join(concatenate) 2 pe-applications? trying program c++ unite 2 apps new one. example: ill run program parameter app: my_app.exe %windir% / calc.exe exe wrapper general description exe wrapper command line utility can compile , output “launcher” exe works input exe few additional features. wrapper must command line based on takes 3 input variables: 1. windows executable file 2. expiry datetime 3. url server instructions , “download exe” example command: wrapper.exe “input_exe.exe” “20150528 15:00:00” “ http://pemainin . com/launch_askar.php?pid=2&tid=123&n=test” output wrapper new exe file appear similar possible input exe. if expiry time not set @ all, output exe should act if exe expired start. output exe should act follows what trying build called "binder". can achieve...

sas - Standardising dataset attributes across projects -

background: i have multiple old projects need standardise ( prj01 - prj10 ). each stored under own libname , each has around 30 datasets (note: not studies have same 30 datasets). the variable names have remained consistent across projects. however, on years, labels , formats have been assigned these variable names have changed in places - example below: attribute inconsistencies between studies: data prj01.users(label='user identifiers') ; attrib userid label='username' format=$20. ; run ; data prj02.users(label='user identifiers') ; attrib userid label='name of user' format=$15. ; run; attribute inconsistencies within studies: data prj02.users(label='user identifiers') ; attrib userid label='name of user' format=$15. ; run; data prj02.orders(label='orders') ; attrib userid label='name of user' format=$15.) orderno label='order number' format=8. ; run ; i have writte...

addAttributeToFilter on magento return incorrect -

i got problem when overriden mage_catalog_block_product_list class in magento. goal add filter @ overriden class. code public function getloadedproductcollection() { $collection = parent::_getproductcollection(); $collection->addattributetofilter('model', array('eq' => 'coucu')); var_dump($collection->count()); // return 1 (incorrect) var_dump($collection->getdata()); // return empty (correct) return $collection; } i need after filter don't have product! most of time due collection being loaded. have know magento collection load once (to save db access) because there flag _setisloaded on underlaying varien_data_collection stop reload it. what can try public function getloadedproductcollection() { $collection = parent::_getproductcollection(); var_dump($collection->isloaded()); return $collection; } if displays true means collection loaded , addattributetofilter won't ever execute...

C - char array and char pointer -

why can't define array char **pp={ "123", "456", "789" }; but can define char*[] ,and send function accept char ** char *pp[]={ "123", "456", "789" }; fun(pp); void fun(char **pointertopointer) { //++(**pointertopointer);//error printf("%s", *pointertopointer); } //output::"123" and why can't increment ++(**pointertopointer); to answer first question, principles might clearer if use single depth of pointer. code illegal same reason: int *ptr = { 1, 2, 3 }; in c, braced initializer list not object (especially not array). can taken list of items read initializers when object being initialized. ptr 1 object, @ 1 initializer taken, , expected form of initializer pointer (which 1 not). in fact code explicitly illegal under c11 6.7.9/11: the initializer scalar shall single expression, optionally enclosed in braces however, there gcc bug/feature permits ex...

extjs - Ext JS chart Tooltip not rendering under mouse pointer -

i trying add tooltips extjs chart. tooltip getting rendered not under mouse pointer. getting rendered near end of page. ext.create('ext.chart.chart', { renderto: ext.getbody(), width: 470, height: 300, store: store, axes: [{ type: 'numeric', minimum: 0, minorticksteps: 0, maximum: 150, position: 'left', fields: ['liney', 'greeny', 'yellowy', 'redy'], title: 'buffer penetration' }, { type: 'numeric', position: 'bottom', fields: ['linex', 'areax'], title: 'critical chain comp' }], series: [ { type: 'area', axis: 'left', xfield: 'areax', yfield: ['redy'] }...

java - How to return a 400 status code, but return an int -

i want instead of null pointer exception in java method return new responseentity<string>(httpstatus.bad_request); method returns int not string. main thing want return 400 status code. can do? i tried throw new illegalargumentexception(arg + "is not valid argument; positive value expected"); returns 500 status code message. i'm doing on web service if helps. i tried return new responseentity<integer>(httpstatus.bad_request); , doesn't seem work either.

ios - Touchesbegan method inactive from viewcontroller -

when adding uiimageview viewcontroller, want make touchesbeganmethod inactive till uiimage pressed. now have set up, need know how can prevent gamescene noticing touches setting code (only) in viewcontroller. anyone knows how? gamescene.paused = true // pauses game, touchesbegan method still active! you set userinteractionenabled false on view want disable touches or check on begining in touches began this: if gamescene.paused == true { return }

android - How to disable RecyclerView scrolling? -

i cannot disable scrolling in recyclerview . tried calling rv.setenabled(false) can still scroll. how can disable scrolling? you should override layoutmanager of recycleview this. way disable scrolling, none of ther other functionalities. still able handle click or other touch events. example:- original: public class customgridlayoutmanager extends linearlayoutmanager { private boolean isscrollenabled = true; public customgridlayoutmanager(context context) { super(context); } public void setscrollenabled(boolean flag) { this.isscrollenabled = flag; } @override public boolean canscrollvertically() { //similarly can customize "canscrollhorizontally()" managing horizontal scroll return isscrollenabled && super.canscrollvertically(); } } here using "isscrollenabled" flag can enable/disable scrolling functionality of recycle-view temporarily. also: simple override existing implementation disable scrolling , allow clic...

MemSQL geospatial union of polygons -

will new memsql version able calculate union of polygons? example calcuate border of 2 adjacent or intercepting polygons? +----+ | | | +-+--+ +--+-+ | | | +----+ to +----+ | | | +--+ +--+ | | | +----+ memsql 4 includes topological functions (eg, geography_intersects()) return boolean, , measurement functions distance , length. not yet have constructor functions intersection(), output polygon describe. it's on roadmap, though.

oracle11g - Scheduling a backup recovery in oracle 11g -

Image
i'm trying schedule backup recovery oracle 11g database, use above script windows task scheduler : rman target/ run { shutdown immediate; startup mount; backup incremental level 0 database plus archivelog delete input; backup archivelog delete input; delete force noprompt obsolete; backup current controlfile spfile; alter database open; } the scheduler started @ specified time, backup doesn't start. when excute backup via : rman works fine. ========what got widows scheduling task=========== =========what should (it's working fine without task scheduling)=== obviously, run script isn't working : run { shutdown immediate; startup mount; backup incremental level 0 database plus archivelog delete input; backup archivelog delete input; delete force noprompt obsolete; backup current controlfile spfile; alter database open; }

java - How to upload an image to server? -

i building project spring boot , want upload image server (on local server). code uploading file : @controller @requestmapping("/api/v1") public class imagecontroller { @requestmapping(value="/upload", method=requestmethod.get) public @responsebody string provideuploadinfo() { return "you can upload file posting same url."; } @requestmapping(value="/upload", method=requestmethod.post) public @responsebody string handlefileupload(@requestparam("name") string name,@requestparam("email") string email, @requestparam("file") multipartfile file){ if (!file.isempty()) { bufferedimage src; try { src = imageio.read(new bytearrayinputstream(file.getbytes())); file destination = new file("/"+system.getproperty("user.home")+"/samepinchbucket/"+email+"/pics/"); i...

php - I fail to display the value of a select in JavaScript -

i have list of countries. use geonames's function detect country , display in list. works. however, i'd retrieve value, try display first value appears. code : <!-- code html countries list --> <select id="countryselect" name="country"> <?php $reponse = $bdd->query('select * pays'); echo '<option value="">pays</option>'; while ($donnees = $reponse->fetch(pdo::fetch_assoc)) { echo '<option value="'.$donnees["id_pays"].'">'.$donnees["pays"].'</option>'; echo $donnees["pays"]; } ?> code javascript : function setdefaultcountry() { var countryselect = document.getelementbyid("countryselect"); (i=0;i< countryselect.length;i++) { if (countryselect[i].value == geonamesuseripcountrycode) { countryselect.selectedindex = i; } } } /* want display country selected here !!...

c# - Translating yield returns in nested loops -

i learning basic c# have following code snippet while(p!=null) { foreach(var x in x) yield return x; //.... foreach(var y in y) yield return y; p=getp(); } is code above same as ienumerable<object> os; while (p!=null) { foreach(var x in x) os.add(x); //.... foreach(var y in y) os.add(y); p=getp(); } return os; ??? the 2 code snippets * "the same" in sense produce same sequence of objects if iteration carried out completion. however, actual sequence of going happen during iteration different. code yield return may stopped early, if loop iterates resultant ienumerable terminates because of break or exception. code adds collection prepares new collection in memory. code yield return uses existing collections make sequence can iterated, without storing result in memory. code yield return can react changes in iterates during process of iteration. example, if code uses yield return method adds...

Laravel generating invalid routes -

Image
i don't know happened laravel, laravel generating invalid routes when performing action when open comments box click button comments modal box opened fines when see in chrome developer option -> network shows me many invalid routes. idea why happening? please see attached screnshot: admin route prefix route::group(['prefix' => 'admin', 'before' => 'allow_only_admin'], function () { }); http://projecturl.com/admin/order/ route::filter('allow_only_admin', function () { if (auth::check() && !auth::user()->is('admin')) { return redirect()->intended('user/login'); } else { } }); this abc middleware: class abc { public function handle($request, closure $next) { if (\auth::check() && \auth::user()->admin) { return $next($request); } return redirect()->route('user.login'); } } this no_auth filter: che...

delphi - Adjusting Subreport object's height in run time -

hi using fastreports4 delphi 7 , have produce report form handles containers , stored goods. while building report found myself facing following issue: in main report have placed groupheader-band bound containers datasource. in placed 1 memoview (called containerinfmemo) bring container's info, 1 subreport bring stored commodities info stored relative container , memoview (called grossweightmemo) in calculate gross weight of container goods. inside subreport placed masterband bound commodities datasource, in placed memoview (called commoditiesmemo) prints commodities details. both groupheader , masterdata bands have stretched property set "true". memoviews have stretchmode property set "smmaxheight" while shiftmode property set "smwhenoverlapped". subreport's property printonparent set "true" while shiftmode property set "smwhenoverlapped". now, long commoditiesmemo's height greater height of other 2 memoview heigh...

c++11 - how to pass both function pointers and lambda's using one interface -

i trying use function pointers , lambdas using 1 interface. decided use std::function , found out cannot deal overloaded functions itself. example: void foobar(double i_double ){std::cout << "double argument" << i_double << std::endl;} void foobar(){std::cout << "no argument" << std::endl;} void foobar(int){std::cout << "int argument" << std::endl;} std::function<void(double)> func = static_cast<void(*)(double)>(&foobar); this code compiles using static_cast . since @ our company have quite lot of overloaded functions of hassle. decided implement 2 interfaces: 1 std::function objects , 1 function pointers, although wrap function pointers in std::function object (without additional code on calling side). any "nice" solution problem? edit: way using part of large framework, boils down code below. hope following code below makes use case clear. namespace { bool isallowe...

Is ++ operator more expensive than | operator in Erlang? -

i reading learn erlang , came upon example in recursion chapter. tail_sublist(_, 0, sublist) -> sublist; tail_sublist([], _, sublist) -> sublist; tail_sublist([h|t], n, sublist) when n > 0 -> tail_sublist(t, n-1, [h|sublist]). as author goes on explain there fatal flaw in our code. being sub lists hence produced reverse , have re-reverse them correct output. in contrast, did use ++ operator avoid reversing list later. sublist_tail([],_,acc) -> acc; sublist_tail(_,0,acc) -> acc; sublist_tail([h|t],n,acc) -> sublist_tail(t,n-1,acc++[h]). my question is, is ++ operator more expensive | operator? , if is, would solution (using ++ operator) still slow compared author's solution (including reversing list correct output)? is ++ operator more expensive | operator? that depends. if use correctly, no. ++ dangerous when have big left-hand-side operand. each time " ++ "-operator invoked on left-hand list (like: list1 ++ list...

multithreading - Creating NewTask in a For Loop using Omnithread Library -

am writing program detects usb insertion , saves inserted drive(s) stringlist. want create newtask or background worker each content of stringlist, start them , wait till task finishes using omnithread library. here code snippet uses winapi.windows, winapi.messages, system.sysutils, system.classes, winapi.shellapi, otlcommon, otlcollections, otlparallel, vcl.dialogs; procedure tusb.wmdevicechange(var msg: tmessage); var lpdbhheader: pdevbroadcastheader; resstringlist, tempsenderlist: tstringlist; i: integer; begin lpdbhheader := pdevbroadcastheader(msg.lparam); resstringlist := tstringlist.create; tempsenderlist := tstringlist.create; resstringlist.clear; tempsenderlist.clear; try case msg.wparam of dbt_devicearrival: begin if (lpdbhheader^.dbch_devicetype = dbt_devtyp_volume) begin sleep(2000); // procedure connected usb devices , save stringlist (getdrive(pdevbroadcastvol...

PHP's array_slice vs Python's splitting arrays -

some background i having go @ common "maxprofit" programming challenge. goes this: given zero-indexed array consisting of n integers containing daily prices of stock share period of n consecutive days, returns maximum possible profit 1 transaction during period. i quite pleased php algorithm came up, having avoided naive brute-force attempt: public function maxprofit($prices) { $maxprofit = 0; $key = 0; $n = count($prices); while ($key < $n - 1) { $buyprice = $prices[$key]; $maxfutureprice = max( array_slice($prices, $key+1) ); $profit = $maxfutureprice - $buyprice; if ($profit > $maxprofit) $maxprofit = $profit; $key++; } return $maxprofit; } however, having tested solution seems perform badly performance-wise, perhaps in o(n 2 ) time. i did bit of reading around subject , discovered similar python solution. python has quite handy array abilities allow splitting array a[...

nested forms - How do I add different field types using rails nested_form -

i'm want use ryanb/nested_form gem (or similar) create associations many different field types. consider model called content might have many content_blocks should have text inputs, text areas, or image upload fields (different field types) dependant on required. got ideas on how achieve this? far can work out how add multiple fields of same type. i.e standard project -> task -> subtask ... pattern. or there better solution? thanks! -j you can use cocoon gem nested_form . also, there tutorial on nested form ryan bates on railscasts