Posts

Showing posts from August, 2012

How to create docker base image from Amazon Linux AMI -

i beginner in docker , need implement docker in aws , want create own images. docker docs, followed process create dockerfile. question how create base image using amazon linux ami? i have amazon linux machine in aws , have done security restriction done in instance. want instance base image docker , want create other docker images base image security restrictions. how can accomplish ? in advance. if want application compatibility, can try centos image amazon linux based on: from centos ..... regards

jquery - Get the position from top of current window -

is there way bottom position using jquery of current viewport while scrolling . not bottom position of document bottom position of visible window. you need sum window's scrolltop , innerheight properties. may done way: var win = $(window); var info = $('.bottom-position'); function onscroll() { var viewportbottom = win.scrolltop() + win.innerheight(); info.html('bottom viewport at: ' + viewportbottom + 'px top.'); }; win.on('scroll resize', onscroll); onscroll(); body { margin: 0; font-family: sans-serif; } .content { height: 1000px; background: #000; } .bottom-position { position: fixed; bottom: 0; right: 0; color: #fff; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"></div> <div class="bottom-position"></div> also on jsfiddle ....

c# - Sending JSON with escape characters such as group separators -

specific question : how should 1 format characters such group separator (0x1d) in json? details: i've inherited c# codebase reading barcodes, putting them in json messages , sending them on way service (not c# or windows based!) the code takes byte array such as: byte[] rawdata = { 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 52, 29, 49, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48}; and uses code translate byte array string put in .json: string datanew = regex.unescape(new string(encoding.ascii.getstring(rawdata).tochararray())); the relevant part of .json looks like: "notes": [ { "id": 0, "details": "produc code: codetype: datamatrix, data: 000000000000000000000000000004\u001d1000000000000000", "active": true, "acknowledged": false, "reported": fal...

javascript - Can memory usage be reduced by avoiding var? -

let's have class myclass function method() going called a lot . of these implementations going more efficient? function myclass() { this.method = function () { var number = 10; var boolean = true; var string = "string"; // }; } function myclass() { this.data = {}; this.method = function () { this.data.number = 10; this.data.boolean = true; this.data.string = "string"; // }; } the first implementation creates new variables eligible garbage collection after execution of function since there's no reference them, great. however, if call function 3 times, there memory allocated total of 3 numbers, 3 booleans , 3 strings. the second implementation doesn't create new variables, overwrites values of previous call of function instead. mean after 3 invocations of function, memory allocated 1 number, boolean , string, instead of 3? there 3 times less memory consumed? ...

How to POST the String Payload to http localhost in mule? -

am new mule , need post string payload stored in variable http localhost. below configuration. <flow name="requestflow" processingstrategy="synchronous"> <set-variable variablename="variable1" value="#[payload]" doc:name="set request"/> <ws:consumer config-ref="web_service_consumer" doc:name="web service consumer" operation="submit"/> <mulexml:dom-to-xml-transformer doc:name="dom xml"/> </flow> i need post call before consuming web service. please advise. for instance, have following url- localhost:8081/getdetails?country=india and have query param named "country". query param in string format can use mel store value in variable follows- [message.inboundproperties.'http.query.params'.country] your variable like <set-variable variablename="hello" value="#[message.inboundproperties....

javascript - Firebase 3 Ionic Email Verification -

