Posts

Showing posts from July, 2015

javascript - Mongoose schema methods and "this" updating properties - NodeJS -

in usersschema want set hashed password hash field. schema looks this: // models/user-model.js const usersschema = new schema({ name: { type: string, required: true }, email: { type: string, unique: true, required: true }, hash: string, salt: string }, { timestamps: true }); usersschema.methods.setpassword = (password) => { this.salt = crypto.randombytes(16).tostring('hex'); this.hash = crypto.pbkdf2sync(password, this.salt, 1000, 64).tostring('hex'); }; in route, trying set new user name, email, , password. here's route: // routes/users.js router.get('/setup', (req, res) => { const user = new user(); user.name = 'jacob'; user.email = 'jacob@gmail.com'; user.setpassword('password'); user.save() .then((user) => { const token = user.generatejwt(); res.json({ yourtoken: token }); }) .catch((err) => { res.json(err); }); }); wh

ios - This is about album and memory -

i'm using swift, , called once album, systematic approach, , allowed dismiss normal way (perhaps less other way), after call complete systems approach, memory rise 20m, wrote simple example, found still case, wrote immediate window in appdelegate . swift rootviewcontroller switch inside, still can not eliminate 20m memory. because called photo album directly 20m, many times i'll call album now, not in demo, need solve 20m problem. the code: class viewcontroller: uiviewcontroller, uiimagepickercontrollerdelegate, uinavigationcontrollerdelegate { override func viewdidload() { super.viewdidload() self.view.backgroundcolor = uicolor.whitecolor() var bu = uibutton() bu.frame = cgrectmake(80, 80, 80, 80) bu.backgroundcolor = uicolor.redcolor() bu.addtarget(self, action: "hh", forcontrolevents: .touchupinside) self.view.addsubview(bu) } func hh() { let imagepicker = uiimagepickercontrolle

html5 - add geolocation to jquery location picker -

i'm trying put html5 geolocation in script attached no luck. find users location when page loads. any appreciated thanks location : <input type="text" id="us3-address" /> raius : <input type="text" id="us3-radius" /> <div id="us3" style="width: 550px; height: 400px;"></div> lat: <input type="text" id="us3-lat" /> long: <input type="text" id="us3-lon" /> <script> $('#us3').locationpicker({ location: { latitude: 46.15242437752303, longitude: 2.7470703125 }, radius: 300, inputbinding: { latitudeinput: $('#us3-lat'), longitudeinput: $('#us3-lon'), radiusinput: $('#us3-radius'), locationnameinput: $('#us3-ad

php - How to remove unwanted ascii characters from string? -

i have string shown below $string1="then & add â...“ to"; the special ascii characters â “ Â etc. causing errors. so want know there default function or ways remove such characters? expected output after processing : $string1="then & add … to"; you need mb_string installed , enabled in php.ini (which default now). on centos install php-mbstring package , restart web server, if running via web. <?php $string = "aâ"; print $string . "\n"; $length = mb_strlen( $string ); $index = 0; $output = ''; while( $index < $length ) { $char = $string[$index]; if( mb_check_encoding( $char, 'ascii') ) { $output .= $string[$index]; } $index++; } print $output . "\n"; ?> result: aâ for replacing character underscore, can modify code append '_' string if check encoding not return 1. http://php.net/manual/en/book.mbstring.php

Powershell script - Organize script by functions -

when put function {} around powershell script, change registry key, script doesn't seem run within brackets. when take out function {}, script runs fine. missing here? function clearpagefile { $regpath = "hklm:\system....(rest of path)" $key = "clearpagefileatshutdown set-itemproperty -path $regpath -name $key -value 0 } unless calling function place else, here's answer... function clearpagefile { $regpath = "hklm:\system....(rest of path)" $key = "clearpagefileatshutdown set-itemproperty -path $regpath -name $key -value 0 } #call function clearpagefile

performance - Python cvxopt glpk ilp return first feasible solution -

i using cvxopt.glpk.ilp solve complicated mixed integer program. wondering if there way program terminate after finding first solution? takes long , feasible solution work fine purposes. if you're using pulp (another python library cvxopt) invoke glpk solve mip, there 1 parameter called maxtime . if set maxtime=1 solver is, terminate search (almost) right after finding first solution. bet cvxopt should have similar parameter glpk since either pulp or cvxopt wrapper of solvers. copy paste description of maxtime parameter in xpress solver, think glpk should have similar may need find out. the maximum time in seconds optimizer run before terminates, including problem setup time , solution time. mip problems, total time taken solve nodes. 0 = no time limit. n > 0 = if integer solution has been found, stop mip search after n seconds, otherwise continue until integer solution found. n < 0 = stop in lp or mip search after -n seconds.

javascript - meteor with flow-router: Do I have access to Meteor.User from within a flow-router trigger? -

i believe security perspective , best handle access restricted url in 2 places: routing level : make sure no-one able route not permitted for template level : no restricted data showed before verifying permissions. iron-router support first way, want use flow-router . i found article satya van he-men , meteor: using flow router authentication , permissions in article using routing groups , triggers "filter" routes permissions. in article using meteor.loggingin() , meteor.userid() , meteor.user() , roles.userisinrole() inside triggersenter: function of flowrouter object. is possible of functions undefined during triggersenter execution? is safe use them? pattern article, want make sure safe use (or can become safe few changes) i think reason concern valid it's possible because triggersenter called once recommend reading official tutorial on auth logic permission on template level , it's reactive. previously, did in router l

r - Kappa Statistic Extremely Large/Sparse matrix -

i have large sparsematrix (mat): 138493 x 17694 sparse matrix of class "dgcmatrix", 10000132 entries i want investigate inter-rating agreement using kappa statistics when run fleiss: kappam.fleiss(mat) i shown following error error in asmethod(object) : cholmod error 'problem large' @ file ../core/cholmod_dense.c, line 105 is due matrix being large? is there other methods can use calculate kappa statistics irr on matrix large? the best answer can offer not possible due extreme sparsity in matrix. problem: 10,000,132 entries 138,493 * 17694 = 2,450,495,142 cell matrix, have (99.59%) missing values. irr package allows these here placing extreme demands on system, asking compare ratings users films not overlap. this compounded problem methods in irr package a) require dense matrixes input, , b) (at least in kripp.alpha() loop on columns making them slow. here illustration constructing matrix similar in nature yours (but no pattern

free jqGrid : how to assign function return value to edit/addNew form field? -

my code is ...... ...... {label: 'reason' ,name: 'reason' ,width: 60 ,editable: true ,editrules : { required: true} ,editoptions: { maxlength: 4 } ,formoptions:{rowpos: 5, colpos: 2, label: " <a href='javascript:selectrsnrecord()' " + " title='see list of reason codes' > reason</a> " } }, ...... ...... when click on reason label on edit/add new form, function selectrsnrecord() gets reason value. new reason value should go reason text box on edit/add new form. can able reason value i'm not getting how show/assign value on jqgrid edit /add new form text box. following, can see new reason value on grid. mygrid.jqgrid('setcell', selectedrowid, 'reason', newvalue); mygrid.jqgrid('getlocalrow', rowid).reason= newvalue; i'm using jqgrid 4.9.0 version , not possible me use other plugin. pleas

javascript - Applying a function/style to every each() iteration -

so got each loop loops through every '.related__item' , checks if contains image (using '.related__item-image') or not. if true, use correct function calculates text heights each '.related__item' , trigger dotdodot function. what problem is, loops through each '.related__item' correctly , console.logs correct true or false depending on image. reason, gives same height all related items. believe somewhere within if statement, going wrong, can't figure out what. how can make every iteration, loop gives true or false, sets correct heights elements and then goes on next , same thing. looking @ making each in , each? jfiddle: https://jsfiddle.net/bwbelbnv/ or js: var self = this; var textblock = $('.text', self); var titleheight = $('.related__item-title', self).outerheight(true); var containerheight = $('.related__item', self).outerheight(); var imageheight = $('.related__item-image', self).oute

mule - For Downloading Mulesoft Anypoint Studio visible that Download 30 day free trial.So How to use after 30 Days? -

Image
for downloading mulesoft anypoint studio visible download 30 day free trial.so how use after 30 days? the 30 day free trial not anypoint studio, mule standalone container. studio continue work indefinitely, not standalone mule container dev, production releases etc. after 30 days container stop running applications can continue develop in anypoint studio. continue using standalone container/s need purchase enterprise license mulesoft. can contact them via website. can use community edition free, uses same studio, need make sure using community runtime when comes deployment not using enterprise features.

c# - linq group by and select multiple columns not in group by -

i'm trying select multiple columns not in group using linq - c#. using linq, i'm trying group isnull(fieldone,''),isnull(fieldto,'') , select field_one, field_two, field_three each group. each row group return, want see numerous rows. so far have following, can't seem select needed columns. var xy = tablequeryable.where( !string.isnullorempty(cust.field_one) || ! string.isnullorempty(ust.field_two) ).groupby(cust=> new { field_one= cust.field_one ?? string.empty, field_tow = cust.field_two ?? string.empty}).where(g=>g.count()>1).asqueryable(); can pls? you pretty there - missing select group: var xy = tablequeryable .where(!string.isnullorempty(cust.first_name) || ! string.isnullorempty(ust.lastname)) .groupby(cust=> new { first_name = cust.first_name ?? string.empty, last_name = cust.last_name ?? string.empty}) .where(g=>g.count()>1) .tolist() // try work around c

node.js - IONIC BUILD IOS Does Nothing and just drop to next line -

when trying build , run ionic project, fail silently (no ouput) without building project or running simulator. zeeshans-mbp:my-reddit zeeshansabri11$ ionic build ios zeeshans-mbp:my-reddit zeeshansabri11$ ionic emulate ios system details: cordova cli: 5.3.3 gulp version: cli version 3.9.0 gulp local: ionic version: 1.1.0 ionic cli version: 1.7.7 ionic app lib version: 0.6.3 ios-deploy version: 1.8.2 ios-sim version: 5.0.3 os: mac os x el capitan node version: v5.0.0 xcode version: xcode 7.1 build version 7b91b nothing happening. getting errors , check udemy instructor , have been told installed node using sudo have uninstall complete node, ionic , cordova , reinstall i'm not getting errors build , emulate command not doing @ all. i have seen similar post on forum seems old , recommending downgrade old version not sure if it's still valid. btw: i'm new ionic, cordova , node please go easy on me :) the problem using node 5.0.0 use node 4.1.2

elasticsearch - Data Store with multiple shard keys -

i've been researching several different data store technologies can used storing huge amounts of semi-structured logs people search through later. i've looked @ cassandra, riak, , elastic search far, , seems elastic search offers closest fit i'm interested in (largely because indexes transparently). however, there's 1 feature i'm interested in seems escape them all, , wondering if there data store feature. what i'm thinking ability transparent shard on multiple key. clear, i'm not talking using composite key sharding. mean if had table sharded user_id , time_of_creation , , ip_address , , inserted row, 3 copies of row created, each 1 in different cluster that's sharded different key (or maybe somehow in same cluster. important part data duplicated). , when wanted query table later, data store transparently choose cluster use. in articles i've read cassandra, people recommend doing this, it's manual process in @ least 3 ways: for inser

android - onLongClick should only happen if condition is true -

this part of code: if(user.getuserid().equals(thislike.getuserid())) { log.i("on marker click", "equal user id!"); toast.maketext(getapplicationcontext(), r.string.longpress, toast.length_short).show(); markerimage.setonlongclicklistener(new view.onlongclicklistener() { @override public boolean onlongclick(view v) { log.i("on marker click", "onlongclick happens!"); if(user.getuserid().equals(thislike.getuserid())) { log.i("on marker click", "equal user id!"); opencontextmenu(markerimage); return true; } else { log.i("on marker click", "not equal user id!!"); return false; } } }); } else {

usb - Powershell WMI: Runs without any errors/exceptions, however doesn't execute script -

Image
$filter = ([wmiclass]"\\.\root\subscription:__eventfilter").createinstance() $filter.querylanguage = "wql" $filter.query = "select * __instancecreationevent within 5 targetinstance isa 'win32_logicaldisk'" $filter.name = "usbfilter" $filter.eventnamespace = 'root\cimv2' $result = $filter.put() $filterpath = $result.path $consumer = ([wmiclass]"\\.\root\subscription:commandlineeventconsumer").createinstance() $consumer.name = 'usbconsumer' $consumer.commandlinetemplate = "c:\windows\system32\windowspowershell\v1.0\powershell.exe –executionpolicy bypass -file c:\test.ps1" $consumer.executablepath = "c:\windows\system32\windowspowershell\v1.0\powershell.exe" $consumer.workingdirectory = "c:\" $result = $consumer.put() $consumerpath = $result.path $bind = ([wmiclass]"\\.\root\subscription:__filtertoconsumerbinding").createinstance() $bind.filter = $filterpath $bind.con

duplicates - Delete duplicated records within row in a df in R -

i rid of duplicated records in each row of df: df <- data.frame(a=c(1,3,5), b =c(1,2,4), c=c(2,3,7)) x1 x2 x3 1 1 1 2 2 3 2 3 3 5 4 7 i want this: x1 x2 x3 1 1 na 2 2 3 2 na 3 5 4 7 now, can achieve using apply : data.frame(t(apply(df,1, function(row) ifelse(!duplicated(row), row, na)))) but seems unlikely there isn't more compact (and perhaps efficient) way of achieving this. am missing command or package here?

jquery - Error in my javascript for hiding select options -

i have 2 attribute selections , content of second 1 dependent on selection of first. if select adult, want title option display. if select child, want mr or miss display. wrote simple javascript hide options not needed , works correctly. if select child unwanted options don't show. if change adult, options show. but, if select adult first, dropdown breaks apart , leaves me list of option values. the javascript used is $("#attrib-1").change(function () { var id = $(this).find("option:selected").attr("value"); switch (id) { case "3": $("#attrib-2 option[value='6']").wrap('<span/>'); $("#attrib-2 option[value='7']").wrap('<span/>'); $("#attrib-2 option[value='9']").wrap('<span/>'); $("#attrib-2 option[value='10']").wrap('<span/>'); break; } switch (id) { case &quo

html - Bootstrap image-circle is rotated on iOS -

Image
i´ve got problem rotating image. problem occurs on iphone in safari browser. you see (badly) red circled image. on iphone rotated 90 degrees no perceptible reason. image above displayed correctly on both browsers exact same html , css. i´m using bootstrap css framework , how images displayed: <div class="col-lg-12" style="text-align: center; margin: 20px; background-color: rgba(255, 255, 255, 0); padding: 30px; border-radius: 20px;"> <div class="col-md-3"> <img class="img-circle" src="../admin/uploads/categories/<?php echo $categoryrow["img"]; ?>" width="140px" height="140px"> </div> <div class="col-md-9"> <h2><?php echo $categoryrow['name']; ?></h2> <p><?php echo $categoryrow['description']; ?></p> <p><a class="btn btn-default" href="category.php?id=<?php

How to convert String into integers in python sickit-learn -

this question has answer here: convert strings in list int [duplicate] 2 answers i have list above: probs= ['2','3','5','6'] and want convert string numeric values following result: resultat=[2, 3, 4, 5, 6] i tried solutions appearing on link: how convert strings integers in python? such one: new_list = list(list(int(a) in b) b in probs if a.isdigit()) but didn't work, can me adapt function on data structure, thankful. >>> probs= ['2','3','5','6'] >>> probs= map(int, probs) >>> probs [2, 3, 5, 6] or (as commented): >>> probs= ['2','3','5','6'] >>> probs = [int(e) e in probs] >>> probs [2, 3, 5, 6] >>>

java - How can I get the index of the highest number in an Object[] in an ArrayList -

Image
how can find highest value or index of highest value in object in arraylist shown below. i attempted iterate arraylist takes whole object , need each element. appreciated thanks if question right use this. for (int = 0; < arraylist.size(); i++) { object array[] = arraylist.get(i); (int j = 0; j < array.length; j++) { // compare here } } first iterate on arraylist , on each array.

c++ - Taking the address of a temporary object of type 'Node' -

t.preordertraversal(t, &t.getroot()); error taking address of temporary object of type 'node'. root node class object. function preodertraversal node object point, give address of node object , error occurred. isn't right way do? class nodelist; class node { private: node* parent; int elem; nodelist* children; node *next; node *prev; }; class nodelist { public: nodelist(); void addnodeatrank(int, int); private: node* header; node* tailer; }; class tree { private: int n; node root; public: tree(); void addnode(tree &t, int, int, int); void preordertraversal(const tree& t, node* p); void postordertraversal(const tree& t, node* p); void printxyofnode(const tree& t, int nodenumber); node getroot(); node* getnodebyelem(node& n, int); }; node::node() { children = nullptr; parent = nullptr; elem = 0; next = nullptr; prev = nullptr; } nodelist::nodelis

graph - Stata-related graphic enquiry -

i have basic question stata. have repeated cross section of individuals year 1 year 20. each individual, year, have year-specific variable- gdp per capita in country instance. variable defined each individual each year, across years. therefore have 20 unique data points variable. want plot variable function of time (say in two-way plot). twoway command not work because have lot more 20 points 20 values because each value have defined on n number of people in cross section in year. how can create separate variable extracts distinct values variable in current form? with simple example of data have saved , others time. stands, question difficult understand. pointed out, lacks both code , example data. please rewrite others can find , use whatever posted here. my interpretation have panel data. variable gdp year-specific (in every panel information duplicated), you'd graph against time. tag 1 instance, , draw graph conditional on that. example: clear set more off //

sql server - T-SQL: sp_depends with a cursor -

i have bunch of views in db dependencies listed for. currently, i'm using 'sp_depends' sproc this. speed process, i'm attempting use sp_depends sproc in cursor iterates on list of views. however, i'm not having luck , i've spent embarrassing amount of time trying "shotgun" fixit. below i've got far. declare @viewnames table ( viewname varchar(255) ) insert @viewnames select name [amf_article].sys.views declare @tablecursor cursor, @viewname varchar(100); set @tablecursor = cursor select viewname @viewnames open @tablecursor fetch next @tablecursor @viewname while(@@fetch_status = 0) begin declare @sql varchar(max) set @sql = 'sp_depends ''[dbo].' + @viewname + '' print @sql exec @sql fetch next @tablecursor @viewname end i think going on quoting combined exec call. can't single quotes match up, , when do, still tells me no. when run statement sp_depends '[dbo].[v_am

swift - PFObject subclass gets "Cannot convert value of type 'Match' to expected argument type '@noescape (AnyObject) throws -> Bool'" error -

i'm getting following error when calling indexof on array of subclass of pfobject. cannot convert value of type 'match' expected argument type '@noescape (anyobject) throws -> bool' my class: class match: pfobject, pfsubclassing {xxxx} the method error happening: func imagepickercontroller(picker: uiimagepickercontroller, didfinishpickingmediawithinfo info: [string : anyobject]) { //dismiss image picker self.dismissviewcontrolleranimated(true) { () -> void in //wait dismissal in case there error show let recordedvideofileurl = info[uiimagepickercontrollermediaurl] as? nsurl if let recordedvideofileurl = recordedvideofileurl { //upload file s3 { let uploadrequest = try s3uploadmanager.uploadfile(self.match!.localpathtovideo()!) self.match!.saveeventually({ (success: bool, error: nserror?) -> void in if (suc

django - Overriding url() from ImageField -

i have image field avatar = models.imagefield(upload_to="avatar", null=true, blank=true) and using view class editview(successmessagemixin, updateview): model = mysiteuser form_class = mysiteuserform pk_url_kwarg = 'pk' template_name = 'update_form.html' success_url = '/myprofile/' success_message = "zmiany zostały wprowadzone." def form_valid(self, form): image_to_del = mysiteuser.objects.get(username=form.instance) print("na dysku plik", image_to_del.avatar) print("formularz pole 'avatar'", form.instance.avatar) if form.instance.avatar != self.request.user.avatar: self.request.user.avatar.delete() return super().form_valid(form) in template form <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save" /> </form>

java - XML to JSON - unexpected behaviour while converting lists? -

this json value: { "hello": [ { "names": { "name": "abc" } }, { "names": { "name": "def" } } ] } i tried using xml.tostring(new jsonobject()) , , get: <hello> <names> <name>abc</name> </names> </hello> <hello> <names> <name>def</name> </names> </hello> whereas, xml expected this: <hello> <names> <name>abc</name> </names> <names> <name>def</name> </names> </hello> this unexpected behaviour results in invalid xml error, since there no root element now. missing here? the issue in json code. [] means array , , definition array set of e

javascript - Angularjs ng-style background image doesn't work when the URL contains brackets -

i'm using ngstyle directive in angularjs change background image of element , i've noticed the style not applied when url of image contains brackets "()". <div ng-style="{'background-image': 'url(https://sumosoft.blob.core.windows.net/rescorp/properties/nw1/marylebone%20road/harley%20house/63/27283_hi_res_1_(1)_1200.jpg)' }"> hello </div> any suggestion? fiddle

php - Pull single Instagram Feed from single user with hashtag using API -

i going building website upcoming client pull instagram feed of posts within account specific hashtag (use #helloworld @myaccount example). recent updates instagram api make process confusing. can authenticate through gui interface once through client's account , store access token. being said, there doesn't seem clear way check if auth token has expired and, if has, request new 1 without requiring go through gui "allow app use..." interface. worried feed functionality may break on our site result of if token expire reason. missing here? there way continue re-authenticate through instagram without having this? not find clear information through documentation. second, running on php-driven site. how go pulling posts single account particular hashtag once auth code has been received , verified valid. must limit hashtags single account. great, there doesn't seem great documentation since instagram updated api. thanks! there no way authenticate auto

First argument in form cannot contain nil or be empty in a rails form -

i getting mad cause have situation trying modify quantity of item via custom action , don´t know why works in 1 view doesn´t in another, stupid can´t find reason, action add_item works perfectly, update_item_quantity doesn´t display de view , shows exception: first argument in form cannot contain nil or empty here code: routes.rb: resources :designs resources :carts resources :cart_items :add_to_cart, on: :member post :add_item, on: :member post :update_item_quantity, on: :member end te controllers following: cart_items_controller.rb def add_item @cart_item = cartitem.new(add_item_params) @design = design.find(params[:design_id]) @cart = cart.find(current_user.cart_id) @cart_item.design_id = @design.id @cart_item.cart_id = current_user.cart_id if @cart_item.save flash[:success] = "design succesfully added active cart" redirect_to cart_path(@cart) else flash[:danger] = "design could

f# - Upcasting and Generics -

i perplexed this. why doesn't work - aren't explicitly telling 't indeed view ? let foo<'t when 't :> view> (v:'t):view = v error fs0001: expression expected have type view here has type 't msdn : in many object-oriented languages, upcasting implicit; in f#, rules different. upcasting applied automatically when pass arguments methods on object type. however, let-bound functions in module, upcasting not automatic , unless parameter type declared flexible type. the :> operator performs static cast, means success of cast determined @ compile time. the minimal code let foo<'t when 't :> view> (v:'t):view = v :> _

python 2.7 - Use of a dictionary + Bitarray -

i need know if bitarray in dictionary not why code not work, idea? dic={} bb=bitarray() bb.append(false) temp=bitarray() temp.append(false) dic[bb]="" if temp in dic: print("hello") this tricky one. dict's keys should hashable. said, let's take @ hashes generated both bitarrays. >>> bb bitarray('0') >>> temp bitarray('0') >>> hash(bb) 1871851 >>> hash(temp) 1871843 therefore, when attempt if temp in dic: , hash of temp not found in dic. therefore don't desired result. don't know why hash of bb , temp different. you instead: >>> dic[bb.tostring()] = 'test' >>> if temp.tostring() in dic: ... print 'hello' ... hello you use bb.tobytes() dict's key if desire. in case, use temp.tobytes() comparison.

android - Using SimpleDateFormat to get current date -

i looked intensively on google, , here find code works show current date i've been through few of suggested questions, don't work show current date day app runs. doing same current time. goal able tapping textview of either date, or time, user can change time reflect choose. return date/time chosen , return reflect in textview. the part need getting current actual date of app being opened, time separately. here code.... date curdate = new date(); simpledateformat format = new simpledateformat("ee, mm dd, yyyy"); string datetostr = format.format(curdate); trying output string show in textview work. want show short hand of both day of week, , month. thinking might need locale, not familiar this. would appreciate date code. or tutorial date can follow. believe can figure out how picker data after user selects date/time, having hard time showing picker when user selects textview. can show via onclicklistener tried google's example of picker

php - Padding when sorting categories fails and mis-sorts -

Image
i'm trying code channel viewer teamspeak 3 server (which has parent , child channels/categories, , child channels child channels , on), when trying style , add padding depends on is, fails , turns out this: while it's supposed this: (obviously not styled, point) here's code: private $_allchannels = array(); private $_allclients = array(); private function showchannels($parentid, $padding) { $response = ''; foreach ($this->_allchannels $channel) { $channelparent = $channel['pid']; $channelid = $channel['cid']; $channelname = $channel['name']; if ($channelparent == $parentid) { $response .= '<span style="margin-left: ' . $padding*2 . 'em;">' . $channelname . '</span><br>'; $response .= $this->showchannels($channelid, $padding++); } } return $response; } public function i

datetime - How to handle daylight saving time properly in Java 7 without Joda Time? -

before marking duplicate read thoroughly plus can't use joda time , java 8 time.util* . i'm trying current date of country dst enabled. since time zone [local-millis] = [utc-millis] + [offset-millis] added dst_offset time in dst enabled country, done on linux machine gmt_time + local_time_zone_offset + dst_offset current local time. the code print current time of istanbul has dst enabled 1 hour. public class dstinstanbul { public static void main(string...args){ calendar calendar = calendar.getinstance(); timezone timezone = timezone.gettimezone("europe/istanbul"); calendar.settimezone(timezone); calendar.add(calendar.millisecond, timezone.getdstsavings()); simpledateformat simpledateformatlocal = new simpledateformat("yyyy-mm-dd hh:mm:ss"); simpledateformatlocal.settimezone(timezone.gettimezone("europe/istanbul")); system.out.println("current date , time : "

Type coercion of blank nodes in JSON-LD -

i have set of json files trying upgrade json-ld through addition of context reference. 1 feature of files array of items of same type. trying use type coercion specify type, i'm having trouble. items in array represented blank nodes, don't have explicit ids - possible automatically assign them types? i'm not sure if possible within json-ld syntax - i'm sure must know! here's presently works: { "@context": { "ex": "http://example.com/schema#", "items": { "@id": "ex:hasitem", "@container": "@set" }, "item": "ex:item", "size": "ex:size", "weight": "ex:weight" }, "@id": "my item set", "items": [ { "@type": "item", "size": 43, "weight": 57 }, { "@type": "item",

python - Plotting a table of log-log values -

i have table of values aren't logs find relation think need create log-log plot. values have are: r c ---------- 0.2 103 2 13.9 20 2.72 200 0.800 2000 0.401 20000 0.433 how plot logs of these values ?

angular - Ionic2 change Tabs selectedIndex property from a childpage -

i'm kind of beginer in angular2 , ionic2. trying build own small app using ionic2's tabs component. i want able change tab using button in childpage. have tried using navcontroller.setroot() , navcontroller.push() none of them have desired behaviour. setroot(homepage) sets correct view doesn't change selected tab in tab menu. push(homepage) sets correct view tabs menu not visible anymore. i bit confused how should comnunicate tabspage (the @component holds tabs) single pages. thanks! well, there should easier way this, did way: because in order change active tab should tabs component, used shared service handle communication between the pages inside tab , the tab container (the component holds tabs) . though events shared service approach because easier understand , mantain when applications start growing. so tabservices only creates observable allow tabs container subscribe it, , declares changetabincontainerpage() method called tab pages

Remote Elasticsearch connection from local rails -

i have rails app running on remote elasticsearch server. rails console works fine connection elasticsearch remote server when try db:migrate or assets:precompile looks tries connect elasticsearch local server , throw error faraday::connectionfailed: connection refused - connect(2) "localhost" port 9200 if not want use elastic search, remove config settings initializers folder(if have created any). but, if still want use elastic search , since not how configuration setting looks like, start elastic search in tab in terminal avoid this.

r - Iterating through equal time intervals in data frame -

so have data frame looks this: > sample userid time_intervals freq 00008bb4da272a962c275faa085d66d2 2009-01-01 0 00008bb4da272a962c275faa085d66d2 2009-02-01 0 00008bb4da272a962c275faa085d66d2 2009-03-01 0 00008bb4da272a962c275faa085d66d2 2009-04-01 0 00008bb4da272a962c275faa085d66d2 2009-05-01 13 00008bb4da272a962c275faa085d66d2 2009-06-01 0 00008bb4da272a962c275faa085d66d2 2009-07-01 4 dput accessible here: https://gist.github.com/anonymous/d4ccfed8e315e3bc7f3233a7e55512f9 it frequency table divided 35 periods of 1 month (the same users). in other words, every 35 rows, userid shows new value, , time_intervals starts on again 2009-01-01. now, i'm having trouble figuring out how following (i have little experience data frames): need find out number of consistently active users (where freq > 0 in months) across periods of 12 months, starting 2009-01-01 , moving 1 month further @ each step. nee

python - Find all upper, lower and mixed case combinations of a string -

i want write program take string, let's "fox" , display: fox, fox, fox, fox, fox, fox, fox, fox my code far: string = raw_input("enter string: ") length = len(string) in range(0, length): j in range(0, length): if == j: x = string.replace(string[i], string[i].upper()) print x output far: enter string: fox fox fox fox >>> >>> import itertools >>> map(''.join, itertools.product(*((c.upper(), c.lower()) c in 'fox'))) ['fox', 'fox', 'fox', 'fox', 'fox', 'fox', 'fox', 'fox'] or >>> s = 'fox' >>> map(''.join, itertools.product(*zip(s.upper(), s.lower())))

html - What is the 80 columns rule? -

i'm high school student , have create website tourism in computer sciences class. on criteria sheet, teacher has written "code should strive fit 80 columns possible ease of printing". have tried search answer , found out sort of rule can't wrap head around means. can me out? examples great. like many rules of thumb, @ least partly based on opinion. derives widespread use of 80-column punched cards , video terminals through mid-1990s. , other rules, has been discussed @ length -- here: eightycolumnrule is 80 character limit still relevant in times of widescreen monitors? [closed] why 80 characters 'standard' limit code width?

scala - When is it appropriate to use a TrieMap? -

i have been reading posts , wondering if can present situation on when triemap preferable using hashmap. so architecture decision should motivate use of triemap? as per documentation. it's mutable collection can safely used in multithreading applications. a concurrent hash-trie or triemap concurrent thread-safe lock-free implementation of hash array mapped trie. used implement concurrent map abstraction. has particularly scalable concurrent insert , remove operations , memory-efficient . supports o(1), atomic, lock-free snapshots used implement linearizable lock-free size, iterator , clear operations. cost of evaluating (lazy) snapshot distributed across subsequent updates, making snapshot evaluation horizontally scalable. for details, see: http://lampwww.epfl.ch/~prokopec/ctries-snapshot.pdf also has nice api caching . example have calculate factorials of different number , re-use results. object o { val factorialscache

java - Integrate redis with spring boot -

how can integrate redis spring boot? after add below dependecy, code structure saving user details list user name key , user object value in redis server. fetch user details given user name? <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-redis</artifactid> <version>1.2.7.release</version> </dependency> take @ example ... https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-redis

webpack expose-loader not working with jQuery -

in webpack config have following line expose jquery on global scope { test: require.resolve('jquery'), loader: 'expose?$!expose?jquery' }, i have file uses $. example: .getscript(`${url}/scripts/test.js`) .done(() => { document.queryselector('#trustlogo_ph').innerhtml($.trustlogo(`${url}/content/themes/images/trustlogo.png`, 'sc4', 'none')); }); however, during webpack build, following error: error '$' not defined no-undef also, if put following directly in file: require('expose?$!expose?jquery!jquery'); i error: error unable resolve path module 'expose?$!expose?jquery!jquery' import/no-unresolved according page, above should work: https://webpack.github.io/docs/shimming-modules.html . i must missing something. advice?

android - SQLiteException : No such column -

sorry if question possibly duplicate. i've looked other similar questions , answers, since i'm not familiar sql terms, i'm not able find solution trough these answers. can please check code find what's wrong? public class dbhelper extends sqliteopenhelper { private static final string database_name = "todolist_db"; private static final string table_todos = "todos"; private static final string todo_title = "todo_title"; private static final string todo_category = "todo_category"; private static final string todo_year = "todo_year"; private static final string todo_month = "todo_month"; private static final string todo_day = "todo_day"; private static final string todo_hour = "todo_hour"; private static final string todo_minute = "todo_minute"; private static final string todo_priority = "todo_priority"; public dbhelpe

parse.com - No data coming through when passing an array to an AngularJS controller using a function -

i working on angularjs application uses parse create array of names. pass array controller, use in html. problem no data coming through , i'm not sure why. have tested parse connection, , working correctly, , test controller , passing data correctly. when combine 2 stops working. parse.js function playernames() { parse.$ = jquery; parse.initialize("my key", "my key"); var names = new array(); var gamescore = parse.object.extend("gamescore"); var query = new parse.query(gamescore); query.find({ success: function (results) { (var in results){ var name = results[i].get("playername"); alert(name); names.push(name); } return names; }, error: function (error) { alert(error.message); return names; }}); }; app.controller('namecontroller', ['$scope', function($scope) {$scope.names = playernames()}]); index.html <div class=&qu

React Native 0.29+ without dev mode in iOS? -

after upgrading rn 0.29.1 dont have url in appdelegate.m file can dev=false... there obvious way turn off dev mode i'm missing? it doesn't seem though facebook has updated docs on how use new rctbundleurlprovider . have added in old urlwithstring previous versions , works fine: add: jscodelocation = [nsurl urlwithstring:@"http://ipaddress:8081/index.ios.bundle?platform=ios&dev=true"]; comment: [[rctbundleurlprovider sharedsettings] setdefaults]; jscodelocation = [[rctbundleurlprovider sharedsettings] jsbundleurlforbundleroot:@"index.ios" fallbackresource:nil];

ios - UITextView should avoid deleting the html tag -

i have uitextview, display content css style comment text. basically, there htmlstring somestyles. nsmutableattributedstring *attributedstringforcomment = [[nsmutableattributedstring alloc] initwithdata:[formatedstr datausingencoding:nsunicodestringencoding] options:@{ nsdocumenttypedocumentattribute: nshtmltextdocumenttype } documentattributes:nil error:nil]; which display content css style on uitextview. now, if 1 edit text, hide comment section removing css styles(so user can not delete other's comment) apply style nsmutableattributedstring adding attribute strike/color deleting/added word. problem : when user done editing part want string editing text html comment's css style. when apply nsmutableattributedstring style, removes html tag , css style. any trick/tips me reach solution.

java - Stack overflow with tail recursion -

why getting stack overflow exception? isn't meant tail recursive function? public static int tailfact(int n, int mult) { if(n == 0) { return mult; }else { return tailfact(n-1, n*mult); } } public static int factt(int n) { return tailfact(n, 1); } public static void main(string[] args) { factt(100000); } /*exception in thread "main" java.lang.stackoverflowerror @ test3.test.tailfact(test.java:13) @ test3.test.tailfact(test.java:13) ... */ java doesn't support tail recursion.

python - I have lxml but still I am asked to install it -

i have lxml because checked using `import pandas pd ` `pd.show_versions(as_json=false)` and have lxml version 3.6.0 in "installed versions" installed versions ------------------ commit: none python: 2.7.12.final.0 python-bits: 64 os: linux os-release: 3.19.0-64-generic machine: x86_64 processor: x86_64 byteorder: little lc_all: none lang: en_us.utf-8 pandas: 0.18.0 nose: 1.3.7 pip: 8.1.2 setuptools: 20.3 cython: 0.23.4 numpy: 1.10.4 scipy: 0.17.0 statsmodels: 0.6.1 xarray: none ipython: 4.1.2 sphinx: 1.3.5 patsy: 0.4.0 dateutil: 2.5.1 pytz: 2016.2 blosc: none bottleneck: 1.0.0 tables: 3.2.2 numexpr: 2.5 matplotlib: 1.5.1 openpyxl: 2.3.2 xlrd: 0.9.4 xlwt: 1.0.0 xlsxwriter: 0.8.4 lxml: 3.6.0 bs4: none html5lib: 0.999999999 httplib2: none apiclient: none sqlalchemy: 1.0.12 pymysql: none psycopg2: none jinja2: 2.8 boto: 2.39.0 but when tried run table_list = pd.read_html("http://www.psmsl.org/data/obtaining/") i massage ---------------