Posts

Showing posts from January, 2012

sql - insert row into the table from values in two tables -

i want insert row in table. problem how values 2 different tables tables. itable has 3 columns ( studentphoto , studentname , studentid ) dtable has (studentphoto , studentid ) ltable have (studentname, studentid) i want insert data table itable table dtable , ltable . is possible , if yes, how? try insert itable (studentphoto , studentname , studentid) select d.studentphoto,l.studentname,d.studentid dtable d inner join l ltable on d.studentid= l.studentid

php - Hide columns if user want that -

this has super simpel solutions, can't wrap head around it. i have sql query: select traning.type_name,users.user_id, users.user_name,user_traning.min_puls, user_traning.medel_puls,user_traning.max_puls, user_traning.duration,user_traning.date, user_traning.view traning inner join user_traning on traning.tr_id=user_traning.tr_id inner join users on user_traning.user_id=users.user_id order `user_traning`.`date` desc i have colum in user_traning called view . the input form inputs either null or 2 . im thinking null means view input, , 2 user want hide input. i have been trying way: while($row = $users_traning->fetchobject()) { if($row->user_id == $_session['user_id'] && $row->view == null) { echo '<span class="glyphicon glyphicon-user"></span> <a href="userinfo.php='.$row->user_id.'">you </a> have ' .$row->type_n

How can I manipulate translation methods of cakephp 3 to become case insensitive? -

