Posts

Showing posts from February, 2014

javascript - if statement with more than one condition -

i need check 3 conditions, sheet_exists = 1 recalc = 1 qty_total , new_qty_total not equal the if statement works if first 2 arguments used: if(sheet_exists === 1 && recalc === 'yes'){ //do } but when try add 3rd argument fails, actions in if statement ignored. i've tried: if((sheet_exists === 1) && (recalc === 'yes') && (qty_total !== new_qty_total)){ //do } and: if(sheet_exists === 1 && recalc === 'yes' && (qty_total !== new_qty_total)){ //do } and: if(sheet_exists === 1 && recalc === 'yes' && qty_total !== new_qty_total){ //do } where going wrong? considering happy behavior of first 2 conditions, , not last one, problem must in last one. pay attention, qty_total !== new_qty_total return true when value or type of qty_total , new_qty_total different. if 1 integer 100 , other string '100' condition evaluates true because dif

php - creating zip of big folder with pdf files -

i'm creating zip of folder pdf , txt files, working well. creating zip of folder above 30 files ( 389 kb each file) getting empty zip. why? here's code: include("include/zip_min.inc"); if($_get['create_zip']) { include("include/zip_min.inc"); $zipfile = new zipfile(); $files_arr=scandir($_get['path']); foreach ($files_arr $folder) { if(( strpos("-".$folder,".pdf") || strpos("-".$folder,".txt") ) )//&& $k<30 { $k++; $fileonserver = $_get['path']."/".$folder;//"path/to/file/oldfilename.txt"; $filename =$folder; $zipfile -> addfile(file_get_contents($fileonserver), $filename); } } // force download zip header("content-type: application/octet-stream"); header("content-disposition: attachment; filename=test.zip"); echo $zipfile -> file(); }

artificial intelligence - Connect 4 and neural networks -

i'm trying code connect 4 - ia based on neural networks. but it's first time use ann, i'm lost... i found looks great, need explanations... structure i'm ok input, don't understand number of hiddens. also, output should number of colomn put coin next turn, means value between 1 , 7. but how these values, using sigmoid function ?

date - How to format brushed time axis (with context-dependent values) -

Image
i have x axis years 2009 - 2016 tickvalues. when select time period time widget, tick values become combination of month names , years (thank this, d3!). have 'december, 2014, february' example. selecting narrower range gives me week names , dates e.g. 'june 14'. i month names appear shortened format, e.g. dec, feb. know d3.time.format('%b'), can't set tickformat without impacting years (which come out 'jan'). how apply context-dependent tickformat d3 time scale axis? i believe looking d3.time.format.multi: for example: var customtimeformat = d3.time.format.multi([ [".%l", function(d) { return d.getmilliseconds(); }], [":%s", function(d) { return d.getseconds(); }], ["%i:%m", function(d) { return d.getminutes(); }], ["%i %p", function(d) { return d.gethours(); }], ["%a %d", function(d) { return d.getday() && d.getdate() != 1; }], ["%b %d", function

algorithm - What is the fastest way to join multiple subsets that have similar elements? -

i have list 500+ thousand subsets each having 1 500 values (integers). have like: {1, 2, 3 } {2, 3} {4, 5} {3, 6, 7} {7, 9} {8, 4} {10, 11} after running code get: {1, 2, 3, 6, 7, 9} {4, 5, 8} {10, 11} i wrote simple code [here] compares each subset each subset, if intersect joined together, else not. ok on small scale, big amount of data takes forever. please, advise improvements? p.s. not strong in maths or logics, big o notation greek me. sorry. you're trying find connected components in graph, each of input sets representing set of nodes that's connected. here's simple implementation: sets = [{1, 2, 3 },{2, 3},{4, 5},{3, 6, 7},{7, 9},{8, 4},{10, 11}] allelts = set.union(*sets) components = {x: {x} x in allelts} component = {x: x x in allelts} s in sets: comp = sorted({component[x] x in s}) mergeto = comp[0] mergefrom in comp[1:]: components[mergeto] |= components[mergefrom] x in components[mergefrom]: c

ibm mobilefirst - Worklight : Can we create different version of desktopwebapp -

is there way in workight can create different version of desktopwebapp can other enviornment android, ios ignore risk. there no "versioning" support mobile web , desktop browser environments in mobilefirst platform. workaround create app in project , add environment, copy/paste contents of previous app , use "version".

coffeescript - Can not load "coffee", it is not registered! Karma error message -

i trying use karma coffeescript. following preprocessor line there in karma config file: preprocessors: { '**/*.coffee': 'coffee' } but getting error - can not load "coffee", not registered! perhaps missing plugin? karma-coffee-preprocessor available devdependencies in package.json. has faced issue? thanks. i figured out solution. because of not installing karma-cli. though installing karma globally enough. after installing karma-cli fine.

c++ - Draw loop and Lua (Luabridge) -

Image
i'm stuck on issue , don't know how fix it. i started working on simple 2d engine using sfml rendering stuff , lua scripting language. engine starts splash screen first before lua code loaded ... my problem don't know how write "good" draw loop lua objects. maybe you'll understand when take on code: main.cpp: ... int draw_stuff() { sf::renderwindow window(sf::videomode(640, 480), title); while (window.isopen()) { sf::event event; while (window.pollevent(event)) { if (event.type == sf::event::closed) window.close(); } window.clear(); if (!success) { window.draw(sp_splash_screen); } if (clock.getelapsedtime().asseconds() > 2) { (static bool first = true; first; first = false) { std::thread thr(&lua_module); thr.detach(); success = true; } } (sf::circleshape obj : circledrawlis

.net - How to increase a speed of receive data from serial port? -

weight scale machine(fc-5000i model) connected vb application via serial port (com1) , baudrate=9600. weight scale machine send set of data. each set includes there commands : uw,+0.000000 g qt,+00000000 pc st,+000.1064 kg but need display weight value in vb , use serialport.datareceived event handling data serial port. each round use 0.5 second receive 1 command. received first command - not show anything received second command -not show anything received third command - show weight in kg . so vb project display weight delay 1 second. user not permit config weight scale machine.

mysql - Fatal error: Call to a member function num_rows() on boolean in C:\xamp\htdocs\project24\system\database\DB_driver.php on line 768 -

Image
dear getting error when trying create table through migration. getting following error : fatal error: call member function num_rows() on boolean in c:\xamp\htdocs\project24\system\database\db_driver.php on line 768 my code is: if ($query->num_rows() > 0) { foreach ($query->result_array() $row) { if (isset($row['table_name'])) { $retval[] = $row['table_name']; } else { $retval[] = array_shift($row); } } } $this->data_cache['table_names'] = $retval; $ex=$this->data_cache['table_names']; return $ex; } line number 768 please me out error i'll suppose $query result of sending query , getting response. i'll explain more appropiate var names: if($result = connection()->query($query)) $rs = mysqli_fetch_array($result); ok, @ point have first row on $rs, do

javascript - Textarea linebreak using ajax -

i got textarea updating description when save using ajax doesn't follow spaces made in textarea. $('#edit-desc').on('click', function () { var = $('.edit-description'), v = i.val(); if ($(this).hasclass('edit-desc')) { $(this).text('update'); item_val = $('#desc_item').html().replace(/<br>/gi, '\n'); $('.edit-description').show(); $('.edit-description').val(item_val); $('#desc_item').hide(); $('.edit-description').focus(); console.log("you pressed edit"); } else { $(this).text('edit'); item_val = $('.edit-description').val().replace(/\n/g, '<br/>'); item_id = $('#collection_item_id').val(); $('.edit-description').hide(); $('#desc_item').show(); $('#desc_item').html(item_val); $.post('php/edit-it

sql - VB.net Query on Datagrid view -

i need display value in datagrid not id. have 2 tables table1, having empid, receivedbyid, releasebyid, id's refer on table2 whereby table2 having id, name. i required display on datagrid table1 respected name not id. ex table1 id's 1,3,3 table2 data is, 1 - name1, 2 - name2, 3-name3 output should be, name1, name3, name3 for c# stringbuilder sb = new stringbuilder(); sb.appendline(" select b.name empname,c.name receivedby,d.name releasedby table1 "); sb.appendline(" inner join table2 b on a.empid = b.id "); sb.appendline(" inner join table2 c on a.receivedbyid = b.id "); sb.appendline(" inner join table2 d on a.releasebyid = b.id "); sqlconnection conn = new sqlconnection(myconstring); sqlcommand cmd = new sqlcommand(sb.tostring(), conn); conn.open(); datatable datatable = new datatable(); sqldataadapt

python 3.x - Scrapy Logging Level Change -

i'm trying start scrapy spider scripty shown in here logging.basicconfig( filename='log.txt', format='%(levelname)s: %(message)s', level=logging.critical ) configure_logging(install_root_handler=false) process = crawlerprocess(get_project_settings()) process.crawl('1740') process.start() # script block here until crawling finished i want configure logging level of spider if not install root logger handler , configure basic config logging.basicconfig method not obey determinded level. info: enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.httperrormiddleware', 'scrapy.spidermiddlewares.offsite.offsitemiddleware', 'scrapy.spidermiddlewares.referer.referermiddleware', 'scrapy.spidermiddlewares.urllength.urllengthmiddleware', 'scrapy.spidermiddlewares.depth.depthmiddleware'] info: enabled item pipelines: ['collector.pipelines.collectorpipeline'] info: spider opened info:

tfs2013 - TFS 2013 raise conflict for every change -

Image
i trying merge change set parent branch, lately every change make in files getting conflict. in image below can see have made small change , consider conflict. how can change visual studio won't show me conflict every space make? the diff , merge tool in vs 2010 , earlier support command line options ignoring whitespace, current vs versions support ignore trim whitespace. there uservoice @ website: https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/3063842-add-ignore-case-and-ignore-whitespace-options as alternate, can replace diff/merge tool in vs these support ignore whitespace, example: winmerge .

jquery - How to check the return of a JavaScript function in onchange event -

how call function inside onchange if return of previous function true, trying calling many function on onchange event, last function should call if return of previous function true. code bellow: <input type="text" name='test' id="test" onchange="remldzero('test'); validatetest(); if(checkduplicate('test', 'url','divid')===true){ nextfunction();};" maxlength="10" required> my jvascript checkduplicate() below function checkduplicate(fieldid,page,msgarea){ var fieldval= $('#'+fieldid).val(); $.ajax({ type: "post", url: page, data: fieldid+'='+fieldval, //datatype: "html", success: function(data){ if(data == 1){ $('#'+msgarea).css("display","none"); if(fieldid == 'test'){ return true;

javascript - Pass data-attr in Materialize's modal (leanModal) -

i using materialize framework in rails app. have element launch modal on click: <div data-target="modal1" class="modal-trigger" data-code="<%=code%>">lalala</div> i want catch data-code in js , save variable. i've done following official documentation: $('.modal-trigger').leanmodal({ ready: function() { var = $(this).attr("data-code"); }, } the variable "a" undefined. how can pass data-attr in materialize modal? best way? thanks. update: i'd display value of data-code in modal. code: <div id="modal1" class="modal bottom-sheet"> <div class="modal-content"> <p>the code</p> </div> </div> update1: solved clickon method , append data attr particular div wondering if possible pass through modal.

asp.net - Publishing log files -

i trying publish log files generated webapp using log4net. suppose iis not publish default, there way fix ? i know there security break in publishing log files, tip welcome watch these files without risk... in general, need add files project them included in webdeploy package/deployment.

javascript - Calling original method when overriding array push -

i'm attempting override push on array. need able call original push method before overriding can push element onto array. below code. i've added list.push within value method. know wrong, added show trying do. let list = [ 'one', 'two', 'three' ] object.defineproperty(list, 'push', { value: function(el) { list.push(el) // know wrong. example of trying do. } }) invoke original prototype implementation current object context: array.prototype.push.call(this, el)

java - How to protect Files.walk from symbolic links recursion? -

how protect files.walk symbolic links recursion? using java or shell. okay, follow links. stream<path> stream = walk(startpath, maxdepth, filevisitoption.follow_links); however check every directory whether symbolic link: files.issymboliclink(path) && fles.isdirectory(path) use path realpath = path.torealpath(); then keeping list of directories on in, ancestors, 1 prevent recursion. doing every directory check in ancestors, when symbolic link somewhere in list/current path. a > b > start:c > d > e > symbolic:f=a > b > c (this still not prevent visiting directory twice, same or subdirectory linked without recursion.)

java - Spring Data REST How to add embedded resources inline -

i'm using spring data rest , hateoas in combination hal browser. works perfectly, make json dump of specific entity (a set of) associated objects. used @projection got stuck again. fyi: normal behaviour (with embedded , links etc) should remain besides new endpoint (without embedded , links). to further illustrate problem/question: class person { string name; list<company> companies; } class company { string name; address address; } class address { string street; } now see this: { "name": "john", "companies": [ { "name": "stackoverflow", "address": {"street": "highway blvd."} }, { "name": "oracle", "address": {"street": "main rd."} } ] } while i'm getting this: { "name": "john", "_links": {

ios - iTunes Connect: How to create Bundle ID as part of other team? -

a customer has added me 'app manager' companies itunes connect portal. how can upload app account? it tells me have no eligible bundle ids , sends me create 1 in developer portal "certificates, identifiers & profiles". if create 1 there, create private account, not customers. please help, release app... i had call company, tell them go https://developer.apple.com/ , go 'people' , invite me admin. can go 'certificates, identifier & profiles' page, click on name @ top , pick 'change team'. there can switch company. hope helps else @ point.

java - scheduled alarm to repeat every minute of the clock android -

i have app requires code executed every minute. issue code has executed @ every minute change of clock. means, if 12:34 code execute @ 12:35 , goes on. current code works includes seconds. meaning, if 12:34:30 , alarm starts, code executed. code executed @ 12:35:30. i want code executed each minute according clock of phone. below current code. intent intent2 = new intent(mainactivity.this, myabservice.class); pendingintent pintent = pendingintent.getservice(mainactivity.this, 0, intent2, 0); alarmmanager alarm_manager = (alarmmanager) getsystemservice(context.alarm_service); alarm_manager.setrepeating(alarmmanager.rtc, c.gettimeinmillis(), 1 * 1000, pintent); im making execute every second effect takes place @ exact time. instead of having every second need repeat @ every minute change of clock (every minute) how go this use intent.action_time_tick broadcast intent fired every minute android os. register registe

javascript - React Component adds classNames which aren't recognized because of imported css modules -

Image
currently working on large project uses react , css modules. want implement 'react-anything-sortable' on bunch of list items. so far implementation has gone standstill because 'react-anything-sortable' adds following classes child inside 'react-anything-component': .ui-sortable, .ui-sortable-item, .ui-draggable , .ui-sortable-placeholder. assume these classes passed 'react-anything-sortable' recognize dom elements being dragged, placed, etc. i import list component's styles referencing .scss file so: import styles './widgetlist.scss' to use styles on component, need add styles.class use class: <div classname={styles.container}>something</div> therefore, it's understandable .ui-sortable being placed 'react-anything-sortable' has no way of referencing stylesheet since doesn't add .styles. 1 can see how other div elements have 'hashed' classname (indicating class in respective css modules ha

php - how to insert data to 2 tables from single form and controller in yii2 -

this create page questions/create.php <?php $form = activeform::begin(); ?> <br><br><br> <?= $form->field($model, 'question')->textinput(['maxlength' => true]) ?> <?= $form->field($model, 'topic')->textinput(['maxlength' => true]) ?> <?= $form->field($model1, 'askid')->textinput(['maxlength' => true]) ?> <div class="form-group"> <?= html::submitbutton($model->isnewrecord ? yii::t('app', 'create') : yii::t('app', 'update'), ['class' => $model->isnewrecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php activeform::end(); askid field in table askquestions questioncontroller public function actioncreate() { $model = new questions(); $model1 = new askquestions(); //$model1 -> load(yii::$app->request->post()); if ($mo

c++ - Unresolved token and symbols for <alcapi.h> -

i want create library can modify acls of object . i've created c++ project in vs 2015 (all c++ components installed), giving me layout dll library. i've included sample code in link above in .cpp file, , included alcapi.h : #include <windows.h> #include <stdio.h> #include <aclapi.h> dword addacetoobjectssecuritydescriptor( lptstr pszobjname, // name of object se_object_type objecttype, // type of object lptstr psztrustee, // trustee new ace trustee_form trusteeform, // format of trustee structure dword dwaccessrights, // access mask new ace access_mode accessmode, // type of ace dword dwinheritance // inheritance flags new ace ) { dword dwres = 0; pacl polddacl = null, pnewdacl = null; psecurity_descriptor psd = null; explicit_access ea; ... when try build this, following errors following: lnk2028 unresolved token (0a00005d) "extern "c" unsigned long

Why Java 8 Stream forEach method behaves differently? -

as per understanding of java 8 lambda expressions, if don't include code after "->" in curly braces value returned implicitly. in case of below example, foreach method expects consumer , expression returns value compiler not giving error in eclipse. list<stringbuilder> messages = arrays.aslist(new stringbuilder(), new stringbuilder()); messages.stream().foreach(s-> s.append("helloworld"));//works fine messages.stream().foreach((stringbuilder s)-> s.append("helloworld")); //works fine messages.stream().foreach(s-> s); // doesn't work , void methods cannot return value messages.stream().foreach(s-> s.tostring()); // works fine messages.stream().foreach(s-> {return s.append("helloworld");}); // doesn't work , void methods cannot return value messages.stream().foreach((stringbuilder s)-> {return s.append("helloworld");}); // doesn't work , void methods cannot return value s.appen

How to Get data From url value parameter $_GET in PHP -

sorry begginer of php. have url example here: http://example.com?category=software-hardware .actual of category software & hardware using script url above foreach ( $key $value ) { $c = array(' ', '&-'); $d = array('-', ''); echo "<a href=\"category/".strtolower(str_replace($c, $d, $value->kategori_laporan))."\" class=\"list-group-item\">".$value->kategori_laporan."</a>"; } how data condition url.? sorry, bad using english. want create url category slideshare. please me.! thanks.! you can fetch like: $cat = $_get['category']; and don't need foreach

ios - how to make top edge of the waveform rounded -

Image
i want create top edge , bottom edge of wave forms in rounded shape . currently able these wave forms the code below is - (uiimage*) drawimagefromsamples:(sint16*)samples maxvalue:(sint16)maxvalue samplecount:(nsinteger)samplecount { cgsize imagesize = cgsizemake(samplecount * (_drawspaces ? 6 : 6), self.height); uigraphicsbeginimagecontextwithoptions(imagesize, no, 0); cgcontextref context = uigraphicsgetcurrentcontext(); cgcontextsetfillcolorwithcolor(context, self.backgroundcolor.cgcolor); cgcontextsetalpha(context, 1.0); cgrect rect; rect.size = imagesize; rect.origin.x = 0; rect.origin.y = 0; cgcolorref wavecolor = self.wavecolor.cgcolor; cgcontextfillrect(context, rect); cgcontextsetlinewidth(context, 2.0); float channelcentery = imagesize.height / 2; float sampleadjustmentfactor = imagesize.height / (float)maxvalue; (nsinteger = 0; < samplecount; i++) { float val = *samples++; val = val * sampleadjustmentfa

mysql - How to update date and hour, while keeping Minutes and Seconds -

i have datetime 0000-00-00 00:00:00 column in table, need keep minute , seconds when updating ____-__-__ __:mm:ss change date , hour current time. how can achieve on mysql side? edit (sample): current date field value: 2016-06-27 15 :13:07 we update table @ 2016-07-28 12:31:18 desired date field value: 2016-07-28 12 :13:07 as can see updated date still has correct 2016-07-28 12: :13:07 (minutes , seconds) selected date before update , replaced current time's minutes , seconds you can make use of mysql concat() function. update query looks this, update table_name set date_column = concat('2016-06-29 15:',minute(date_column),':',second(date_column)) column_id = 1 concat() returns string results concatenating given arguments. so in case update date , hour adding first argument 2016-06-29 15: , , use same minute , second same column. , concatenate arguments make new value need. http://dev.mysql.com/doc/refman/5.7/en/strin

c - UPNP - Bind between Device and Services (miniupnp) -

i using miniupnp sw package running on router. in order list available devices / services on lan network, used 'listdevice' application, query miniupnpc discover devices / services , print them out. can please explain how can understand, service belong each device? see example table below: 1: urn:schemas-upnp-org:service:layer3forwarding:1 http://192.168.1.1:5000/rootdesc.xml uuid:63ce4f39-1485-4bd6-ba33-bb1ec09dc1cf::urn:schemas-upnp-org:service:layer3forwarding:1 2: uuid:63ce4f39-1485-4bd6-ba33-bb1ec09dc1cf http://192.168.1.1:5000/rootdesc.xml uuid:63ce4f39-1485-4bd6-ba33-bb1ec09dc1cf 3: uuid:63ce4f39-1485-4bd6-ba33-bb1ec09dc1c0 http://192.168.1.1:5000/rootdesc.xml uuid:63ce4f39-1485-4bd6-ba33-bb1ec09dc1c0 4: uuid:63ce4f39-1485-4bd6-ba33-bb1ec09dc1c1 http://192.168.1.1:5000/rootdesc.xml uuid:63ce4f39-1485-4bd6-ba33-bb1ec09dc1c1 5: urn:schemas-upnp-org:device:wanconnectiondevice:1 http://192.168.1.1:5000/rootdesc.xml uuid:63ce4f39-1485

automation - Is there a way to get VMs Operating System name from Hyper-V using powershell? -

i'm writing script on hyper-v host getting vms guest informations. there way vms operating system name hyper-v using powershell? there several examples using (get-wmiobject win32_operatingsystem -computername $vmname).name should information directly hyper-v because of domain restrictions. also i'm using hyper-v module of powershell couldn't see cmdlets related os. this retrieved guest intrinsic exchange items. # filter parsing xml data filter import-cimxml { # create new xml object input $cimxml = [xml]$_ $cimobj = new-object -typename system.object # iterate on data , pull out value name , data each entry foreach ($cimproperty in $cimxml.selectnodes("/instance/property[@name='name']")) { $cimobj | add-member -membertype noteproperty -name $cimproperty.name -value $cimproperty.value } foreach ($cimproperty in $cimxml.selectnodes("/instance/property[@name='data']"))

ios - swift mirror return class name in class function -

i'm having class function , in class function want name of class thats extending abstract entity class. i found mirror type have this: class abstractentity { class func findorcreateentity() -> anyobject? { print("name: \(nsstringfromclass(mirror(reflecting: self)))") } } the problem example class car extends abstractentity , calls method prints car.type, correct don't want .type extension. there way class name? i want swift way if it's possible. know of exnteions of nsobject , nsstringfromclass thing.. for clarity: class abstractentity: nsmanagedobject { // insert code here add functionality managed object subclass class func findorcreateentitywithuuid(entityname: string, uuid: string, context: nsmanagedobjectcontext) -> anyobject? { let request = nsfetchrequest(entityname: entityname) request.returnsobjectsasfaults = false; let predicate = nspredicate(format: "uuid = %@", uuid)

Firebase Java client with custom authentication -

i'm looking firebase java client allows custom auth. so read documentation , had @ answer i'm still not sure if there plain java client firebase 3 allows custom auth token. as understand it: the java library supposed firebase-server-sdk, not have of methods in firebaseauth in android sdk signinwithcustomtoken. the android sdk android , not on maven central , appears have dependencies on google's play services. from here took possible set uuid java sdk client, still need service account credentials, not work token. so if have plain java application supposed simple custom auth token based firebase client have no library @ moment? you supposed mint custom token on server using firebase-server-sdk java. pass token client , call signinwithcustomtoken(mintedtoken). sign in user , generate firebase id token.

python - Efficient method to transpose submatrix in a numpy array -

i have large numpy array of matrix has structure: np.array([ [[1, 2], [3, 4]], [[5, 6], [7, 8]], ]) my expected output np.array([ [[1, 3], [2, 4]], [[5, 7], [6, 8]], ]) i know methods using list comprehension or loops , create numpy array again, methods involving creating numpy list slow data. , vectorize seems working on numbers. when use normal python lists or other languages, can map transpose function list, seems there no similar function in numpy. how can efficiently?

laravel - image is not loading using php echo -

i have tried echo table fields 1 one. can't echo image field. code is: if ($data->prophylaxis_indicated == 1) { echo "<td><span title='true_logo'> <img src='url('images/1-icon.png')' height='20' width='20'></span></td>"; } else { echo "<td> <span title='true_logo'><img src='url('images/0-icon.png')'height='20' width='20'></span></td>"; } i think problem trying use blade syntax in controller. use code work if(($data->prophylaxis_indicated)==1){ echo " <td><span title='true_logo'> <img src='images/1-icon.png' height='20' width='20'> </span></td>"; } else{ echo "<td> <span title='true_logo'>

javascript - Making Reusable Function in Jquery -

i use code , makes website load. $('#start').click(function() { $('html,body').animate({ scrolltop : $('.scroll').offset().top },1500);//end animate });//end click i used change #start , .scroll everytime. tips? wrap in function. function foo(startelem, scrollelem) { $(startelem).click(function() { $('html,body').animate({ scrolltop : $(scrollelem).offset().top },1500);//end animate }); } then call when need it. foo('#start', '.scroll'); read more here .

.net - Passing user_id from back-end to client-side with Segment Analytics.NET and Mixpanel -

i using c# .net, angularjs , other technology quite loosely coupled. need implement segment , mixpanel. have implemented alias , identify in back-end upon registration , login respectively. put track, page calls required. i need pass user_id client side on login pass value each event required in documentation. ( how connect segment.io server , client side events same anonymous user? ) quite close need, , did not work me. the point here need anyway pass userid identify call on login both back-end , front-end libraries. should regardless of alias call. in accord segment support responses.

AngularJS/Ionic how to initialize a controller's code without rendering the view? -

i building app have number of controllers. i'm watching web socket message in chatcontroller connected inbox.html view. app starts on 'requests' page controller different. problem unless user has explicitly visited inbox.html view @ least once, web socket(socket.io) event isn't detected since code 'chatcontroller' hasn't been initialised. options have enabling functionality? somehow initialise code 'chatcontroller' app starts without user having visit screen. thank you

keyboard events - How to post Extended ASCII chars (0x80 to 0xFF) using PostMessage in Delphi? -

i writing keyboard mapper application in need send extended ascii chars (0x80 0xff) current window. have tried below function constructlparam(vkey: word): longint; // cardinal; begin { constructlparam } if vkey > $ff result := longint(mapvirtualkeyw(vkey, 0) , $00000fff or $f000) shl 16 or 1 else result := longint(mapvirtualkey(vkey, 0) , $000000ff or $ff00) shl 16 or 1; end; { constructlparam } procedure postcharacter(targetwinhandle: hwnd; unicodevalue: word; ime_msg, widefunction, simulatekey, sendmsg: boolean); begin { postcharacter } if sendmsg // sendmsg fn if ime_msg // ime msg if widefunction // wide fn begin if simulatekey sendmessagew(targetwinhandle, wm_ime_keydown, makewparam(unicodevalue, 0), constructlparam(unicodevalue)); sendmessagew(targetwinhandle, wm_ime_char, makewparam(unicodevalue, 0), constructlparam(unicodevalue)); if simulatekey sendmessagew(targetwinhandle, wm_i

files with extra suffix in batch -

i'm trying list files have suffix after extension e.g: .txt.1 or .txt.2 etc.. i'm using txt. it's giving file names instead of files suffix for %%a in (*txt.*) (call :renum "%%a") after i'm writing program rename files accordingly. can please check , help. one solution filter extension inside loop: for %%a in (*txt.*) ( if not "%%~xa"==".txt" call :renum "%%a" ) this works using "enhanced substitution of for variable references", in case %%~xa . can overview of available substitutions executing for /? . update: this solution not work case-insensitively, because neither explicitly demanded or prohibited. use if /i instead of plain if if case-insensivity desired. as dbenham notes, there edge cases: name.txt.txt will not processed. if that's ok not stated, rather likely. name_txt.ext will processed, due given wildcard *txt.* , can avoided using *.txt.* instead. rationale n

Deploy a Laravel App on Cloudfoundry -

i trying deploy laravel based web application swisscom application cloud. therefor use provided php buildpack. docs shows example lumen, assuming should work laravel well. used command: cf push app-name -m 512m -n app-name while deploying these 2 errors: a) the extension 'fpm' not provided buildpack. extension 'tokenizer' not provided buildpack. extension 'dom' not provided buildpack. extension 'json' not provided buildpack. extension 'pcre' not provided buildpack. extension 'reflection' not provided buildpack. extension 'spl' not provided buildpack. b) generating autoload files > illuminate\foundation\composerscripts::postinstall > php artisan optimize php warning: require(/tmp/app/bootstrap/../vendor/autoload.php):failed open stream: no such file or directory in /tmp/app/bootstrap/autoload.php on line 17 php fatal error: require(): failed opening required '/tmp/app/bootstrap/../vendor/autoload.php'

android - setText() not working -

settext(), settextsize() , addview not working. shown cannot resolve symbol type. intent intent = getintent(); string message = intent.getstringextra(myactivity.extra_message); textview textview = new textview(this); textview.settextsize(40); textview.settext(message); relativelayout layout = (relativelayout) findviewbyid(r.id.content); layout.addview(textview); you can't use methods such add , find view id before layout inflated. verifý setcontentview called before. if does, @ value of message log.

Autocomplete TextBox in Asp.Net with C# -

can please me create autocomplete textbox in asp.net using c#. trying create end not working. i used oracle 11g db. below code <asp:textbox id="textbox1" runat="server" autopostback="true"></asp:textbox> <ajaxtoolkit:autocompleteextender servicemethod="getcompletionlist" minimumprefixlength="1" completioninterval="10" enablecaching="false" completionsetcount="1" targetcontrolid="textbox1" id="autocompleteextender1" runat="server" firstrowselected="false"> </ajaxtoolkit:autocompleteextender> c# code: [webmethod] [system.web.script.services.scriptmethod()] [system.web.services.webmethod] public static list<string> getcompletionlist(string prefixtext, int count) { return autofillproducts(prefixtext); } [system.web.script.services.scriptmethod()] [system.web.services.webmethod] priva

c# - Mapping List<Model> to Dictionary<int, ViewModel> -

i have model class: public class model { public int id {get;set;} public string name {get;set;} } and view model: public class viewmodel { public string name {get;set;} } i want map list dictionary key model.id. i have started such configuration: configuration .createmap<model, keyvaluepair<int, viewmodel>>() .constructusing( x => new keyvaluepair<int, viewmodel>(x.id, _mapper.map<viewmodel>(x))); but don't want use mapper instance in configuration. there other way achieve this? i've seen answers, people used x.mapto(), doesn't seem available anymore... you can use mapper instance lambda parameter x.engine.mapper simple this configuration .createmap<model, keyvaluepair<int, viewmodel>>() .constructusing(context => new keyvaluepair<int, viewmodel>( ((model)context.sourcevalue).id, context.engine.mapper.map<viewmodel>(context.sou

angular - How to get ID of element ViewChild angular2 and jquery? -

i need have relation between jquery , viewchild of angular2 i tried undefined value @viewchild('item', {read: viewcontainerref}) item; console.log( $(this.item.nativeelement).attr('id')) ); update part <div class="container col411 col-sm-4" id="div411item" style="border: 1px solid #9da0a4;" (dblclick)="activeeditcol411()" #item> new content </div> activeeditcol411(){ $('#item').prop('contenteditable','true'); } you have parenthesis in code. conole.log( $(this.item.nativeelement).attr('id') ) ); are sure have id attribute in html tag? if don`t have one, add , try code below: console.log( $(this.item.nativeelement).attr('id') ); answer updated: <div class="container col411 col-sm-4" id="div411item" style="border: 1px solid #9da0a4;" (dblclick)="activeeditcol411()" #item> new co

web ide - How to trigger Eslints automated fix in SAP Webide? -

Image
there errors eslint can fix automaticly as descaribed on webpage (command-line, atomtext, etc.) how in sap webide? currently web ide not support automatic fixing of code eslint warnings , errors need manually fixing line of code. fix according eslint comment error not there anymore update - how change new line mode changing new line mode can done web ide user settings in order access user settings need click on settings icon located on web ide right side pane , select code editor , under code editor see new line mode

c# - Is there a way to display an error message if the table is not updated? -

i want update row in table: try { string sql ="update tablename set firstname ='john' id = 123"; mysqlcommand command = new mysqlcommand(sql, connection); connection.open(); command.executenonquery(); } catch (exception) { } { connection.close(); } based on id (key), works if id in table, if id doesn't exist in table shows no error message. is there way can know if id not found? actually executenonquery returns number of rows affected. can make use of that: int affectedrows = command.executenonquery(); if (affectedrows == 0) { // show error; } else { // success; }

php - Wordpress create account and copy user information to another database -

i'm using woocommerce , customer must logged or create account buy. when create account need password send password web service , create new user other database. this database used web application , have encrypt password phalcon hash method can't because wordpress password hashed. how can do ? there way this. can have access users plain password whenever user logs in there no way recursively of passwords of course. don't think create problem because functionality work logged users without interruption. you need create hook called wp_authenticate_user : add_filter('wp_authenticate_user', 'myplugin_auth_login',10,2); // $priority 10, $accepted_args 2. function myplugin_auth_login ($user, $password) { $user_id = $user->id; // check if passsword converted $phalcon_hash = get_user_meta( $user_id, 'phalcon_hash' ); if($phalcon_hash == false) { // convert password $phalcon_password = use_your_ph

c - sizeof struct inside struct -

struct s1 { char c; int i; }; struct s3 { char c1; struct s1 s; double c2; }; i trying calculate sizeof(s3) , program 24. don't know offset of struct s1 inside s3, there rule offset? thought "the offset of s1 must n times of size of itself, i.e., n * sizeof(s1)", however, found not true. help. the c standard intentionally flexible on this. all guarantees (i) address of first element in struct same address of struct , , (ii) data members appear in order declared in struct . (iii) empty struct have non-zero sizeof . last 1 means pointer arithmetic valid on null structures. in particular, padding (of amount) allowed inserted between structure member, , @ end.

When and how to use @noreturn attribute in Swift? -

i read code block enclosed in curly braces after keyword else in context of guard-else flow, must call function marked noreturn attribute or transfer control using return , break , continue or throw . the last part quite clear, while don't understand first. first of all, function returns (an empty tuple @ least) if don't declare return type. secondly, when can use noreturn function? docs suggesting core, built-in methods marked noreturn ? the else clause of guard statement required, , must either call function marked noreturn attribute or transfer program control outside guard statement’s enclosing scope using 1 of following statements: return break continue throw here source . first of all, function returns (an empty tuple @ least) if don't declare return type. (@noreturn obsolete; see swift 3 update below.) no, there functions terminate process , not return caller. these marked in swift @noreturn , such as @noreturn public

ios - Mobile browser crashes when loading page -

recently found problems our webpage crashes on ios. happening both in chrome , safari. has idea how debug it, or why happens ? its hard reproduce (actually on phone not able to). trying turning off components page. page contains lot of html (20-100 pages) , bit heavy javascript components, such maps, street view or graphs. thanks idea or hint. thanks! you can debug webpage, when loading on mobile browser(safari). follow below steps: connect ios device mac--> open safari on mac --> in menu bar can see develop option --> on selecting develop option show connected devices--> keep menu popup open , browse webpage on connected ios device. note : if device doesn't show in develop option please enable in ios device settings --> safari --> advanced --> web inspector.

How to remove Error:Execution failed for task ':app:transformClassesWithDexForDebug' of android -

error:execution failed task ':app:transformclasseswithdexfordebug'. com.android.build.api.transform.transformexception: com.android.ide.common.process.processexception: java.util.concurrent.executionexception: com.android.ide.common.process.processexception: org.gradle.process.internal.execexception: process 'command 'c:\program files\java\jdk1.8.0_92\bin\java.exe'' finished non-zero exit value 2 if using android studio 2.1.2 , buildtoolversion 24.0.0. downgrade 23.0.x.

angular - Custom validation for positive numbers -

i trying find information, if there built-in validators, check if input positive number? i trying build following: static nonzero(control:control) { if (number(control.value) < 0) { control.seterrors({nonzero: true}) } else { control.seterrors(null) } } however, didn't know how use in form builder: this.form = _formbuilder.group({ field:['', validators.required]}) what doing wrong? you can configure way leveraging validators.compose method: this.form = _formbuilder.group({ field:['', validators.compose([ validators.required, nonzero ]) ]}); this allows define 2 synchronous validators field. edit i implement validator way: static nonzero(control:control):{ [key: string]: any; } { if (number(control.value) < 0) { return {nonzero: true}; } else { return null; } }

c++ - How to avoid an unreachable code warning due to a compiler bug? -

the cut down reproducible test case, vs2015 update 2, following. attempting build "warning level 4" , treat warnings fatal errors improve chances of noticing said warnings. hoping in community has run , has found reasonable workaround. this may prove localised if noone else has seen equivalent issue, i'd note underlying question "how badly should 1 mangle codebase evade poor compiler warnings", or equivalently, "how should 1 report bugs compiler vendor loses bug reports". #ifdef _win32 #pragma warning( push ) #pragma warning( disable : 4702 ) // suggested comments #endif template <class type> void func (type t) { t.func (); t.func (); } #ifdef _win32 #pragma warning( pop ) #endif struct nothrow { void func () {} }; struct throws { void func () {throw 1;} }; int main () { nothrow nt; func (nt); throws t; func (t); } this triggers unreachable code warnings. templated function looks reasonable itself, 1

php - prestashop display attachment inline -

i'm creating custom pdf file containing product details. display product attachments images. have changed attachment controller header('content-disposition: inline; filename="'.utf8_decode($a->file_name).'"'); when visit url through browser displays nicely: http://domain.nl/nl/index.php?controller=attachment&id_attachment=483 but using url inside img tag in pdf template gives: tcpdf error: [image] unable image: http://domain.nl/nl/index.php?controller=attachment&id_attachment=483 does have idea on how make work? i created new file next attachmentcontroller.php called attachmentinlinecontroller.php. contents different: <?php class attachmentinlinecontrollercore extends frontcontroller { public function __construct() { $a = new attachment(tools::getvalue('id_attachment'), $this->context->language->id); if (!$a->id) { tools::redirect('index.php');

html5 - What speaks against single-page apps from a user experience point of view? -

Image
i them more , wonder why not more common. explanations involving caching or seo make sense me, don't see them directly driven user experience considerations. in way traditional sites page reloads better user? personally think best argument normal page reloads user's perspective when it's harder break many basic browser functions. in general back/forward buttons work, bookmarking works, copying , pasting links works, history works, page titles work, getting error page when server call fails works, works expected. free. i have seen single page application implemented in way breaks 1 or more of above more times can count. it's naturally not problem if just right (and in general nicer use), not sites do. just example here's screenshot how site spa , justifiedly (they have music player don't want interrupt page loads), broke basic browser function in way might not have thought of. trying find song listened couldn't remember exact title... beca

java - JavaCompiler API - slow compilation when running in tomcat -

my application generates java code during runtime , compiles using javacompiler api. of generated files can rather large - few hundred thousand lines. find when run javac command on generated code in command line, or alternatively if use application compilation via javacompiler api, can compile many of these files (~500), if large, in under 2 minutes. however, if call api via application when running on tomcat server, compilation time runs upwards of twelve minutes (!!!). i appreciate suggestions on how improve performance of compilation. thanks! try set thread priority highest value (on thread or thread pool): setpriority(thread.max_priority);