Posts

Showing posts from May, 2011

html - How it possible in table td has different hights using one table -

Image
i want design table in html have different heights of td using 1 table. possible? if possible how can done? <table> <tbody> <td>height:30px</td> <td>height:90px</td> <td>height:60px</td> <td>height:80px</td> </tbody> </table> something table : <style> tr { height: auto; } td { overflow: hidden; display: inline-block; white-space: nowrap; vertical-align: top; background-color: #3399ff; height: 100%; width: 75px; border: 1px solid black; } td:nth-child(odd) { background-color: #1177dd; } #b { height: 200px; } #j { height: 90px; } #k { height: 180px; } </style> <table> <tbody> <tr> <td id="b">b</td> <td id="j">j</td> <td id="k">k</td> </tr> </tbody> </table>

php - lumen http error 500 in nginx and how to see error_log? -

my php project lumen ok on computer wamp (windows.apache.mysql.php) environment. but when upload server on lnmp (linux,nginx,mysql,php) environment, i enter url , came http error 500 the root /home/wwwroot/www.projectname.cn/projectname/public; so put test.php @ "/home/wwwroot/www.projectname.cn/projectname/public" enter www.projectname.cn/test.php it's right page. so change index.php <?php $app = require __dir__.'/../bootstrap/app.php'; dump($app); //$app->run(); also http error 500 and @ local environment , add route in projectname/app/http/routes.php <?php $app->get('/', function() use ($app) { return $app->welcome(); }); $app->get('/hello', function() { return "hello "; }); i enter “www.projectname.cn/hello” doesn't work the routes.php doesn't work what's maybe reason caused ?? you can see error log dynamically using command tail -f /var/log/n

c++14 - Customize the deleter to deallocate a 2D array through std::unique_ptr -

suppose parsing environment variable list given map<string, string> 2d memory held unique_ptr<char*[]> . however, not sure how can customise deleter 2d memory case ? // given: env (type of map<string, string>) // return: unique_ptr<char*[]> (with customized deleter) // prepare parsing environment c-style strings auto idx = size_t{0}; // should fill `ret` proper deleter won't give memory leak? auto ret = std::make_unique<char*[]>(env.size() + 1, ???); for(const auto& kvp : env) { auto entry = kvp.first + "=" + kvp.second; ret[idx] = new char[entry.size() + 1]; strncpy(ret[idx], entry.c_str(), entry.size() + 1); ++idx; } ret[idx] = nullptr; // later use of exec call return ret; apparently, above code leaks, because of new operator in inner loop. there no version of std::make_unique accepting deleter argument (by way, std::make_unique c++14, not c++11). try this: size_t size = env.size() + 1; auto ret

javascript - Customize Alfresco form, when workflow completed -

Image
we doing customizations alfresco workflow details page manipulating share-config.xml when workflow in progress, fields in workflow details displayed expected. but when workflow completes , not able view workflow details page customization , rendering default form. is there anyway can customize it, after workflow completes. any dom manipulation ways fine. sample code, trying <config evaluator="task-type" condition="icmrwf:submitartefacttask"> <forms> <form id="workflow-details"> <field-visibility> <show id="bpm:groupassignee" /> <show id="icmrwf:workgroup" /> <show id="bpm:sendemailnotifications" /> <show id="packageitems" /> </field-visibility> <appearance> <set id="&q

.net - Regex to exclude string at beginning of string -

i want exclude fixed string @ beginning, numbers after fixed string. the fixed string re163, here examples expected result: example result re16310000 10000 re16312345 12345 re16316300 16300 i've tried following regex: it works these examples: re16310000 10000 re16319999 19999 but doesn't fit that: re16320000 320000 (expected 20000) re16316320 320 (expected 16320) why regex ? substring enough: string source = "re16310000"; string result = source.substring(5); in case have use regular expressions can try (?<=re163)[0-9]+$ pattern; c# example: string pattern = @"(?<=re163)[0-9]+$"; string result = regex.match(source, pattern).value;

salt stack - SaltStack: Highstate top.sls files execution when merging strategy is "same" -

in /etc/salt/master have following options set: file_roots: base: - /srv/salt dev: - /srv/salt/dev and top_file_merging_strategy: same default_top: base i have top.sls base( /srv/salt/top.sls ) environment, goes: base: '*': - files where files.sls in defined in /srv/salt , 1 top.sls dev( /srv/salt/dev/top.sls ) environment, goes: dev: 'saltminion1': - django 'saltminion2': - mysql where django.sls , mysql.sls defined in /srv/salt/dev/ . if call: salt '*' state.highstate when using top_file_merging_strategy: merge , both base , dev environment getting applied minions, whereas scenario, using top_file_merging_strategy: same , base environment getting applied. according salt documentation: top file , both base dev environments should have gotten applied. what doing wrong? appreciated. i think experiencing this . it's been fixed in salt 2016.11.

How to show profile picture of user logged in asp.net mvc 5 using asp.net identity -

Image
i`m using asp.net identity , have added property profile image in application user class, when register new users add image url , show fine in page. so how can image profile icon of logged in users on navbar on picture:

javascript - How to extend js class from outside library in TypeScript / Using mojs in TypeScript -

i know how declare library ( example usage mojs): declare var mojs:any; but have problem extending it: class myobject extends mojs.customshape { getshape () { return '..path' } }; i error: type 'any' not constructor object type i tried this: declare var mojs:object{ customshape:any }; but no luck - wrong code. so how can extend js library class in typescript? ok, managed setting type objectconstructor my code mojs: declare var mojs: { customshape:objectconstructor, //here usage addshape:any, burst:any, timeline:any, shape:any, shapeswirl:any }; so objectconstructor can extend class without errors like: class myobject extends mojs.customshape { getshape () { return '..path' } };

performance - How to POST multiple large image files via Volley Android -

i trying post around 10 images via volley converting base64 volley post images multiple time due retry policy. compressing files , tried changing timeout problem still exist. retrofit doing same. why need/use base64? are using rather post? use multipart file upload large files, instance (with retrofit): public interface fileuploadservice { @multipart @post("/upload") void upload(@part("myfile") typedfile file, @part("description") string description, callback<string> cb); }

bash - Join and delete lines based on patern -

i have file 200,000+ lines. lines grouped. beginning of each group of rows starts "image" followed 1 row starts "histo" , @ least one, multiple, rows start "frag". need to: 1. delete row starts "histo". 2. each "frag" line need join previous "image" row. here example. >image ...data1... >histo numbers 0 0 1 1 0 1 0 >frag ...data1... >frag ...data2... >image ...data2... >histo numbers 0 0 1 1 0 1 0 >frag ...data1... >frag ...data2... >frag ...data3... >frag ...data4... the result needs this: >image ...data1... frag ...data1... >image ...data1... frag ...data2... >image ...data2... frag ...data1... >image ...data2... frag ...data2... >image ...data2... frag ...data3... >image ...data2... frag ...data4... it possible have many frag lines before starts on image line. using mac can use pretty tool. i tried combining multiple frag lines s

android - Execute Thread in every Viewpager item -

i have 2 images, in single viewpager item. when clicking on image display line, simple line. i growing line using thread, line percentage of vote given particular image, based on percentage lines drawn on both image after click but problem if click on 1 image single line drawn on particular image, , every other viewpager items no line drawn on click i want 2 lines after click on image, ivimageone.setonclicklistener(new view.onclicklistener() { @override public void onclick(final view v) { id = arraylist.get(position).get("user_id1"); feed_id = arraylist.get(position).get("feed_id"); log.e("feeeeeee", feed_id); view tempview = (view) v.gettag(r.integer.btnminusview); integer pos = (integer) v.gettag(r.integer.btnminuspos); ivrighttick = (imageview) tempview.findviewbyid(r.id.ivrighttick); ivlefttick = (imageview) tempview.findviewbyid(r.id.ivlefttick); ivlefttick.setvisi

html - floating a div into left -

Image
just want make div of list float left one just having hard time , wondering did go wrong there, did put wrong division or something my css .list_wrapper{ width:200px; background-color:red; display:block;} .list_wrapper2{ width:900px; background-color:blue; float:left; } my html <div class = "list_wrapper2" > <h3><?php echo $letter?></h3> <?php foreach($pages $page): ?> <div class = "list_wrapper" > <ul> <li class="listcss"> <a href="<?php echo base_url;?>/page.php?page=<?php echo e($page['slug']);?>"><?php echo e($page['label']);?></a> </li> </ul> </div> <?php endforeach; ?> <?php endfor; ?> </div> try display: inline-block instead of float: left . here example started. note: float wrap

php - How can I transfer a value from a page to another?without changing pages -

i'm trying build website 2 pages. page 1 in page theres buttom , everytime buttom clicked increases value of label on page 2. page 2 in page there 1 label value increased page 1 could give me example consider following link solution problem using ajax , jquery . http://tutorialzine.com/2009/09/simple-ajax-website-jquery/

domain driven design - Doubts on application structure and communication directions -

i'm building cqs-style ddd-application. i'm having doubts on how 'components' work each other. but first i'll give brief overview application's structure: applicationservice -> receives command objects -> doesn't return results -> acts on domain model -> speaks aggregate repository domain modifications queryservice -> bypasses domain model; doesn't speak aggregate repositories -> executes queries against database populate view -> returns 'representation' objects rest controller -> receives http requests , binds 'body content' & request params command objects -> delegates applicationservice post, put & delete requests -> returns @ least http code -> delegates queryservice requests infrastructure -> handles persistence db -> contains scheduling operations -> handles foreign domain events our domain model 'interested' in 'open host' -&g

security - Dcrypt a password without asking for master password -

so know there other posts regarding password storage , encryption question different. bare me end. i working on password manager website, fun. , wondering how secure idea had was. so each password user stores encrypted using aes-256 master password key , randomly generated salt. master password encrypted using bcrypt, before hand hashed 100,000 times using whirlpool, increase strain when trying login. if user decides doesn't want enter password every time he/she requests password site program cannot decrypt password , autofill because master password required decrypt stored passwords. one idea had store password in users current session, that's not idea because trying make assuming attacker has breached server , downloading database , snooping around. another though use 100,000 time hashed password key aes-256 encryption , store hash in session. that's better storing in plain text, still lets attacker able decrypt stored passwords if he/she can information ses

pdo - About fwrite in php -

i creating file in php using fwrite . need attach database index.php doubt can print below line on fwrite ? have tried shows error. there way this? $fd =fopen("database.php","w"); fwrite($fd, "$dbhost='localhost'; $dbuser='$user'; $dbpass='$pass'; $dbname='$email'; $dbh = new pdo('mysql:host=localhost;dbname=$email', $dbuser, $dbpass);"); fclose($fd); it's showing errors because variables aren't escaped. fix issue, either swap out quote markes single quote marks or add backslash () infront of $. $fd=fopen("database.php","w"); fwrite($fd,"\$dbhost='localhost'; \$dbuser='\$user'; \$dbpass='\$pass'; \$dbname='\$email'; \$dbh=newpdo('mysql:host=localhost;dbname=\$email',\$dbuser,\$dbpass);"); fclose($fd); or quote mark fix: fwrite($fd, '$dbhost="localhost"; $dbuser="$user"; $dbp

ruby - Rails app can't upload files that use gem jquery_mobile_rails -

gemfile: gem 'jquery-rails' gem 'jquery_mobile_rails' application.js: //= require jquery.mobile html: <form accept-charset="utf-8" action="/home/test" enctype="multipart/form-data" method="post"> <br> <div class="ui-input-text ui-body-inherit ui-corner-all ui-shadow-inset"> <input id="test" name="test" type="file"> </div> <div class="ui-btn ui-input-btn ui-corner-all ui-shadow"> <input type="submit"> </div> </form> controller: class homecontroller < applicationcontroller skip_before_filter :verify_authenticity_token, only: [:test] def index end def test binding.pry end end after current selection file submitted, no params[:test] in params. when rid of "//= require jquery.mobile",params[:test] in params. not know have not encountered, how solve?

javascript - Passing an array to a function and pushing values to it using AngularJS -

i trying populate arrays dynamically local storage sqlite database tables when controller loaded. i have several arrays defined follows (small sample shown): $scope.myarray1 = []; $scope.myarray2 = []; i create array table name/array name associateion e.g. my_table_1 should queried , written $scope.myarray1 . looks below (small sample shown): $scope.tablearrayassociation = [{ tablename: "my_table_1", arrayname: "myarray1" }, { tablename: "my_table_1", arrayname: "myarray2" }]; to have function calls sqlite local storage database table , reads values it.for function pass table name query , array write data function parameters. i can query required table no problem passed parameter, when try , insert array error. below said function. ondeviceready function ondeviceready() { querylocalstoragetablesandbuildarrays($scope.tablearrayassociation); } loop through each item, query table , push array. function qu

java - Mapper code generation -

there many mapper tools available pojo , dto. check link: any tool java object object mapping? there tool generates dao, service classes automatically? dozer sample: <mapping> <class-a>yourpackage.sourceclassname</class-a> <class-b>yourpackage.destinationclassname</class-b> <field> <a>yoursourcefieldname</a> <b>yourdestinationfieldname</b> </field> </mapping> sourceclassname sourceobject = ... mapper mapper = new dozerbeanmapper(); destinationobject destobject = mapper.map(sourceobject, destinationclassname.class); asserttrue(destobject.getyourdestinationfieldname().equals(sourceobject.getyoursourcefieldname)); here xml configuration fine, can skip code part , specify pojo-dto configuration or pojo-dto along-with filter configuration. , tool should able automatically generate intermediate translation code in form of dao , service classes. there such tools available?

can't get custom Dimension Value Google Analytics Android -

i'm using code setting custom dimension tracker.send(new hitbuilders.screenviewbuilder() .set("&cd", "home screen") .build() ); also tried : mtracker.send(new hitbuilders.screenviewbuilder() .set("&cd1", "premiumuser") .build() ); and getting value : mtracker.get("&cd1"); but nothing work ,i have no idea how current set value dimension. used alot of resources nothing works. followed steps setting custom dimensions in account. ideas? your code sets custom dimension single hit , reads tracker object. that's reason reads don't work. assuming want add "premiumuser" custom dimension subsequent hits, , dimension index 1, code should follows: mtracker.set("&cd1", "premiumuser"); then should able read tracker object: mtracker.get("&cd1"); you can find documentation tracker here

javascript - How to destroy a Panel in extjs -

i have border layout in west side have few buttons. on click of buttons few panels show in central panel. here example code of 1 panel display in central panel. { xtype: 'mypanel', // user define panel itemid: 'mypanel1', showzoom: false, showlegends:false, showslider: false, showdatagrid: true, charttype: 'line', controlpanel:false, orientation: 'x' } now have 1 buton called setting open 1 window. window having checkboxes. in have 1 checkbox called legends. want when click on checkbox legends above panel showlegends : true.when showlegends true create legendpanel , on false want destroy panel. showlegends:true if (me.showlegends) { legendpanel = ext.create('igo.panel.legendspanel', { itemid: graphconfig.itemid + 'legends', graphid: graphconfig.itemid }); } cpanel.add(gpanel); how can destroy panel when showlegends false.please answering this!! hope helps, ex

javascript - D3 Treemap headers -

Image
i'm trying add headers @ top of each rectangle have name of parent in them. i'm trying follow example https://bl.ocks.org/deenar/336efdeb97f1c79d4a6b don't understand i'm still new d3. currently i've added following add header doesn't seem show anything: var header = nodes.filter(function(d) { return !d.children; }); var headercells = svg.selectall("g.cell.header") .data(header, function(d) { console.log("gf"+name); return d.name; }); var headerentertransition = headercells.enter() .append("g") .attr("class", "cell header") .on("click", function(d) { zoom(d); }); headerentertransition.append("rect") .attr("width", function(d) { return math.max(0.01, d.dx); }) .attr("height", headerheight) .style("fill", "red"); headerentertransition.append('foreignob

detect Shake in android -

i trying hit api when user shake device 10 times. have tried many git simple , stack overflow solution non of them can solve problem. of git library working detecting shake before 10 times or after 10 times. i have tried library and this library. please give me valuable solution. by using sensorlistener please check ticked answer... you have adjust shake_threshold value achieve this how detect shake event android? thank you!

javascript - Remove iframe and prevent conflicts with libraries -

we have application make carrusel images , using iframe insert in web pages. we want remove iframe, , have ready work 1 div, our users insert in pages: <script src="https://www.example.com/mycustom-carrusel.min.js"></script> <div id="custom-unique-id" style="width:100%;height:300px;"></div> the mycustom-carrusel.min.js has our code minified gulp. our javascript call our api , paint necessary inside div, problem using libraries, jquery , others. we want prevent conflict example jquery or whatever other library conflict web page of user. what best technology implement , prevent possible conflict our code? thanks! isolation of styles , scripts page widget embedded why iframe typically used. keep using iframe . in future (once implemented in popular browsers), instead of iframe , use all css property value of unset , initial , or revert , reset inherited styles widget element , nested elements , safely ap

android - enqueue multiple GET request when using nested retrofit 2.0 -

i using retrofit 2.0 make api calls nesting multiple requests. api's works fine individually. when nested retrofit, first request execute after when register second request it's not callback in enqueue method (i.e. it's directly returning null without inserting enqueue's inner methods onresponse , onfailure ) my code :- public class main2activity extends appcompatactivity { gson gson; jsonobject jsonresult=null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main2); toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); gson=new gsonbuilder().create(); firstrequest(); //-- first retrofit request } private void firstrequest() { retrofit retrofit=new retrofit.builder().baseurl(getresources().getstring(r.string.api_url)).addconverterfactory(gsonconverterfactory.cre

html - Set div width and resize when it doesn't fit on the screen for absolute positioned div -

Image
i trying set fixed width div, example 200px. want div have 200px, except when current window has not enough space it. div { border: 2px solid; } .fixedwidth { width: 200px; position: absolute; } .nowidth { position: absolute; } <div class="fixedwidth"> lalala lala lalala lalala </div> <br /> <br /> <div class="nowidth"> alala lala alal lala </div> then following problem can seen when screen gets smaller: the first div not resize , text falls outside screen. i noticed, behaviour trying achieve max-width normal div, doesn't work absolute positioned divs. since normal divs possible without media queries, searching solution without media queries, not sure if possible. you should able following: .fixedwidth { max-width:200px; width: 100%; } this mean 200px until screen not large enough

javascript - How to create jquery Jtable dynamically -

i have dynamically create jquery jtable based on columns selected user. till have done hardcoding column names , firing ajax data displayed in jtable. how create dynamically ? here js sample code. <script type="text/javascript"> $(document).ready(function () { $('#studenttablecontainer').jtable({ title: 'the student list', paging: true, //enable paging pagesize: 10, //set page size (default: 10) sorting: true, //enable sorting defaultsorting: 'name asc', //set default sortin fields: { studentid: { key: true, create: false, edit: false, list: false }, name: { title: 'name', width: '23%' }, emailaddress: { title: 'email address', list: false }, } });

python - Use Flask to convert a Pandas dataframe to CSV and serve a download -

i have pandas dataframe in flask app want return csv file. return response(df.to_csv()) the problem output appears in browser instead of downloading separate file. how can change that? i tried following gave empty output. response = make_response(df.to_csv()) response.headers['content-type'] = 'text/csv' return response(response) set content-disposition tell browser download file instead of showing content on page. resp = make_response(df.to_csv()) resp.headers["content-disposition"] = "attachment; filename=export.csv" resp.headers["content-type"] = "text/csv" return resp

Android volley - avoid multiple requests of the same kind to the server? -

i using volley upload list of images server. happens within service. once image uploaded remove list. problem arises when internet connection breaks. when internet connection breaks , comes again thinking of adding images yet uploaded request queue. this can result in more 1 copy of same image saved on server request same image might have gone through before getting rseponse. how can address scenario? i'm not quite sure why you're using service schedule requests volley automatically runs it's request in seperate thread. nevertheless can listen both request results, successful , unsuccessful adding listeners. you can remove image list schedule request using volley. if succeeds can carry on desired, if fails can add again list. public static request getimageuploadrequest(final string image) { response.listener<t> responselistener = new response.listener<t>() { @override public void onresponse(t response

c - How can I reverse the letters in each word of a string -

how can reverse words of string characters , numbers. example: this start! siht si eht trats! i've written code reverses (also '!'); output is: siht si eht !trats code: #include<stdio.h> void reverse(char *begin, char *end); void reversewords(char *s) { char *word_begin = s; char *temp = s; while(isalnum(*temp) || *temp ) { temp++; if (*temp == '\0') { reverse(word_begin, temp-1); } else if(*temp == ' ') { reverse(word_begin, temp-1); word_begin = temp+1; } } } void reverse(char *begin, char *end) { char temp; while (begin < end) { temp = *begin; *begin++ = *end; *end-- = temp; } } int main() { char s[50]; scanf("%[^\n]",&s); char *temp = s; reversewords(s); printf("%s", s); getchar(

javascript - Use json_encode() with a foreach loop -

i have following code allows me echo product categories in wordpress withing select box: $arguments = array( 'number' => $number, 'orderby' => $orderby, 'order' => $order, 'hide_empty' => $hide_empty, 'include' => $ids ); $product_cats = get_terms( 'product_cat', $arguments ); foreach ( $product_cats $cat ) : echo '<option value="' . $cat->term_id . '">' . $cat->name . '</option>'; endforeach; i trying use returned values foreach loop within json_encode() can use categories in javascript code. but cannot figure out way it, can provide guidance? if use <?php echo json_encode($product_cats); ?> it not work try in javascript tag; <script type="text/javascript"> var mycatjson = json.parse('<?php echo json_encode($product_cats); ?>

javascript - TypeHeadBootStrap does not work -

i have json has following structure: [{"id":1,"nome":"teste"},{"id":2,"nome":"teste"},{"id":3,"nome":"teste3"}] i want use head type code not load, in browser console shows loaded json correctly. $('#nome').typeahead({ source: function(query, process) { objects = []; map = {}; console.log(data); $.each(data, function(i, object) { map[object.label] = object; objects.push(object.label); }); process(objects); }, updater: function(item) { console.log(map[item].id); //$('hiddeninputelement').val(map[item].id); return item; } }); i using lib: https://github.com/bassjobsen/bootstrap-3-typeahead resolved changed library https://github.com/biggora/bootstrap-ajax-typeahead

git - Why it seems that I have all my commit in the same branch also if I created a new one and commit into this new branch? -

i new in git , have following doubt branches. i have used following command create new branch named easy-mode : git branch easy-mode then see al branches , output: andrea@andrea-pc mingw64 ~/documents/ws_vari/version-control/asteroids (easy-mod e) $ git branch * easy-mode master so should means easy-mode branch correctly created , in moment active branch. true? ok, have modified file named game.js , have added staging area , have committed it. expect commit related easy-mode branch active branch. the problem trying show commit graph obtain these result: andrea@andrea-pc mingw64 ~/documents/ws_vari/version-control/asteroids (easy-mod e) $ git log --graph master easy-mode * commit 59b4bce5964825b7c6fec4270ba34d2166f5168e | author: andrea nobili <nobili.andrea@gmail.com> | date: thu jul 28 13:17:01 2016 +0200 | | make asteroids split 2 smaller pieces instead of 3 | * commit cba1887f66a579e81c70a607d8402e84fa6e966d | author: andrea nobili <nobili.and

Do I ought to follow naming conventions for Java packages? -

i learning java , have found naming conventions used in tutorials on oracle's website , com.etc.project.program do have follow convention? and pros , cons of following or not following it? conventions not mandatory you create bettter code , others understand easier: according wikipedia : reasons using naming convention (as opposed allowing programmers choose character sequence) include following: to reduce effort needed read , understand source code to enable code reviews focus on more important issues arguing on syntax , naming standards. to enable code quality review tools focus reporting on significant issues other syntax , style preferences. to enhance source code appearance (for example, disallowing overlong names or unclear abbreviations).

c# - Can I use Generics to get the property of a passed struct? -

i trying use generics pass in struct function , have function access properties. want utilize generics more because supposed "safe , efficient". here's code looks like. class class foo { struct { int a; int b } struct b { int a; int b; } } generic function void bar<t> (t input) { var = input.a; //this says know nothing } function call bar<foo.a> (aobj); can generics used this?(that access object's data members...) or can create over-loaded method? parts of objects trying access function common both types, that's why thought use generics. using generics not imply can use duck typing. c# statically typed language, need following: first, define interface defines common interface of a , b : interface ihasab { int { get; } int b { get; } } then, have struct s implement interface: struct : ihasab { public a(int a, int b) { = a; b = b;

java - Finding all possible subset sum which is equal to 0 out of set of positive and negative numbers? -

this question has answer here: given set of n integers, return subsets of k elements sum 0 3 answers you have array has set of positive , negative numbers, print subset sum equal 0. i can think of approach can cam make powersets of givcen array , check if sum 0. not llok optimized solution me. after reading looks bit similar problem on net , looks can solved dynamic programming below program find if there combination exist make sum 11 example ? public boolean subsetsum(int input[], int total) { boolean t[][] = new boolean[input.length + 1][total + 1]; (int = 0; <= input.length; i++) { t[i][0] = true; } (int = 1; <= input.length; i++) { (int j = 1; j <= total; j++) { if (j - input[i - 1] >= 0) { t[i][j] = t[i - 1][j] || t[i - 1][j - input[i - 1]];

c# - Route attributes not registering my controller method -

Image
i trying register new route handles login functionality same way did other routes. other routes worked login 1 not. here route attribute working routes : // post api/user/adduser [httppost] [route("api/user/adduser")] public ihttpactionresult adduser([frombody]user user) { blah blah } here code login method: // post api/user/login [httppost] [route("api/user/login")] public ihttpactionresult login(string email, string password) { blah blah } and here webapiconfig.cs: // web api routes config.maphttpattributeroutes(); config.routes.maphttproute( name: "userrouteapi", routetemplate: "api/user/{method}" ); this http response when try access login api -> output on browser: i don't it, created route same way did previously. tried restarting visual studio, iis express, pretty sure route template correct. i need desperate here!

Bash. infinite loop showing a counter and more info -

i have script generates dinamically bash script. in heredoc script there infinite loop showing counter (this works!): date1=`date +%s` while true; echo -ne "$(date -u --date @$((`date +%s` - $date1)) +%h:%m:%s)\r"; done this loop working fine if put this. problem need show not counter. more info needed (some static data). i'll put not working code: #!/bin/bash dir="/tmp/" my_file="generatedscript.sh" rm -rf "$dir$my_file" > /dev/null 2>&1 exec 3>"$dir$my_file" cat >&3 <<-'eof' #!/bin/bash date1=`date +%s` while true; echo -ne "info\n" # damned line, if remove counter works fine echo -ne "time counter: $(date -u --date @$((`date +%s` - $date1)) +%h:%m:%s)\r"; done eof exec 3>&- xterm -hold -geometry 78x25+0+0 -t "testing" -e "bash \"$dir$my_file\"" > /dev/null 2>&1 & this shows

linux - scripting in jenkins for deployment -

i have jenkins installed on windows server, configured git. using deploy container plugin deploy build remote hosts. instead of deploying using plugin, want write shell script deploy war in post build action. remote machine linux machine (centos). gone through link run batch scripts on remote server (windows) jenkins not great help. appreciated. thanks

send text containt of the webpage instead of url in android webview app -

i have android webview app , have added share action in it, shares url of current page of webview. want send text content of page instead of url. please me share intent. following code share intent. case r.id.menu_item_share: { intent shareintent = new intent(intent.action_send); shareintent.settype("text/plain"); shareintent.putextra(intent.extra_text, mywebview.geturl()); startactivity(intent.createchooser(shareintent, "share website!")); shareintent.setpackage("com.whatsapp"); break; //or, return true; if need content of web page, please try this. url url = new url("http://www.google.com/"); urlconnection con = url.openconnection(); pattern p = pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*"); matcher m = p.matcher(con.getcontenttype()); string charset = m.matches() ? m.group(1) : "iso-8859-1"; reader r =

android - Avoid deleting children objects - Realm -

i have following scenario: one dose has 1 or more nutrients , when dose deleted nutrients stay in database. there annotation allows that? thank in advance! if delete dose object, links invalidated, nutrient classes belong stay in database when call dose.deletefromrealm() . so that's default use-case.

ios - adding a border around SceneKit node -

i trying highlight selected node in scenekit tap gesture. unfortunately, have not been able accomplish it. best thing change material when node tapped. let material = key.geometry!.firstmaterial! material.emission.contents = uicolor.blackcolor() can suggest way can go add border or outline around object instead of changing color of entire node? scnnode conforms scnboundingvolume protocol. this protocol defines getboundingboxmin:max: method. use minimum , maximum coordinates of bounding box of geometry attached node. then use scenekit primitive type scngeometryprimitivetypeline draw lines of bounding box. check scngeometryelement.

Rails: Can't get mailer to work when I set credentials as environment variables -

i setting contact form in rails 4 app, send emails using gmail. first, got work these settings in config/environments/development.rb: config.action_mailer.delivery_method = :smtp config.action_mailer.raise_delivery_errors = true config.action_mailer.smtp_settings = { address: 'smtp.gmail.com', port: 587, domain: 'gmail.com', user_name: 'myusername@gmail.com', password: 'mypassword', authentication: 'plain', enable_starttls_auto: true } then used this approach setting environment variables in config/environment_variables.yml , loading config/initializers/environment_varibles.rb, , changed smtp settings in config/environments/development.rb to: config.action_mailer.delivery_method = :smtp config.action_mailer.raise_delivery_errors = true config.action_mailer.smtp_settings = { address: 'smtp.gmail.com', port: 587,

FInding duplicate value in PHP array -

this question has answer here: how remove duplicate values multi-dimensional array in php 15 answers [0] => array ( [id] => 9 [order_address_id] => 9 [created] => 2015-12-17 12:24:20 [order_status] => dispatched [total_discount] => [total_shipping_charge] => 60 [s_state] => ny [b_state] => ny [order_id] => 9 [p_name] => product 1 [qty] => 1 [price] => 475 ) [1] => array ( [id] => 9 [order_address_id] => 9 [created] => 2015-12-17 12:24:20 [order_status] => dispatched [total_discount] => [total_shipping_charge] => 60 [s_state] => ma [b_st

python - cx_Freeze: shortcutDir gives error -

Image
i'm creating single file exe form python program. i'm using cx_freeze. works perfect except 1 little agnoying thing. when install program installs should do, including shortcut on desktop. but...when want start program shortcut on desktop following error: when try run program within program folder works. when manually create shortcut desktop works aswell. does know why why shortcut, installed @ installation of program doesn't work? my cx_freeze setup.py import cx_freeze import sys executables = [cx_freeze.executable("tennis_calculator.py", base="win32gui", icon="tennis_ball.ico", shortcutname="tpc", shortcutdir="desktopfolder")] build_exe_options = {"icon": "tennis_ball.ico","packages":["tkinter", "csv", "ttk"], "include_files":["tennis_ball.ico", "testtennis.csv"]} build_msi_options = {"include_files":&

C++ Should I check whether a file exists before deleting it? -

quite simply, want delete file may or may not exist. bad practice use remove(filename) , ignore return value? edit: remove, i'm referring this should check whether file exists before deleting it? there no such requirement or need, , doing in no way useful. and ignore return value? usually, user may want know whether file deleted or not, bad idea ignore return value. further, user wants know why file not deleted (see std::perror ).

c# - How to get a value of a session key value pair in Session_OnEnd() method -

i have added value of order using session.add("order",1) in session when user logs out can unlock order locked when user accessing it. there other way fire database query when user logs out ? please help. you have code in session_end method, only under following condition: the session_onend event supported when session-state httpsessionstate.mode property value inproc, default. if session-state mode set stateserver or sqlserver, session_onend event in global.asax file ignored. if session state mode property value custom, support session_onend event determined custom session-state store provider. if using sqlserver or stateserver session management - can implement httpmodule. see following reference: http://www.codeproject.com/articles/21156/asp-net-httpmodule-for-handling-session-end-with-s http://www.ivan-nikolov.com/en/article/5/asp-net-session-state-mode-and-session-end-callback

node.js - Make dynamic path in node and express js -

i trying make route dynamic /review-{title}-{id} , causing error don't know why, if user enter wrong params how handle that. client requirement above, not in node , express please suggested how make routes above. if needed make route /review/:title/:id format how can make that. i trying redirect me out 404 page, please find existing code details inside, server.js this working.. app.get('/review', (req, res) => { res.sendfile(path.resolve(__dirname, '../client/review.html')); }); not one.. app.get('/review-*-*', (req, res) => { res.sendfile(path.resolve(__dirname, '../client/review.html')); }); not 1 working app.get('/review/*/*', (req, res) => { res.sendfile(path.resolve(__dirname, '../client/review.html')); }); 404 page call evrytime while accessing dynamic pages app.get('/*', (req, res) => { res.sendfile(path.resolve(__dirname, '../client/404.html')); }); check out syntax ro

sqlalchemy - Filter results by count of items in relationship -

let's have these 2 models : def client(db.model): id = db.column(db.integer, primary_key=true) invoices = db.relationship('invoice', backref='client') def invoice(db.model): id = db.column(db.integer, primary_key=true) i'd retrieve client @ least 1 invoice , less 20 invoice . expecting work : client.query.join(invoice).filter(and_(invoice.count() > 1, invoice.count() <= 20)) or nice : client.query.join(invoice).filter(and_(count_(invoice) > 1, count_(invoice) <= 20)) but of course, can't simple. .count() can't work there , can't find count_() in sqlalchemy.func . thanks coworkers , code lying around, got working: client = client.query\ .outerjoin(client.invoices)\ .group_by(client)\ .having(\ func.and_(\ func.count_(client.invoices) >= 1)\ func.count_(client.invoices) <= 20)\ ) ).all() i hop

c# - Copy a Nullable property to a non-Nullable version using Reflection -

i writing code transform 1 object using reflection... it's in progress think boil down following trust both properties have same type: private void copypropertyvalue(object source, string sourcepropertyname, object target, string targetpropertyname) { propertyinfo sourceproperty = source.gettype().getproperty(sourcepropertyname); propertyinfo targetproperty = target.gettype().getproperty(targetpropertyname); targetproperty.setvalue(target, sourceproperty.getvalue(source)); } however have additional issue source type might nullable , target type not. e.g nullable<int> => int . in case need make sure still works , sensible behaviour performed e.g. nop or set default value type. what might like? given getvalue returns boxed representation, null reference null value of nullable type, it's easy detect , handle want: private void copypropertyvalue( object source, string sourcepropertyname, object targ

php - How to display data from code igniter model with AJAX request -

Image
my codeigniter site has side panel , when click or select options in side panel appropriate content appear main panel. home page url http://localhost/main/userinfo/allusers when click female button url http://localhost/main/userinfo/female have following output when made ajax request. did mistake? controller(main.php) class main extends ci_controller { public function __construct() { parent::__construct(); $this->load->model('userinfo_model'); } public function index() {} public function userinfo($gender) { $this->load->view('home/inc/header_view'); $usermain_data['user_info'] = $this->userinfo_model->get_data($gender); $this->load->view('home/main_view', $usermain_data); } model(userinfo_model.php) class userinfo_model extends ci_model { function __construct() { // call model constructor parent::__construct(); } function get_data($gender) { $this-&g