this part of src/locale/en_us/default.po file msgid "acg_id" msgstr "access control group identifier" msgid "acg_id" msgstr "access control group identifier" msgid "acg_id" msgstr "access control group identifier" my default.po file long. , think impossible write this. msgid "acg_id" msgid "acg_id" msgid "acg_id" msgstr "access control group identifier" how can implement function below in cakephp core function __($token){ $translation = translation(strtolower($token));//translation returns translation of token if exists else returns null return $translation ? $translation : $token; } then default.po file become shorter :) this msgid "acg_id" msgstr "access control group identifier" while think case insensitive translations kinda bad practice (why not use proper message ids?), can pre-declare of shorthand translation functions in a

jQuery .ajax() access to beforeSend local variable in javascript loop -

have jquery ajax call inside javascript cycle. here code: var number_of_ping_for_average = 4; var ping_start_time; for(i = 0; i++; < number_of_ping_for_average){ $.ajax({ type: 'get', url: "http://www.exmple.com/pkt.ext", timeout: 1000, cache: false, beforesend: function(){ ping_start_time[i][new date().gettime()]; }, success: function (data) { var ping_arrive_time = new date().gettime(); var ping_val = ping_arrive_time - ping_start_time[i]; }, error: function(data){ //timeout or 500 error //@todo fare funzionare tutto } }); } as see... need call variable "i" inside anonymous fun

xcode - How to embed a file in an objective-c project and extract it in running time? -

i have code written in objective-c os x. want create text file right after user runs program , save under documents folder. right stored text in string variable , on run time write in file. problem don't want have hardcode content of text file in code. is there way embed text file in project , when user runs application extract , store under path? p.s. using xcode. thanks. just add file project. in build phases add new copy files build phase , choose resources folder. in code use nsbundle

javascript - Stripe security issue -

i'm integrating stripe online store. can see code below, payment form inserted html values each form field. means user change price of field, , fraud. is secure? if not, how can add security measures? thanks! :) <form action="" method="post"> <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="deleted_for_demonstration" data-amount="2000" data-name="demo site" data-description="2 widgets ($20.00)" data-image="/128x128.png"> </script> </form> i assume using stripe.js in case wouldn't required use price in form. i try , change code flow below... for instance... user selects product id 123 via post request on product page. store have selected product in session. when checkout... use stripe js on card details on frontend exchange form card details token. post token server. th

node.js - Sails Hook route forbidden -

i try make installable hook make security verifications under hook.js set : routes : { before : { "/" : function (req, res, view) { ..... res.forbidden(); } } }, and have error if try send forbidden page user : error: sending 500 ("server error") response: typeerror: object #<serverresponse> has no method 'view' @ object.forbidden (/users/jaumard/documents/workspaceide/kikilib/api/responses/forbidden.js:56:19) @ serverresponse.bound [as forbidden] (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:729:21) @ isrouteallowed (/users/jaumard/documents/workspaceide/kikilib/api/hooks/acl.js:66:18) @ routetargetfnwrapper (/usr/local/lib/node_modules/sails/lib/router/bind.js:179:5) @ callbacks (/usr/local/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37) @ param (/usr/local/lib/node_modules/sails/node_modules/express/lib/

wordpress - Amazon Linux EC2 Instance Keeps Crashing -

it doesn't matter flavor of linux use. frustrating. need bottom of this. here link wp-config.php file: http://pastebin.com/jtzjdx8e here link error_log: http://pastebin.com/vgamvfca if problem gets solved, owe beer!

rails css How to place two button in a line -

i'm rails beginner. want make 2 button placed in line. how can put button correctly on line of table? two buttons: <%= button_to "empty cart", @cart, method: :delete %> <%= submit_tag "delete item" %> my view <%= form_tag destroy_multiple_carts_path, method: :delete %> <table class="table"> <tbody> <tr> <td class = "checkbox_size_sm"><input type="checkbox"></td> <td class = "image">item</td> <td class = "title"> </td> <td>price</td> </tr> <% @cart.line_items.order(created_at: :desc).each |item| %> <tr> <td><%= check_box_tag "item_ids[]", item.id %></td&

scala - Invoking curried function -

below implementation of curried function : scala> def multiply(x: int, y: int) = x * y multiply: (x: int, y: int)int scala> def multiplycurried = (multiply _).curried multiplycurried: int => (int => int) when attempt implement multiplycurried receive exception : <console>:10: error: missing parameter type multiplycurried(a => b => * b) what correct implementation invoke multiplycurried ? from wikipedia: currying technique of translating evaluation of function takes multiple arguments (or tuple of arguments) evaluating sequence of functions, each single argument (partial application) def multiply(x: int, y: int) = x * y //> multiply: (x: int, y: int)int def multiplycurried = (multiply _).curried //> multiplycurried: => int => (int => int) def multiplycurried2(x: int)(y: int) = x * y //> multiplycurried2: (x: int)(y: int)int def multiplycurried3(x:int) = (y:int) => x * y //> multiplycur

Swift and Ionic framework -

i want move app written on swift in ionic framework. best way achieve this? is there workaround write swift in visual studio? tools need set project up. p.s work on pc , prefer visual studio basically need re-write whole logic/code of application on javascript based framework , use ionic/angularjs frontend.

spring - Strange JAVA Syntax -

the following code used in spring - hibernate full java based configuration in many places (like here ): properties hibernateproperties() { return new properties() { { setproperty("hibernate.dialect", "org.hibernate.dialect.mysqldialect"); setproperty("hibernate.show_sql", "true"); setproperty("hibernate.format_sql", "true"); setproperty("use_sql_comments", "true"); setproperty("hibernate.hbm2ddl.auto", "none"); } }; } this method in class. think return object anonymous class object (please tell me if i'm wrong). curly brackets enclosing setproperty statements? array? if there should not semi-colons in there? i haven't been able find place syntax explained. please give link explained in detail. this method returns object of type propertie

Trying to compare tags in mongodb string array, with textbox input c# -

okay have mongodb has collection called videos , in videos have field called tags. want compare textbox input tags on videos in collection , return them gridview if tag matches input textbox. when create new video tags field string array possible store more 1 tag. trying in c#. hope of can thanks! code creating new video document. #region database connection var client = new mongoclient(); var server = client.getserver(); var db = server.getdatabase("database"); #endregion var videos = db.getcollection<video>("videos"); var name = txtvideoname.text; var location = txtvideolocation.text; var description = txtvideodescription.text; var user = txtvideousername.text; string[] lst = txtvideotags.text.split(new char[] { ',' }); var index = videos.count(); var id = 0; if (id <= index) { id += (int)index; }

git - How to see diff between working directory and staging index? -

Image
we can see difference between repository , working directory with: git diff we can see difference between repository , staging index with: git diff --staged but how see difference between working directory , staging index ? actually, git diff between index , working tree git diff head between repo , working tree. see 365git.tumblr.com post :

jquery - javascript replace string individual -

the example red color or black color if replace or string and using code var k = "red color or black color"; var s = k.replace("or","and"); alert(s); the result : red coland , black coland i want replace or .. if want replace insensitively, make use of regex , use ignorecase ( i ) flag use word-boundaries. string version replaces first occurrence , case-sensitive. if want replace "or" regardless of case, add g regex. var k = "red color or black color"; var s = k.replace(/\bor\b/gi,"and"); alert(s);

android - Cannot start an activity properly from a Listview with Search option -

i have created application supposed show listview searchbox , items user can click on , start new activity, or search specific 1 , same. right can search item , start activity supposed to, when click without searching, doesn't start properly. example clicking on first 10 items launches 1 same activity instead of 10 different ones. my code looks - public class itemmenu extends activity { private listview lv; arrayadapter<string> adapter; edittext inputsearch; arraylist<hashmap<string, string>> itemlist; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.item_menu); string items[] = {"item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7", "item 8", "item 9", "item 10", "item 11" etc... }; lv = (listview) findviewbyid(r.id.itemlistview);

apache - How to Fix Warnings in Hadoop Installation -

i'm trying install hadoop onto xubuntu pc. ubuntu 14.10 (gnu/linux 3.16.0-30-generic x86_64). installed hadoop 2.6 when go run n@dell:~$ start-dfs.sh 15/03/28 12:27:19 warn util.nativecodeloader: unable load native-hadoop library platform... using builtin-java classes applicable starting namenodes on [localhost] n@localhost's password: localhost: connection closed unknown na@localhost's password: localhost: starting datanode, logging /usr/local/hadoop/logs/hadoop-n-datanode-dell.out starting secondary namenodes [0.0.0.0] n@0.0.0.0's password: 0.0.0.0: starting secondarynamenode, logging /usr/local/hadoop/logs/hadoop-n-secondarynamenode-dell.out 15/03/28 12:30:23 warn util.nativecodeloader: unable load native-hadoop library platform... using builtin-java classes applicable i'm pretty sure should still run fine, don't having errors this. i've googled lot , haven't found solution works. i'm not using centos

VBA "Loop" within If Else statement -

can tell me why getting compile error: "loop without do" following code. sub burrito_log() dim j long j = 1 x = inputbox("how many burritos did have today?") cells(j, 2) = x cells(j, 1) = date j = j + 1 ans = msgbox("burrito log", vbyesno, "are done inputting?") if ans = vbyes 'do nothing else loop end if end sub after formating code error obvious. loop located before end if . move after end if .

javascript - jquery - append Icons generated by for loop into list items anchor -

i grateful guidance or solution! from array of class names, i'm generating icon sets using loop: // icon array var iconsarray = ['fa-search','fa-toggle-up','fa-link']; var iconsarraylength = iconsarray.length; // loop through array (var = 0; < iconsarraylength; i++) { // result console.log('<i class="fa' + ' ' + iconsarray[i] + '"></i>'); } i have navigation element. list has same number of items id: <nav> <ul id="nav"> <li><a href="">link 1</a></li> <li><a href="">link 2</a></li> <li><a href="">link 3</a></li> </ul> </nav> q. how append / prepend returned icon sets correct nav item? to clear, first array value intended first navigation item , on. i'm sure there's out there answer que

What is the way to manage UI messaging for PHP / jQuery -

i've been tasked setting user interface manage our success & error messaging our web application, has php/mysql backend. use lot of jquery on frontend. currently messages in php array descriptive name key , message value. echo them out jquery message popup plugin through json. we've echo'd array out json_encode var make messages accessible through js files. i contemplating throwing array db table columns like: 'id','editable'(boolean),'org_id'(int),'title'(varchar),'message'(varchar),'description'(varchar),'module_event'(varchar, value, maybe json), 'status'(bolean active/inactive) , create array there. the question: any packages exist? if not, please make suggestions based on info provided. thanks! i'd suggestions of existing solutions or best way manage situation. love automate of if possible. these success & error messages things along lines of "this record has been saved"

ios - iOS8.2 not playing custom alert sound from parse.com app -

i have set push notification app via parse.com. app installed on iphone 5s running ios8.2. app code in swift if send regular push notification, comes fine, plays short buzz (like 'quick' vibration or short standard 'note' text alert, rather have set standard text alert. (if send imessage, , have alert tone set 'chord', plays ok) if instead send dictionary version custom sound included in app bundle (yes, converted in terminal per apple instructions), still same above. cannot play custom alert sounds. it makes no difference if originate push app, or button on parse.com just other person said, ensure file in correct format (you want in .caf files) also, sure have entered correct file name when sending push notification if using client push. example parse docs: let data = [ "alert" : "the mets scored! game tied 1-1!", "badge" : "increment", "sounds" : "cheering.caf" //ensure file

for loop 1 to 1 in bash -

i have issue loop: for file in "$list" if [ ! -f "$file" ]; final_list="$final_list $file" fi done in $list stored file file1 file2 file3 , need check each word if exist file name. works if have in $list more 1 word. if $list containst 1 word don't work. variable $final_list empty. thank the problem double quotes. prevent word-splitting on $list, $file contains whole $list. but, condition checks non-existence, single file woudl failt condition, list 'file1 file2' , file of name doesn't exist, whole list assigned $final_list. try running script set -xv see what's going on.

c++ - What's the difference between & and && in a range-based for loop? -

i'm wondering what's difference between for (auto& : v) , for (auto&& : v) in range-based loop in code: #include <iostream> #include <vector> int main() { std::vector<int> v = {0, 1, 2, 3, 4, 5}; std::cout << "initial values: "; (auto : v) // prints initial values std::cout << << ' '; std::cout << '\n'; (auto : v) // doesn't modifies v because copy of each value std::cout << ++i << ' '; std::cout << '\n'; (auto& : v) // modifies v because reference std::cout << ++i << ' '; std::cout << '\n'; (auto&& : v) // modifies v because rvalue reference (am right?) std::cout << ++i << ' '; std::cout << '\n'; (const auto &i : v) // wouldn't compile without /**/ because const std::

java - Can you push synchronization costs onto one thread? -

i have 2 threads: primary thread main processing of application, , secondary thread receives data batches primary thread , processes , outputs them, either user, file, or on network. in general, data should processed @ faster rate produced. ensure main thread never waits secondary thread. secondary thread can accept amount of overhead, expanding buffers, redoing work, , on, sole objective of maximizing performance of main thread. ideally main thread never synchronize @ all. there way push synchronization costs onto 1 thread in java? this outline of solution: the main thread works in isolation time, piling data collection; when has generated nice batch, it: i. creates new collection itself; ii. sets filled-up collection aside, available picked reading thread; iii. cases collection atomicreference . the reading thread polls atomicreference updates; when notices has been set, picks batch, casing null shared reference, main thread knows can put collection in.

javascript - jQuery preventdefault submit form doesn't work when submitting form through js function? -

i have basic form: <form id="myform" name="myform" action="index.php" method="post"> <input type="submit" value="submit" /> </form> then jquery attach submit event: $( document ).ready(function() { var frm = $('#myform'); frm.submit(function (ev) { ev.preventdefault(); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { alert('ok'); } }); }); }); when press submit button works fine, alert 'ok'. but if change submit button actual button add onclick function through javascript, this: <input type="button" value="submit" onclick="submitf(this.form);" /> js: function submitf(form) { form.submit(); } my jquery event doesn't trigger, form su

css - How to align Nested HTML tables to the same height -

Image
i want align 2 nested table same height. placed inside of parent table. html: <table class="table table-condensed theme-font no-padding no-margin" cellpadding="0" cellspacing="0"> <tbody> <tr class="no-padding no-margin"> <td class="no-padding no-margin col-xs-6"> <table class="table table-condensed theme-font no-padding no-margin full-height border" cellpadding="0" cellspacing="0" rules="cols"> <thead> <tr> <th class="text-center border col-xs-4">particulars</th> <th class="text-center border col-xs-2">amount (dr.)</th> </tr> </thead> <tbody class="full-height">

sql - how to count multiple value in count function -

table id q1 q2 q3 q4 q5 ----------------------------------- 1 v.good fair fair ----------------------------------- 2 v.good fair fair i want answer this ---------------------- status q1 q2 q3 q4 q5 ---------------------- v.good 4 3 2 4 3 ---------------------- 4 5 6 7 8 ---------------------- fair 5 7 6 3 9 ---------------------- can 1 me in problem feel stuck thank in advance i assuming sample data incomplete expected output doesn't seem have of in terms of counts provided. if case guess @ interpreting want is: select 'v.good' status, sum(case when q1 = 'v.good' 1 end) q1, sum(case when q2 = 'v.good' 1 end) q2, sum(case when q3 = 'v.good' 1 end) q3, sum(case when q4 = 'v.good' 1 end) q4, sum(case when q5 = 'v.good' 1 end) q5 tbl union select 'good', sum(case when q1 = 'good' 1 end) q1, sum(case wh

IBM MobileFirst 6.3 :Failed to obtain JMX connection to access an MBean -

when tried deploy projects running on ibm mobilefirst 6.3 using jdk1.7 getting following error in mobilefirst server console in eclipse kepler sr2: [error ] failed obtain jmx connection access mbean. there might jmx configuration error: connection refused: connect [attention] no running mxbeans found and error message shown in mobilefirst console: fwlse3030e: runtime "myproject" not exist in worklight administration database. database may corrupted. everything working fine till error appears projects . tried create new project same error each time. tried delete mobilefirst development server , add again nothing changed. full log: application error srve0777e: exception émise par la classe d'application 'com.worklight.core.auth.impl.authenticationfilter.iswaitingforsynchronization:607' javax.servlet.servletexception: java.lang.runtimeexception: timeout while waiting management service start up.120 secs. at com.workl

fft - fortran complex to real fftw issue -

i working on project need implement fourier transform , inverse transform. testing program modified online example; print or write commands debugging purposes: program testit include 'fftw3.f' double complex out!, in real in parameter (n=100) dimension in(n), out(n) integer*8 p,p2 integer i,j real x real fact write(*,*)"stuff in data" open(unit=12, file="input.txt", action="write", status="replace") open(unit=20, file="dftoutput.txt", action="write", status="replace") x=0 in = 0 i=1,n/2 in(i)=1 enddo i=1,n write(*,"(f10.2,1x,f10.2)")in(i) write(12,*)real(in(i)) enddo write(*,*)"create plans" call dfftw_plan_dft_r2c_1d(p ,n,in,out,fftw_estimate) call dfftw_plan_dft_c2r_1d(p2,n,in,out,fftw_estimate) write(*,*)"do it" call dfftw_execute_dft_r2c(p,in,out) i=1,n write(*,"(f12.4,1x,f12.4)")out(i) write(20

drop down menu - Custom dropdown in android -

Image
i want build dropdown in android app looks below when not clicked: on clicking, should this: the user should able scroll dropdown list fling gesture (upward / downward) list should show 3 elements @ once. i have no idea called or how achieve this. pointers appreciated!! thanks!

oop - java interface and child class -

this question has answer here: is good/acceptable practice declare variable interface type? 5 answers what mean “program interface”? 30 answers i have next question. have interface public interface myinterface { blah blah } and have child: public class mychild implemets myinterface { blah blah } what difference between: mychild child = new mychild(); and myinterface child = new mychild(); ? your added code snippet - mychild child = new mychild(); and myinterface child = new mychild(); in first case child can contain object of mychild class. in second case child (where child myinterface ) can contain object of class implements myinterface . here can advantage of polymorphism.

python - The view didn't return an HttpResponse object. It returned None instead. Request Method: POST -

the problem appears when submit form. few days ago worked, changed nothing in code, fails. possible different module makes part of code crashed? traceback: environment: request method: post request url: http://127.0.0.1:8000/users/new/ django version: 1.7.3 python version: 3.4.0 installed applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mojblog', 'users') installed middleware: ('django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.common.commonmiddleware', 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', 'django.contrib.auth.middleware.sessionauthenticationmiddleware', 'django.contrib.messages.middleware.messagemiddleware', 'django.middleware.clickj

angularjs - How to provide delay in ng-controller -

as html page gets loaded, calls supercategorycontroller, assigning supercategories $scope variable. $scope.supercategories = supercategoryservice.getsupercategories(); but controller depends on service, in turn calls http request. @ time pf assignment http request not completed. $scope.supercategories getting assiged undefined. sampleapp.service('supercategoryservice', ['$http', function ($http){ var url = 'http://localhost/cgi-bin/supercategory.pl'; var supercategories; $http({ method: 'post', url: url, data: "action=get", headers: {'content-type': 'application/x-www-form-urlencoded'} }). success(function (data) { alert (data); if (data != null || data != 'undefined') { supercategories = data; } }) .error(function (error) { alert (error.message);

list - Haskell split tuple array where first elements are the same -

i have list in haskell of form similar to [([], "str1"), ([], "str2"), ([1], "ser1")] and want split separate lists of 2-tuples, first elements of each tuple same, so [([], "str1"), ([], "str2")] [([1], "ser1")] i''ve been eyeing data.list.split 's splitwhen function, i've been having trouble getting ghc accept predicate it, since gather wasn't meant that. i think can use groupby : > import data.list > import data.function > let xs = [([], "str1"), ([], "str2"), ([1], "ser1")] > groupby ((==) `on` fst) xs [[([],"str1"),([],"str2")], [([1],"ser1")]]

eclipse - Start a java project which uses Jargon Libraries -

we trying develop java application irods(a middleware heterogeneous databases). use jargon api need use java jargon api in link . using java first time , not aware of how import library in our project. in presentation following steps mentioned @ beginning git clone https://github.com/dice-unc/jargon.git mvn clean install -dmaven.test.skip=true but want expose libraries in new eclipse project. pointers regarding setting libraries exlipse project helpful. you asking quote of eclipse jdt docs. try give hint on matter. when have managed install maven , got build running, find jargon-xxx.jar in target folder. take jar file , place in eclipse project , select "configure build path" - "add jar". select jargon.jar file in project folder, on classpath in project. hint: if professional project, need have on team setup proper build environment you, possibly using maven or other tool manages dependencies , supported in ide. otherwise can perform ma

windows 8 - (C++/DirectX11) Something wrong in ID3D11DeviceContext::Draw() (or in my head) -

using directx sdk included windows8 sdk. compile success, program stops in 1 place. debugging showed error in function: //id3d11devicecontext* devicecontext //idxgiswapchain* swapchain //const float background[4] = {0.0f, 0.0f, 0.0f, 0.0f}; void drawscene(){ devicecontext->clearrendertargetview(rendertargetview, backgroung); devicecontext->draw(3, 0); //<-this swapchain->present(0, 0); } while commenting function goes ok. think have problems in functions: bool initscene(){ hr = d3dcompilefromfile(l"effects.fx", 0, 0, "vs", "vs_4_0", null, null, &vsbuffer, null); hr = d3dcompilefromfile(l"effects.fx", 0, 0, "ps", "ps_4_0", null, null, &psbuffer, null); hr = device->createvertexshader(vsbuffer->getbufferpointer(), vsbuffer->getbuffersize(), null, &vs); hr = device->createpixelshader(psbuffer->getbu

c# - How to add popupcontainer edit in the gridcontrol devexpress -

i developing application in wpf using mvvm design pattern. in 1 of user controls have gridcontrol (devexpress). gridcontrol bound datatable in viewmodel class . example columns of datatable begin date , end date ,value, comments. in column of comments want pop container appear in gridcontrol. possible that? first add following xaml namespaces xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" you can use gridcolumn.editsettings edit or view cell within editor following inside <dxg:gridcontrol> <dxg:gridcontrol.columns > <dxg:gridcolumn fieldname="begindate"> <dxg:gridcolumn.editsettings> <dxe:dateeditsettings/> </dxg:gridcolumn.editsettings> </dxg:gridcolumn> <dxg:gridcolumn fieldname="enddate"> <dxg:gridcolumn.editsettings> <dxe:dateeditsettings/>

Ternary operator on arrays in python -

i trying perform following operation on array in python: if true else b i trying perform on 1 channel of image. want check if value greater 255, if so, return 255 else return value being checked. here i'm trying: imfinal[:,:,1] = imfinal[:,:,1] if imfinal[:,:,1] <= 255 else 255 i following error: valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all() is there better way perform operation? use np.where : imfinal[:,:,1] = np.where(imfinal[:,:,1] <= 255, imfinal[:,:,1], 255) as why error see this: valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all() . essentially becomes ambiguous when compare arrays using and , or because if 1 value in array matches? compare arrays should use bitwise operators & , | , ~ and , or , not respectively. np.where uses boolean condition assign value in second param when true, else assigns 3rd param, see docs

javascript - Creating a filter in the view using AngularFire/Firebase query -

i building app in user inputs tastings, , tastings displayed in few places - on user's personal tastings page, , on "latest tastings" style page. on tastings page, when button clicked, "basictastings()" function called, , that's want query db , view update tastings have "type: basic" (thee type: advanced). in function, test console log outputting key() basic/advanced. i'm lost in pushing object scope objects go through ng-repeat. finally - make sense me doing way? approaching in manner instead of through, say, jquery .click() filtering idea because thought better approach if end large amounts of data in db. my data set as: { "tastings" : { "-jlucgqblssteob7weqi" : { "brewdate" : "2015-03-28t07:07:04.880z", "origin" : "panama", "overallrating" : 4.5, "roaster" : "verve", "roastname" : "los l

sockets - How do my browser knows it needs to connect to port 443 or port 80 -

this trying do open browser , start browse https website gmail or google.com i can see through wireshark name resolution being done dns server. but after that, connection directly established port 443 (starting tcp handshake) one thing not able understand is, how browser knows needs connect port 443, tried exploring dns packet, contains destination address, , there no info tells needs connect port 443. even if say, browser has priority in querying first time, sees if port 443 open connect or connect port 80, not able see such behavior if connect normal http website, in sense that, if go normal http website, there no traffic flow browser indicating had searched first port 443 , went port 80. i sure missing here, not sure is. the presence of https: in url tells that.

java - Reference to method is ambiguous when using lambdas and generics -

i getting error on following code, believe should not there... using jdk 8u40 compile code. public class ambiguous { public static void main(string[] args) { consumerintfunctiontest(data -> { arrays.sort(data); }, int[]::new); consumerintfunctiontest(arrays::sort, int[]::new); } private static <t> void consumerintfunctiontest(final consumer<t> consumer, final intfunction<t> generator) { } private static <t> void consumerintfunctiontest(final function<t, ?> consumer, final intfunction<t> generator) { } } the error following: error:(17, 9) java: reference consumerintfunctiontest ambiguous both method consumerintfunctiontest(java.util.function.consumer,java.util.function.intfunction) in net.tuis.ubench.ambiguous , method consumerintfunctiontest(java.util.function.function,java.util.function.intfunction) in net.tuis.ubench.ambiguous match the error occurs on following

node.js - Node, copy file from module to project -

i try create node module , make postinstall script (into package.json) copy js file current project : fs.copy(appdir + "/schedule.js", appdir + "/../../config/schedule.js", function (err) { if (err) { console.log(err); } else { fs.chmod(appdir + "/../../config/schedule.js", 0755, function (err, succ) { console.log(err, succ); }); console.log("done write schedule.js base config"); } }); the problem file correctly copy it's lock , can't edited... chmod doesn't return error. i'm under max os x node js 0.10.33 (ide intellij) found :) if module install : sudo npm install mymodule the file not editable if module install without sudo fine npm install mymodule

node.js - TypeError: Cannot call method 'then' of undefined -

i have following code executing inside controller in sailsjs. underlying adapter sails-orientdb. following error back typeerror: cannot call method 'then' of undefined why error occurring? user.query("select id user username='" + req.param("userid") + "'").then(function(userdata){ console.log(userdata); return userdata; }).fail(function (err) { console.log("handled"); }); to expand on @jaumard said. background usually it's recommend use standard waterline query methods such find() , update() , create() , destroy() , etc. these methods support callbacks , promises , these methods work same way against waterline adapter (orientdb, mysql, mongodb, etc). sometimes may want more complex not supported standard waterline methods , sails-orientdb extends waterline definition query() , among other methods . sails-orientdb .query() sails-orientdb query uses callback c

python - MongoEngine change database -

due project setup (same flasky ) , when run python tests ( line 34 ), connection development database created, before configuration set test (line 11 here ). results in problems tests, since meant run on clean db. looking online, found descriptions of switch_db not need. need either change database connection using, or drop connection , create new one. cant find way either of these.. missing ? connection initialized using line of code, inside init .py of main app directory. from mongoengine import connection db_name = 'name_from_config' connection(db_name) you should avoid creating connection mongoengine in way describe precisely reason. flasky using application factory approach allows application know connection config use when implementing data models. the best way integrate mongoenigne app flask-mongoengine should solve problem out-of-the-box.

Python optparse: parse.error()---->TypeError: error() missing 1 required positional argument: 'msg' -

i having trouble running trace route module on new python 3.4.3. on previous versions of python able run module yet unable to. keep receiving traceback error when try calling parser.error() function of optparse. typeerror: error() missing 1 required positional argument: 'msg'* here snippet of code if __name__ == "__main__": parser = optparse.optionparser(usage="%prog [options] hostname") parser.add_option("-p", "--port", dest="port", help="port use socket connection [default:%default]", default=33434, metavar="port") parser.add_option("-m", "--max-hops", dest="max_hops", help="max hops before giving [default: %default]", default=30, metavar="maxhops") (options, args) = parser.parse_args() if len(args) != 1: parser.error() else:

html - Email form .php script error -

i have script email form inside, have .php script supposed send inputs in form email. problem when submit form, error seen below: warning: mail(): failed connect mailserver @ "127.0.0.1" port 25, verify "smtp" , "smtp_port" setting in php.ini or use ini_set() in c:\program files (x86)\easyphp-devserver-14.1vc11\data\localweb\scripts\supformsend.php on line 16 html script: <form action="supformsend.php" method="post" id="contactforms"> <div id="namelabelform"> <label for="name">name:</label><br> <input type="text" id="nameinput" name="nameinput"/> </div> <div id="emaillabelform"> <label for="mail">e-mail:</label><br> <input type="email" id="mailinput" name="mailinput"/> </div> <d

c++ - Why is template overload a better match than a simple conversion? -

#include <iostream> using namespace std; template<typename t> void func(t t) { std::cout << "matched template\n"; } void func(long x) { std::cout << "matched long\n"; } int main() { func(0); } output: matched template in other cases, non-template function preferred when overload resolution might ambiguous, why 1 different? §13.3.3 [over.match.best]/p1-2: 1 define icsi(f) follows: (1.1) [inapplicable bullet omitted] (1.2) let icsi(f) denote implicit conversion sequence converts i-th argument in list type of i-th parameter of viable function f . 13.3.3.1 defines implicit conversion sequences , 13.3.3.2 defines means 1 implicit conversion sequence better conversion sequence or worse conversion sequence another. given these definitions, viable function f1 defined better function viable function f2 if arguments i , icsi(f1) not worse conversion sequence icsi(f2) , , then