i working on ionic application uses firebase 3 baas. application trying implement email verification feature. firebase sending email email template want change url in email node server run "applyactioncode(oobcode)" , set emailverified property user in database true. problem cannot find way send uid if user in email. here code in ionic - register: function(formuser) { var d = $q.defer(); auth.$createuserwithemailandpassword(formuser.email, formuser.password) .then(function(user) { $log.log("user created uid: " + user.uid); auth.user = $firebaseobject(usersref.child(user.uid)); auth.user.id = user.uid; auth.user.email = user.email; auth.user.image = user.photourl; auth.user.emailverified = user.emailverified; auth.user.provider = user.providerid; user.sendemailverification(); auth.user.$save().then(function(){ d.resolve(); }).cat...

reactjs - How to fade text in, then out -

i'm trying make notification next appear text input inform users text saved, , fade notification text out. basically i'm trying replicate action, when corresponding text input submitted. $(this).fadeout().next().fadein(); i can't think of way fade in, out, isn't absurdly roundabout. i'm using redux well, , use that, it's not requirement. advice appreciated. you can use css take care of that. here's simple example (not using redux). use js trigger, css style. class app extends react.component { constructor() { super(); this.state = { show: false }; this.shownotification = this.shownotification.bind(this); } shownotification() { // can use redux this. this.setstate({ show: true, }); settimeout(() => { this.setstate({ show: false, }); }, 1000); } render() { return ( <div> <button onclick={this.shownotificat...

python - TypeError: 'long' object has no attribute '__getitem__' for MySQL -

i trying retrieve data mysql table. my code def getdata(self, id): #load data mysql query = 'select * goals id = "%s"'% (id) try : cursor.execute(query) data = cursor.fetchone() conn.commit() except exception e: raise e data = false if data not false: row in data: self.id = row[0] self.description = row[1] self.imageid = row[2] self.imagelink = row[3] self.location = row[4] self.status = row[5] self.publishid = row[6] self.goardid = row[7] self.likesid = row[8] self.createddate = row[9] self.createdtime = row[10] self.hide = row[11] x = newthink() print x.create_new() print x.goalid, x.subscriptionid, x.likesid, x.goardid see = x.adddata('just second', 'nairob...

check variable in mysql table with php -

i want check variable in mysql table , action done if fits. want check whether logged in account has type = d. if so, should redirected, if not normal html code should appear. now, gets completly ignored. this code <?php require_once("./include/membersite_config.php"); session_start(); if(!$fgmembersite->checklogin()) { $fgmembersite->redirecttourl("login.php"); exit; } else { $now = time(); // checks time, homepage gets loaded if ($now > $_session['expire']) { session_destroy(); header("location: http://www.uni-landau.de/vivian/source/expiredlogin/expiredloginlayout.php"); exit(); } else { ?> <?php include "connect.php"?> <?php include "functions.php"?> <?php $check_login = mysql_query("select type users username='$username'"); $run = mysql_fetch_array($che...

How to use a custom TokensRegex rules annotator with Stanford CoreNLP Server? -

the tokensregex rules color annotator ( stanford-corenlp-full-2016-10-31/tokensregex/color.rules.txt ) loads when using corenlp through command line fails web server java.lang.illegalargumentexception: unknown annotator: color . setup # custom.properties annotators=tokenize,ssplit,pos,lemma,ner,regexner,color customannotatorclass.color = edu.stanford.nlp.pipeline.tokensregexannotator color.rules = tokensregex/color.rules.txt command line $ java -cp "*" -xmx2g edu.stanford.nlp.pipeline.stanfordcorenlp -props custom.properties -file ./tokensregex/color.input.txt -outputformat text [main] info edu.stanford.nlp.pipeline.stanfordcorenlp - registering annotator color class edu.stanford.nlp.pipeline.tokensregexannotator ... [main] info edu.stanford.nlp.pipeline.stanfordcorenlp - adding annotator color [main] info edu.stanford.nlp.ling.tokensregex.coremapexpressionextractor - reading tokensregex rules tokensregex/color.rules.txt [main] info edu.stanford.nlp.ling.tokensre...

php - Sql query is not fetching results with variables -

i trying execute sql query using inner join ... code below... part 1 works fine.. , creating value $query_adlist dynamically.. when user variable $query_adlist in part 2, not fetch results. part 1. $query_adlist=""; $ad_list_countx=mysql_query("select count(ads_id) ads id=$id"); if($ad_list_countx){$ad_list_count=mysql_fetch_row($ad_list_countx);} if(isset($ad_list_count) && $ad_list_count[0] > 0) { $query_adlist .="&& ("; $query_ad_listx=mysql_query("select ads_id ads id=$id"); if(isset($query_ad_listx)) { $sign=" || "; $count=1; while($query_ad_list=mysql_fetch_array($query_ad_listx)) { if($ad_list_count[0] == $count){$sign=") &&";} $query_adlist .="ad_clicks.ads_id=".$query_ad_list['ads_id'].$sign; $count++; } } } the value of variable after while loop...

python - How to delete a certain model instance in django after a given date -

class mess(models.model): muser = models.onetoonefield(user) mess_name = (('gh','girls hostel top mess'), ('ih','girls hostel down mess'), ('mm','mega mess'), ('fb','first block mess'), ('sb','second block mess'), ('tb','third block mess'), ) mess_name = models.charfield(max_length=25, choices =mess_name,primary_key=true) per_day_cost = models.integerfield() def __str__(self): return self.mess_name class messmenu(models.model): mess_name = models.foreignkey(mess) day = models.datefield() morning = models.textfield() afternoon = models.textfield() snacks = models.textfield() dinner = models.textfield() def __str__(self): return self.mess_name once create object in messmenu want django delete object after 7 days. please let me k...

ios - ReactiveCocoa: Xcode asking me the conversion to swift 3 -

Image
evening, i'm working project using cocoapods, simpleauth pod . now can't understand why, after installed pods , updated them, opening workspace receive warning: while readme of reactivecocoa saying swift 3 ready. mine reactivecocoa version 4.2.2, latest. you may have change xcode 8.1 toolchain use swift 3.0.

ember.js - Find all components by name using wildcard -

is possible find ember components based on name using wildcard or regex? so far found way find component fullname: appinstance.lookup('component:my-component') but want achieve like: appinstance.lookup('component:my-*') return array of components name begins 'my-' you can list names of entries using require.entries : function getkeys(){ return object.keys(require.entries).filter(function(key){ return /.*components\/my-.*/.test(key); }; then can make lookup keys. (be aware function getkeys returns both component's js file names , template file names.)

if statement - Python If/Else Only Returning In Order, Not By Logic -

resolved when integer containing "0" or "4" entered, if-statement returns first in statement. for example, in code below, if enter "60", execute: print "nice, you're not greedy - win!" exit(0) not dead("you greedy bastard!") as expected how_much >= 50. have tried bunch of changes, can't seem execute intended. know what's going on here? def gold_room(): print "this room full of gold. how take?" number_type = false while true: choice = raw_input("> ") how_much = int(choice) if "0" in choice or "4" in choice , how_much < 50: print "nice, you're not greedy - win!" exit(0) elif "0" in choice or "4" in choice , how_much >= 50: dead("you greedy bastard!") else: print "man, learn type number. put 0 or 4 in num...

Spark Pivot String in PySpark -

this question has answer here: pivot string column on pyspark dataframe 1 answer i have problem restructuring data using spark. original data looks this: df = sqlcontext.createdataframe([ ("id_1", "var_1", "butter"), ("id_1", "var_2", "toast"), ("id_1", "var_3", "ham"), ("id_2", "var_1", "jam"), ("id_2", "var_2", "toast"), ("id_2", "var_3", "egg"), ], ["id", "var", "val"]) >>> df.show() +----+-----+------+ | id| var| val| +----+-----+------+ |id_1|var_1|butter| |id_1|var_2| toast| |id_1|var_3| ham| |id_2|var_1| jam| |id_2|var_2| toast| |id_2|var_3| egg| +----+-----+------+ this structure try achieve: +----+-----...

java - eclipse package with dot not representing directory structure -

in eclipse can created package name dots in it. i.e danny.com.app i have thought create directory structure of app/com/danny, eclipse create package name call danny.com.app with no directory structure representing this please can explain me thanks danny of course, package names go "a.b.c" i guess: package empty far. think settings control if eclipse creates empty directory create package. thus: see happens when add package. pretty sure eclipse create a/b/c directory in filesystem. but maybe problem using eclipse package view @ project. thing is: eclipse has different views can use inspect project. package explorer ... shows packages , whereas file explorer shows actual file system folders, contents.

html - Link not working Inside Div -

i beginner , have stupid question ask. created these 2 divs , have linked 2 pages them. problem is, 2nd link (sign in) works first 1 won't. here's html: <div id="intro-img" class="animated fadein"> <a href="signup.html" class="btn">sign up</a> <div class="wallpaper" alt="wireframe"></div> <div id="intro-img" class="animated fadein"> <a href="signin.html"class="btn1">sign in</a> <div class="wallpaper1" alt="wireframe"></div> and here's relevant css : #intro .btn { position: absolute; width: 200px; height: 70px; padding: 0; top: 150px; z-index: 40; } #intro .btn1 { position: absolute; width: 200px; height: 70px; padding: 0; top: 280px; left:5px; z-index: 50; } yo...

python - tf return Invalid JPEG data, size 1100 -

i new in tensor flow , trying feed jpg images tensorflow return error. this code: import tensorflow tf filename_queue = tf.train.string_input_producer(['d-maiz-bueno/lista']) reader = tf.wholefilereader() key, value = reader.read(filename_queue) my_img = tf.image.decode_jpeg(value,channels=0) # jpg decoder init_op = tf.initialize_all_variables() tf.session() sess: sess.run(init_op) coord = tf.train.coordinator() threads = tf.train.start_queue_runners(coord=coord) in range(50): #length of filename list image = my_img.eval() #here image tensor :) # print(image.shape) # image.show(image.fromarray(np.asarray(image))) # # coord.request_stop() # coord.join(threads) the images in d-maiz-bueno/lista , lista list jpg images. images jpg 640x480 pixels size 24.2kb the error is: tensorflow.python.framework.errors.invalidargumenterror: invalid jpeg data, size 1100 [[node: decodejpeg = decodejpegacceptable_fraction=1, channels=0, ...

ios - Segue to replace UISplitViewController master view -

Image
we have a basic uisplitviewcontroller storyboard. attempting add navigation bar icon on master screen links new view can't work desired. here's have arrow pointing new icon: we want work apple mail click icon , new view appears in master view such when click edit: but after adjusting segue settings best can use show detail shows new screen in detail view. how can new view show in master view? turns out right in front of me: kind: present modally presentation: current context the presentation setting missing.....

java - list_append causing duplicates in Map. if list_append called for for existing keys in DynamoDB -

Image
in following code in java trying append item "test.com" map field named "daily". when run code adds dulplicate key map. map<string,string> atrval = new hashmap<string,string>(); atrval.put("test.com", json); updateitemspec updateitemspec = new updateitemspec() .withprimarykey("id", id) .withupdateexpression("set daily = list_append(daily , :r)") .withconditionexpression("attribute_not_exists (daily.#k1)") .withvaluemap(new valuemap() .withlist(":r", arrays.aslist(atrval)) ) .withnamemap(new namemap() .with("#k1", "test.com")); table.updateitem(updateitemspec); attribute_not_exists should preventing doing that. ideas ...

How can I convert IANA time zone name to UTC offset at present in Ubuntu C/C++ -

in python or java can utc offset (at present time) given iana name of timezone ("america/los_angeles" instance). see get utc offset time zone name in python example. how can same using c/c++ on ubuntu 14.04? edit : preferably in thread-safe way (no environment variables). you alluded fact, it's important note offset between utc , time in time zone not constant. if time zone performs daylight saving (summer) time adjustments, offset vary depending on time of year. one way find offset take time you're interested in, hand localtime() function, @ tm_gmtoff field. tz environment variable set zone name you're interested in. here's example current time: #include <time.h> #include <stdio.h> int main() { setenv("tz", "america/los_angeles", 1); time_t t = time(null); struct tm *tmp = localtime(&t); printf("%ld\n", tmp->tm_gmtoff); } at moment prints -25200, indicating los an...

python 2.7 - Lines in my code being skipped and I am not sure why -

i using python 2.7 , pretty new python. wanted ask why lines in code being skipped although don't see reason them be. my code seen below: def add_client: code adding client def check_clients: code listing out client info modes = {'add': add_client, 'check': check_clients} while true: while true: action = raw_input('input action: \n').lower() if action in modes or ['exit']: break print 'actions available:', in modes: print i.title() + ',', print 'exit' if action in modes: modes[mode](wb) if action == 'exit': break when run code , input action not in list of modes, not print out 'actions available: add, check, exit' , seems skip seen below. input action: k input action: if change code seen below works intended: modes = {'add': add_entries, 'check': check_stats} w...

c++ - Deletion of Dynamically Allocated Memory -

i have been given task, need create string_copy function note function body , prototypes have been given source , needs maintained. portions written me after comment write code here . #include <iostream> using namespace std; int string_length(const char* string_c); char* string_copy(const char* string_c); int main() { const char* string_c = "this string , long 1 can create memory leaks when copied , not deleted"; // write code here int length = string_length(string_c); cout << "copied string: " << string_copy(string_c) << endl; return 0; } int string_length(const char* string) { int length = 0; (const char* ptr = string; *ptr != '\0'; ++ptr) { ++length; } return length; } char* string_copy(const char* string) { // need add 1 because of ’\0’ char* result = new char[string_length(string) + 1]; // write code here (remember zero-termination !) int i; (i = 0; string...

redux - Multiple reactjs applications on one portal -

i investigating implementation of portal multiple reactjs applications. need of ideas have segregating various applications (built reactjs, redux). thinking keeping applications separately hosted instances (on node)and provide access through single portal page (also in react , node). thinking using node proxy route requests various applications. practice? other line of thought package of apps single bundle. lead question of how root component structured , @ moment not sure , don't approach. appreciate feedback.

java - Using superclass method to calculate price -

i doing problem on inheritance , hierarchy of classes. problem this: have superclass contains quantity attribute. code class here: class items { private int quantity; public items(int quantity) { this.quantity = quantity; } then have 2 subclasses contains prices , other attributes. code snippet: class coffee extends items { private string size; public coffee (int quantity, string size) { super(quantity); this.size = size; } } class donuts extends items { private double price; private string flavour; public donuts(int quantity, double price, string flavour) { super(quantity); this.price = price; this.flavour = flavour; } } what want calculate total price each object. my program reads text file , creates object , stores them in arraylist. text file reading this, please note have commented first 2 lines explain each token is, not included in real file. : coffee,3,medium // name of item quantity , size donut,7,0.89,chocolate // na...

c++ - Identifier not found when it's not meant to be an identifier? -

i have defined function called decryptionarchive() this: string decryptionarchive(char i) { } can create function string identifier? i've search everywhere , have found creating pointers string data types. when run code: string chartoadd = decryptionarchive(i[curr]); yes, have imported string, , using namespace std. 'i' string, issue? actual error code is error c3861: 'decryptionarchive': identifier not found this error occurs on line 26, line of string chartoadd = decryptionarchive(i[curr]); doesn't make sense me. ideas? thanks edit: ran on laptop, works fine! going on here? you didn't declare array. treating array, yet isn't array.

dashboard - Alternative(s) to Capital One Hygieia -

all - have been looking @ tools provide near real-time visibility , feedback our entire delivery pipeline. 1 found similar have been looking captial 1 hygieia ( https://github.com/capitalone/hygieia ). do guys know of alternative dashboards available @ point in market? thanks lot in advance

java - Greedy Recursive Search -

my professor gave assignment need search around given point in grid other spots makes group (in example need find number of spots in "l" shape within problem). so grid 10x10, , professor has given spot start with. professor gave idea check neighboring spots, , add set, if spot newly found (which in set) recursively call method. private spot findspots(set<spot> spots, set<spot> activespots, spot initial) { spot newspot = null; set<spot> activeset = new hashset<spot>(); checkaround(activeset, new spot(initial.i - 1, initial.j)); checkaround(activeset, new spot(initial.i + 1, initial.j)); checkaround(activeset, new spot(initial.i, initial.j - 1)); checkaround(activeset, new spot(initial.i, initial.j + 1)); (spot spot : activeset) { newspot = findspots(spots, activespots, spot); if (grid[newspot.i][newspot.j] == true) spots.add(newspot); } return newspot; } private boolean check...

java - Executing code generated by javap -c -

lets consider following scenario: javap -c test.class > bytecodetest how execute content of bytecodetest ? you write program rebuild byte code output, don't know of any. usually use decompiler if wanted compile later. decompiler designed produce output can compiled. intellij's built in decompiler pretty , handles lambdas.

android - Three fragments in one one activity -

new android, , i'm trying make app displays name list, right topic heading on right of that, , third fragment displays details on topic heading. i'd 3 fragments diplay on main activity. want this: paint description so far main xml: <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context=".mainactivity"> <linearlayout android:id="@+id/companylistfrag_ll" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment class= "name.financialnews.companieslistfragment" android:id="@+id/list_companies" android:layout_width=...

OpenCV's Sobel filter - why does it look so bad, especially compared to Gimp? -

Image
i'm trying rebuild preprocessing have done before in gimp, using opencv. first stage sobel filter edge detection. works in gimp: now here attempt opencv: opencv_imgproc.sobel(/* src = */ scaled, /* dst = */ sobel, /* ddepth = */ opencv_core.cv_32f, /* dx = */ 1, /* dy = */ 1, /* ksize = */ 5, /* scale = */ 0.25, /* delta = */ 0.0, /* bordertype = */ opencv_core.border_replicate) it looks bad, highlighting points instead of contours: so doing wrong, or how gimp achieve such result , how can replicate in opencv? info image used https://www.pexels.com/photo/brown-wooden-flooring-hallway-176162/ ("free personal , commercial use"). solution tl;dr edge detection via sobel filter requires two separate filter operations. cannot done in single step . result of 2 separate steps has combined form final result of edge detection. info: i'm using float images (cv_32f) simplicity. solution in code: // load example image std::string path ...

c# - What is a NullReferenceException, and how do I fix it? -

i have code , when executes, throws nullreferenceexception , saying: object reference not set instance of object. what mean, , can fix error? what cause? bottom line you trying use null (or nothing in vb.net). means either set null , or never set @ all. like else, null gets passed around. if null in method "a", method "b" passed null to method "a". the rest of article goes more detail , shows mistakes many programmers make can lead nullreferenceexception . more specifically the runtime throwing nullreferenceexception always means same thing: trying use reference, , reference not initialized (or once initialized, no longer initialized). this means reference null , , cannot access members (such methods) through null reference. simplest case: string foo = null; foo.toupper(); this throw nullreferenceexception @ second line because can't call instance method toupper() on string reference pointing null ....

java - MultiThreaded collision detection Android -

i trying see if character collides of moving objects. in main java file have done multi threading moving objects. cant seem collision detection working on multiple threads, appreciated. seems detect collision on moving objects made , not once start moving

Using header files in C -

i'm trying learn use of header files in c. found few resources in research none of them created desired effect. first, according this tutorial, can write functions in header file itself. don't want that. want keep header file unchanged if changed code given interface remains unchanged. answer this question suggests 2 methods. first can write code , header file separately , include them when compile follows: gcc -o myprog test.c library.c but don't want either. library functions should readily available without needing include in compile line. according same answer, create library , link -l switch. when comes functions printf, don't need either of them. have include header files.is there way of doing that? summary tl;dr i want write library in c which: doesn't have implemented in header file itself. doesn't have included in compile line every time use library functions. doesn't have linked -l every time use library function. basical...

android - Gradle sais that the return statment of onStartCommmand is unreachable -

hey guys code of onstartfunction command in service public int onstartcommand(intent intent,int flags,int startid) { super.onstartcommand(intent,flags,startid); context context = getapplicationcontext(); for(;;) { long current = system.currenttimemillis(); usagestatsmanager usagestatsmanager = ((usagestatsmanager) context.getsystemservice(context.usage_stats_service)); (usagestats usagestats : usagestatsmanager.queryusagestats(usagestatsmanager.interval_daily, current - 1000, current)) { log.i("nome processo", usagestats.getpackagename()); } } return 0; } the problem when i'm compile because gradle says me return 0 "error:(56, 9) error: unreachable statement" you have loop no parameters. infinite loop. need way loop terminate or return statement never reached.

auto tab in C to HTML -

how can convert auto tabs in c code html, neat in html aligned. safe use 4spaces? times, 1tab not 4 spaces, 1,2, or 3 space only. pls help, thanks! int x ; /* comment tab */ x = 0u ; /* comment tab */ if ( gvar == 3u) /* comment tab */ { /* comment tab */ x++ ; /* comment tab */ } /* comment tab */ gvar = 99u ; /* comment tab */ return ( 0 ) /* comment tab */ well can't blithely convert every tab 4 spaces. that's not how tabs work. instead want each tab character advance output position next tab stop. you have 2 options: 1. specify css tab-size : pre { tab-size: 4; -o-tab-size: 4; -moz-tab-size: 4; } <pre> int main() { return 0; /* comment */ } </pre> this simplest solution, unfortunately the tab-size rule isn't recognized ie or edge . 2. pre-process source code: pipe c source code through expand command line utility ...

How do I setup the reset password function on Yii2? -

i have error: "the view file not exist: /var/www/html/myproject/frontend/views/common/mail/passwordresettoken-html.php" this code located @ frontend/models/passwordresetrequestform return yii::$app ->mailer ->compose( ['html' => '/common/mail/passwordresettoken-html', 'text' => '/common/mail/passwordresettoken-text'], ['user' => $user] ) ->setfrom([yii::$app->params['supportemail'] => yii::$app->name . ' robot']) ->setto($this->email) ->setsubject('password reset ' . yii::$app->name) ->send(); could have wrong path common mail try return yii::$app ->mailer ->compose( ['html' => '@common/mail/passwordresettoken-html', 'text' => '@common/mail/passwordresettoken-text'], ['user' => $user] ) ->setfrom([yii...

c - CUSE - return proper IOCTL for termios.tcgetattr() -

Image
i try use libfuse (cuse) create character device , play on regular tty, fine till use tcgetattr . unfortunately, termios.tcgetattr() raise i/o error . cusetest.c #define fuse_use_version 29 #define _file_offset_bits 64 #include <fuse/cuse_lowlevel.h> #include <fuse/fuse_opt.h> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> //#include <termios.h> #include <linux/termios.h> #include <unistd.h> #include <stdlib.h> #include <strings.h> #include <errno.h> #define log(...) { fprintf(stderr, "debug: "__va_args__); puts(""); } while (0) static void cusetest_open(fuse_req_t req, struct fuse_file_info *fi) { log("cusetest_open called\n"); fuse_reply_open(req, fi); } static void cusetest_read(fuse_req_t req, size_t size, off_t off, struct fuse_file_info *fi) { log("cusetest_read called\n"); ...

c++ - Counting number of occurrences in a range within an unordered_map -

i have unordered_map set as: unordered_map<int, deque<my_struct>> table; when read values program, do: table[int].push_back(obj); what want able if i'm given 2 integer variables, want able find number of keys occur between two. so if in table have code like table[49].push_back(obj); table[59].push_back(obj); table[60].push_back(obj); if execute search function(which i'm trying write) between key values of 45 , 65, should have 3 results. i'm not sure how go in efficient manner. ideas helpful. you. if using std::unordered_map don't think have choice loop on integers 45 65 , use find check if key exists in unordered_map : using my_table = std::unordered_map<int, std::deque<my_struct>>; int count(const my_table& table, int begin, int end) { int sum = 0; (int = begin; != end; ++i) { auto find_result = table.find(i); if (find_result != table.end()) sum++; } return sum; } but may no...

javascript - Whats the equivalent of ES6 methods(class) in es5? -

how polyfill es6 class methods es5? i reading book , says following: class ninja { constructor(name) { this.name = name; } swingsword() { return true; } } is same function ninja(name) { this.name = name; } ninja.prototype.swingsword = function() { return true; }; i asking why adding swingsword on prototype , not inside constructor function? because function should on object , not on prototype chain. am right or wrong? it should on prototype, methods not per-instance data. can't think of language implements way, whole idea of classes have whole class of objects have same set of methods. if put inside constructor function, unique function per instance made constructor. e.g, 1000 objects == 1000 functions, per "method".

ios - Inconsistency in Swift optional protocol behaviour -

coming .net, trying learn swift3/ios , got puzzled following apparent inconsistent behaviour of optional protocol members. suspect got juggling between objc/swift words, missing here actually? // in playground, given below: @objc protocol someptotocol { @objc optional func somemethod() } class somedelegate: nsobject, someptotocol { } class somecontroller: nsobject { var delegate: someptotocol = somedelegate() } // works , compiles without error let controller = somecontroller() controller.delegate.somemethod?() // no error, typed '(() -> ())?' // fails compile ?? let delegate = somedelegate() delegate.somemethod?() // error: 'somedelegate' has no member 'somemethod' i expect either both fail or both pass, if please enlighten me on anomaly. the difference between 2 blocks of code type of variable involved. in first block, delegate explicitly typed someptotocol , , protocol defines somemethod method, statement valid. ...

facebook chatbot - Wit.ai API converse doesn't respond with bookmarked action -

i feel must doing wrong in api. following weather example missing location. story works fine. however when use api on http using postman testing purposes cannot raise action after sending location user, returns stop message. think must not sending correct context across or similar. my understanding follows: send across message 'i want know weather' raises action wit: 'weather' (works correctly) respond 'missinglocation' wit replies msg 'which location want know weather for?' (works correctly) respond 'paris' in message (no context same session) wit replies finding entity 'paris' 'stop' , no action. here expect action request again need know time. happens when use story , test using bot messenger. any ideas anyone? expect need respond more 'paris' in message thanks. note: question asked "scruffjinks" on github before no answer https://github.com/wit-ai/wit/issues/301

Attempt to compare nil with number Error in Lua (Corona Lab) -

i'm new corona (lua). after running game, game seems work perfectly, until few seconds later when following error: 'attempt compare nil number' local function gameloop() -- create new asteroids createasteroid() -- remove asteroids have been drifted off screen = #asteroidstable, 1, -1 local thisasteroid = asteroidstable [i] if (thisasteroid.x < -100 or thisasteroid.x > display.contentwidth + 100 or thisasteroid.y < -100 or thisasteroid.y > display.contentheight + 100 ) display.remove( thisasteroid ) table.remove( asteroidstable) end end end as can see above, 'thisasteroid' in 'asteroidstable = {}' defined variable in top of module , outside of function. local asteroidstable = { } thanks help! either thisasteroid.x , thisasteroid.y , display.contentwidth or display.contentheight nil . use print(thisasteroid.x) etc find out 1 nil . you should line numbe...