Posts

Showing posts from May, 2012

ruby on rails - Using a frozen constant as a hash key? -

i built small api makes few calls have similar payloads, have base payload merge in call-specific elements, so: def foo_call base_payload.merge({"request.id" => request_id}) end def biz_call base_payload.merge({"request.id" => some_other_thing}) end def base_payload { bar: bar, baz: baz, "request.id" => default_id } end my coworker suggested make "request.id" frozen constant, arguing making constant means can freeze means wont allocating new string object on each call, saving bit of memory. this: requestid = "request.id".freeze def foo_call base_payload.merge({requestid => request_id}) end def biz_call base_payload.merge({requestid => some_other_thing}) end def base_payload { bar: bar, baz: baz, requestid => default_id } end i'm little apprehensive, can't quite pin down reason why not (other latent resistance @ having new commit :> ). feel might cause

With a simple http server in node.js, how to find out why it's crashed? -

i running basic http server serve static files in node.js express : var setting = require('../setting') var express = require('express'), app = express(), port = setting.http.port; app.use(express.static(__dirname + '/' + setting.http.static_dir)); app.listen(port); i know can use forever restart server if it's dead reason. but, there way log when server crashed can know reason why it's crashed , when it's crashed? with forever : forever -o out.log -e err.log my-script.js see this answer more details . if want log express server errors, use error handler generated express cli tool: server.on('error', onerror); /** * event listener http server "error" event. */ function onerror(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'pipe ' + port : 'port ' + port; // handle specific listen errors friendly m

virtualbox - Getting timeout on vagrant up -

today have started learning vagrant. creating first, base virtual machine ( hashicorp/precise32) went pretty smooth. wanted test box, time :puppetlabs/ubuntu-14.04-32-puppet. im getting msg : default: warning: connection timeout. retrying... have read might because of disabled virtualization, understand virtualization it's needed 64bit machines. can problem here? me, please? in advance. try increase 'ssh_wait_timeout' increase 'boot_wait' activate vb.gui options in vagrantfile increase 'config.vm.boot_timeout options in vagrantfile disable shared folder line config.vm.synced_folder '.', '/vagrant', disabled: true in vagrantfile update vagrant (latest 1.8.1) update virtualbox (latest 5.0.12) cross finger

android - Compile error building project with multiple flavors and Play Services -

when trying build play services enabled project multiple flavors, compile errors. think might related package names not matching, not sure. have hints doing wrong? i using newer gradle plugin allows ( per gh issue ) i seeing error when try build multiple flavors: error:(115, 50) error: cannot find symbol variable global_tracker i double checked package names match expectation, wonder if still not correct. my build.gradle looks this: productflavors { app1 { applicationid "com.examplea.app" manifestplaceholders = [domain:"examplea"] } imore { applicationid "com.exampleb.app" manifestplaceholders = [domain:"exampleb"] } crackberry { applicationid "com.examplec.app" manifestplaceholders = [domain:"examplec"] } an example of 1 of google-services.json files (which located @ main/src/examplea) i

Order list item on Rails update with jQuery -

i have sidebar list of room names. can edit room's name in modal. when click update in modal, room name should updated in sidebar , should appear in proper order in list. happen on refresh because of server side rails code. need make work on client side. it's working fine except sorting. i've tried in update.js.erb file: $("ul.rooms li").detach().sort(asc_sort).appendto('ul.rooms'); function asc_sort(a, b){ return ($(b).text()) < ($(a).text()) ? 1 : -1; } that results in each list item appearing twice , newly updated room sorts bottom of list. here's html looks list item (the room name 1): <li> <a href="#" class="room" id="room-11"> 1 <span class="badge counter"></span> </a> <a class="cog-link pull-right" style="padding:0 20px 0 2px;" data-remote="true" href="/rooms/11/edit"><i class="glyphic

ios - Need a completion block for SnapKit constraints in a UIView -

i have uiview in swift using snapkit layout it's views. want blur 1 of views, need put blur code in method runs after layout code finished , 1 view has it's proper size. i can't seem figure out right place blur code go. since snapkit based on blocks, it's asynchronous , don't know when finished. callback method can use? edit: reported issue on snapkit , blocks synchronous after all. however, in layoutsubviews (and after synchronous blocks) frames still cgrectzero , blur code can't snapshot , blur view of 0 width or height. i don't know snapkit there's technique can use code executed after last of bunch of asynchronous blocks has been completed. the trick create class hold piece of code , have each block hold reference it. in class's deinit code, execute code. example: class completionblock { var completioncode:()->() init?(_ execute:()->() ) { completioncode = execute } func deferred() {} deinit {

objective c - uisearchbar in grouped section uitable -

i've pieced several tutorials create grouped table sections , i'm trying uisearchbar work. problem i'm having how search within grouped sections. i've read similar questions post suggested can't this code create grouped sections #import "job.h" // model data #import "address.h" // model data - (void)viewdidload { [super viewdidload]; self.thetable.delegate = self; self.thetable.datasource =self; _searchbar.delegate = (id)self; fmdbdataaccess *db = [[fmdbdataaccess alloc] init]; jobs = [[nsmutablearray alloc] init]; jobs = [db getjobs:1]; _sections = [[nsmutabledictionary alloc] init]; nsmutablearray *jobstemparray = [db getjobsasdictionary:1]; bool found; // loop through books , create our keys (nsdictionary *book in jobstemparray) { nsstring *clong = [book objectforkey:@"addraddress"]; nsstring *c = [clong substringtoindex:1]; found =

ios - Dynamically changing the height of the cell and UIImage based on the ratio of actual image -

this have tried far i defined global variable float imgheight; then in - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath this size_t pixelswide = cgimagegetwidth(scribbleimage.image.cgimage); size_t pixelshigh = cgimagegetheight(scribbleimage.image.cgimage); cgfloat ratio = 312/pixelswide; pixelshigh = pixelshigh*ratio; then in - (cgfloat)tableview:(uitableview *)tableview heightforrowatindexpath:(nsindexpath *)indexpath return pixlesheight; now since heightforrowatindexpath called before cellforrowatindexpath , pixelsheight 0 . i cannot figure out way of doing this. should redefine uiimage in heightforrow , this [scribbleimage setimagewithurl: [nsurl urlwithstring:scribble[@"scribble_image"]] placeholderimage:[uiimage imagenamed:@"default.png"]]; in there well?! there should easier way of doing this. do in heightforrowatindexpath. understand conce

php - How to import XML feed with multiple images -

i have xml feed ... <products> <product> <title>mini piscina</title> <description>mini piscina penru copii pana la 6 ani.</description> <price>22.00</price> <images> <image1>produs_1402038969.jpg</image1> <image2>produs_1402382460.jpg</image2> </images> </product> </products> ... , part of script ... $xml=simplexml_load_file("../feed/feed") or die("error: cannot create object"); $partener = 'toys'; foreach($xml -> product $row) { $magazin = $partener; $titlu = $row -> title; $descriere = $row -> description; $pret = $row -> price; $imagine1 = $row -> images1; $imagine2 = $row -> images2; $sql = "insert toys (magazin,titlu,descriere,pret,imagine1,imagine2) values ('$magazin','$titlu','$descriere','$pret','$imagine1',

python - How can I change this div with same search_key when I click next button? -

this views.py retrieve 6 image urls instagram.first time ok how can change shown 6 images in home.html file(that retrieve 6 new images) when click next button? def home(request): trends = [] if request.method == 'post': if request.post.get('q'): search_key = request.post.get('q').replace(" ","") getimagefrominstagram(search_key) else: search_key = '' veriler = hashtags.objects.values_list('hashtag',flat=true) line = hashtags(hashtag=search_key,trends=search_key,image_url=tagurl) line.save() return render(request, "home.html", {'trends':trends,'urls':urls,'hashtags':veriler}) def getimagefrominstagram(): tagurl = 'https://api.instagram.com/v1/tags/'+ search_key +'/media/recent?client_id=hidden security' q = requests.get(tagurl).json() urls = [ q['data'][i][&

In R, is it possible set the title of a Cairo window? -

i'm outputting several plots via cairo package in r. having 5 windows titled "cairo graphics" makes hard find right 1 in taskbar. is there anyway change text in title bar? these did not work: cairowin(title="hello") windows.options(title="hello"); cairowin() unfortunately, window title hard-coded in cairo source code (in w32-backend.c ): window gawin = newwindow("cairo graphics", rect(20,20,width,height), document|standardwindow); so answer no, unless want patch , recompile package.

Issue with printing space with single quotes in a int array in Java -

i want print int[] in specific format (within space between each numbers, etc) however found java not print spaces in single quotes, , change numbers in int[] . same things happened bracket character. for example: int[] test = {1,2,3,4,5}; system.out.println('(' + test[0]+ ' ' +test[1] + ' ' + test[2] + ' ' +test[3] + ' ' + test[4] + ')'); //224 system.out.println("(" + test[0]+ " " +test[1] + " " + test[2] + " " +test[3] + " " + test[4] + ")"); //(1 2 3 4 5) i think space , bracket characters, , wonder why need use double quotes print them , why single quotes space character change output? thank you! the reason is, characters fundamentally stored numbers. when add characters other numbers, you'll receive number result. // prints 97 system.out.println('a' + 0); the situation character

centos - How to install php55-php-mcrypt with scl-utils? -

it's known fact on fedora/rhel/centos 7.x based systems php 5.4.16 supported version. however, application needed php 5.5 , installed rhel-recommended scl-utils repository explained on https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/developer_guide/scl-utils.html the problem have installed required packages except php55-php-mcrypt : yum install php55-php-mcrypt loaded plugins: fastestmirror loading mirror speeds cached hostfile * base: mirrors.sonic.net * epel: mirror.hmc.edu * extras: mirror.keystealth.org * updates: mirrors.easynews.com no package php55-php-mcrypt available. error: nothing could recommend way package installed? explanation why "mcrypt" bad idea, , not part of standard repository : about libmcrypt , php-mcrypt for people want use official rhscl packages on rhel (which available in centos-scl repository), can find additional packages in community repositories: php55 => php55more rh-php56 =&g

c# - Proving my contracts are validating the right thing -

i have interface so: [contractclass(typeof(contractstockdataprovider))] public interface istockdataprovider { /// <summary> /// collect stock data cache/ persistence layer/ api /// </summary> /// <param name="symbol"></param> /// <returns></returns> task<stock> getstockasync(string symbol); /// <summary> /// reset stock history values specified date /// </summary> /// <param name="date"></param> /// <returns></returns> task updatestockvaluesasync(datetime date); /// <summary> /// updates stock prices latest values in stockhistories table. /// </summary> /// <returns></returns> task updatestockpricesasync(); /// <summary> /// determines last population date stockhistories table, , /// updates table available after that. /// </summary> /// <returns></

sql - Order By Clause seems to be not working -

i have full-text search utilizes top , order by. i've used same query in database , order stays same. reason on different database, order seems change little. not lot, little. here looks like select top 20 * ( select distinct candidateid, [resume], firstname, middlename, lastname, row_number() on (order createddate desc) num dbo.tblcandidates (contains(([resume]), @searchitem)) ) num > @start can think of reason order clause wouldn't work in case? thanks! you don't have order by clause (the 1 inside over() clause used determine row_number() , not have influence whatsoever of order of output). if you've observed specific order query on other systems, has been purely coincidental , should not relied upon. if want specific order, need add order by outer query, no matter think should or have observed elsewhere. select top 20 * ( select distinct candidateid, [resume], firstname, middlename, lastname, row_number() o

PHP: imagepng() creates broken image -

Image
i have problem creating thumnail of png image. this works: $src = imagecreatefromjpeg("http://www.gaze.se/".$folder.$filename); $rootfolder = $_server['document_root'] ; $tmp = imagecreatetruecolor($targ_w, $targ_h); imagecopyresampled($tmp, $src, 0,0,$_post['x'],$_post['y'],$targ_w,$targ_h,$_post['w'],$_post['h']); imagejpeg($tmp, $rootfolder.$folder.'thumb_'.$filename,100); imagedestroy($tmp); imagedestroy($src); then change 2 jpeg functions png, this: $src = imagecreatefrompng("http://www.gaze.se/".$folder.$filename); $rootfolder = $_server['document_root'] ; $tmp = imagecreatetruecolor($targ_w, $targ_h); imagecopyresampled($tmp, $src, 0,0,$_post['x'],$_post['y'],$targ_w,$targ_h,$_post['w'],$_post['h']); imagepng($tmp, $rootfolder.$folder.'thumb_'.$filename,100); imagedestroy($tmp); imagedestroy($src

qlikview - Tie R script and QlikSense software together -

i require qliksense create excel file when user selects set of tuples , r automatically pick file, perform script on file. script creates csv file want qliksense automatically pick , perform predefined operations on it. there way can link 2 of these software in such manner? so clarify flowchart is: qlik gets large data set -> user selects set of rows , creates csv -> custom r script (picks csv automatically) run on csv , creates new csv -> qlik picks (automatically) , visually displays results of program is there kind of wrapper software tie them together? or better idea perhaps make sort of ui works r in background , user can manually pass file through ui? help. check out r extension has been developed on http://branch.qlik.com , extensions being created , added time. need create account access project once have direct link below. http://branch.qlik.com/#/project/5677d32d7f70718900987bdd

java - How add framelayout in first group listview(ExpandbleListView)? -

i'm trying add first group of new layout. disclosure of groups, new layout appears in other groups. want new layout added in first group expandblelistview. clumsy code adds in groups, , these groups not clickable. @override public view getgroupview(int groupposition, boolean isexpanded, view convertview, viewgroup parent) { if (convertview == null) { convertview = inflater.inflate(r.layout.mylistview, parent, false); } if(groupposition == 0) { linearlayout fl = (linearlayout)convertview.findviewbyid(r.id.mylistview); view fl2 = inflater.inflate(r.layout.infoday, fl, true); //fl.addview(fl2); } textview textchild = (textview)convertview.findviewbyid(r.id.textview22); group group = (group)getgroup(groupposition); textchild.settext(group.string); return convertview; } my list <?xml version="1.0" encoding="utf-8"?><framelayout xmlns:android="http://sc

android - The way to change database helper to support multiple languages? -

this dbhelper code. want ask whether possible support multiple language in database? there need use google translate api or should create database language? private databasehelper dbhelper; private sqlitedatabase db; private static final string k_id = "id"; private static final string k_name = "name"; private static final string k_ben = "benefit"; private static final string table = "plant"; private static class databasehelper extends sqliteopenhelper { databasehelper(context context) { super(context, "dbplant", null, 1); } public void oncreate(sqlitedatabase db) { string sql = "create table " + table + " (" + k_id + " integer primary key ," + k_name + " text , " + k_ben + " text);"; db.execsql(sql); sql = "insert " + table + " (" + k_n

c - reading from stdin after execl() bash return an eio(Input/output error) -

the following code can act expected if executed shell. but if set program user's shell , ssh host execute program shell, read(0, &buf123, 1); return eio(input/output error): #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <regex.h> #include <curl/curl.h> #include <readline/readline.h> int main() { char *shell = "/bin/bash"; pid_t child; if ((child = fork()) < 0) { perror("vfork"); return; } if (child == 0) { execl(shell, shell + 5, "-c", "exec /bin/bash --login", null); perror("execl"); return; } wait(null); char buf123[1024]; read(0, &buf123, 1); printf("::%s::\n", buf123); } but if change execl(bash) non-interactive bash execl(bash -c "id") or other program rather bash

Gmail API's history.list endpoint gives inaccurate data -

i'm seeing history list endpoint return incorrect data. when add label, history api endpoint returns "labelsremoved" , in fact returns incorrect label id. strangely, information under payload['labelsremoved']['message']['labelids'] correct. should ignore "labelsadded" , "labelsremoved" fields , use "messages" field instead? users.history: list have various properties per resource. labelsadded , labelsremoved lists if labels added/removed message. main property messages still contain messages of history record. list of messages changed in history record. fields specific change types, such messagesadded may duplicate messages in field. recommend using specific change-type fields instead of this.

database - How does a DBMS implement their own sorting algorithm? Or do they? -

when sql translated c parser such yacc or bison, piece of translated c code contains the sorting algorithm mathematics? not understand how sorting implemented in dbms (such mysql or microsoft sql server) - algorithm part of grammar parser? or, algorithm applies resulted group of data after fetched sql query, not directly apply computer memory? or sorting algorithm iso standard , dbms required use same algorithm? i did researched , googling find no clear answer. without unneedingly reading book on database internal, explain concept clearly? the sorting algorithm not part of grammar parser, it's technically 'implementation detail' . it's rather important 1 though, can fundamentally impact performance of complex queries. term 'implementation detail' refers it's dbms vendor decide , how it. it partially delegated query optimizer, common sorting algorithms heapsort, mergesort, quicksort et al have different 'best case scenarios'. perform

I can't insert data into a SQLite databse on Android -

i trying insert room numbers , coordinates database, access them give directions rooms, seems failing insert data database. here database handler: public class mrldatabasehandler extends sqliteopenhelper { //private context context; //private string locationsfile; private static final int database_version = 1; private static final string database_name = "mrl_locationsdb3"; static final string table_locations = "locations"; //table name private static final string key_id = "_gpspoint_id"; private static final string key_rnumber = "_rnumber"; private static final string key_lat = "_latitude"; private static final string key_longi = "_longitude"; private static final string key_alti = "_altitude"; public mrldatabasehandler(context context) { super(context, database_name, null, database_version); //this.context = context; //locationsfil

iphone - My app is only availbale in US store, why? -

today app releases on itunes,and it's free app available in store. how can change available worldwide? to change stores app appears in, go itunesconnect -> "manage applications" select app , click "rights , pricing" button. can check stores here. and if fine here , apple may need time updation. thanks

Card number is required- authorize.net -

i trying integrate authorize.net payment gateway in website. code works fine in testing mode when switch live mode gives me following error: [errorcode:net\authorize\api\contract\v1\transactionresponsetype\errorsatype\erroratype:private] => 33 [errortext:net\authorize\api\contract\v1\transactionresponsetype\errorsatype\erroratype:private] => expiration date required. i double check card info , correct still receive same error response. means card number passed not caught endpoint of api. here code passing card info: $creditcard = new anetapi\creditcardtype(); $creditcard->setcardnumber("16 digit card number"); $creditcard->setexpirationdate("2019-7"); $paymentone = new anetapi\paymenttype(); $paymentone->setcreditcard($creditcard); for security hide card number. idea overcome error appreciated. in advance. the customer’s credit card expiration date format must 1 of f

java - create new object in arraylist with attributes -

i new java , starting work arraylists . trying create arraylist students. each student has different attribute associated them ( name, id ). trying figure out how add new student object attributes. here have: arraylist < student > studentarray; public student(string name, int id) { this.fname = name; this.stid = id; } public stromg getname() { return fname; } public int getid() { return stid; } public boolean setname(string name) { this.fname = name; return true; } public boolean setidnum(int id) { this.stid = id; return true; } what need following: import java.util.*; class teststudent { public static void main(string args[]) { list<student> studentlist= new arraylist<student>(); student tempstudent = new student(); tempstudent.setname("rey"); tempstudent.setidnum(619); studentlist.add(tempstudent); system.out.println(studentlist.get(0).getname()+", "+stu

javascript - Intercepting AJAX Calls -

i'm facing problem intercepting ajax calls. know how can somehow intercept ajax calls @ level ajaxsetup(). have 1 question: ajaxsetup() intercepts calls within document. don't want that. i'm trying changing default type 'get' 'post' of calls. , need use ajaxsetup(). there way how can 'setup' selected or 'ajax calls follow url pattern'? thank you. use beforesend in $.ajaxsetup() $.ajaxsetup({ beforesend: function (jqxhr, settings) { settings.type = settings.url.indexof("foo") > -1 ? "post" : "get" } }); get request changed post -> fiddle (check network panel changed submission method)

keycode - Pressing specific keys to do certain things in JavaScript works in Chrome but not Firefox -

i'm using 2 functions detect whether pressed key matches want, , if so, something. works charm in chrome, neither function works in firefox. there way can make work there too? document.onkeypress = function() { if (event.charcode == 49) { alert("you pressed 1!"); } if (event.charcode == 50) { alert("you pressed 2!"); } if (event.charcode == 51) { alert("you pressed 3!"); } if (event.charcode == 52) { alert("you pressed 4!"); } } document.onkeydown = function() { if (event.keycode == 122) { alert("you pressed f11!"); } } <span>press 1, 2, 3, 4 , f11 launch different events.</span> you forget declare event argument. perhaprs chrome automatically. works in both browsers- document.onkeypress = function(event) { if (event.charcode == 49) { alert("you pressed 1!"); } if (event.charcode == 50) { alert("you pres

osx - Any tool that can confirm if a drive with raw partition is part of a ZFS pool? -

i have client issue working on stack of ssd drives , machine installed in. of now, stack of drives shows in few operating systems (win10, win7, mac osx) unpartitioned raw space. looking simple way examine drive , see if raw, or formatted zfs. does know of windows or mac utility help? i've tried few recovery software programs, hinted @ being compatible zfs formatted drives, have yet see indicate if zfs, or not formatted. regards, ed zfs storing @ start , @ end of each device magic number, 0x00bab10c ("oobabloc", i.e. überblock), reversed little-endian: 0x0cb1ba00 . so if number doesn't appear in device data, can sure isn't used zfs. if appear, need investigate little further. for details, have zfs on disk specification draft available here , page 13.

asp.net mvc - MVC Data access logic -

i know many people have asked question still don't have clear understanding should data access layer in mvc project. here do: i have web application , data access layer in separate projects in data access project have 1 class (which have named "db") processes requests database and when need example list books call db.getallbooks(); controller is practice or should have separate class books operations, user operations etc in data access layer?

image - Android - Too much memory consumed by changing ImageView drawable -

in android app have custom imageview which, based on user interaction, needs update image. imageview can have 2 images, represent , front of card. so, when user clicks button need show of card (set custom's imageview image of card , when user cliks button again, set front image imageview drawable). in order accomplish have 2 methods in custom imageview: public void showback() { setimageresource(r.drawable.card_back); } public void showfront() { setimageresource(r.drawable.card_front); } of course, works great, memory consumption of app near 114 mb, , increases user clicks button (rotates card). due that, think problem produced change of image. images small, 1 104.6kb , other 80.4kb (png format), don't understand why app consuming memory (maybe because images allocated times , never recycled?, or maybe because of android's cache system of drawables?) so, can solve problem? thank you. image dimensions 335 x 501 the size of images don't

javascript - Use SetInterval when the If condition is True -

is possible if value of $new changed var updatechart function reload again , again goes var check function , again have same condition on it. var updateinterval = 3000; var updatechart = function() { var check = function() { if(<?php echo $new; ?>).change(function(){ setinterval(function(){updatechart()}, 1000); }); } dps.push(<?php echo $str; ?>); chart.render(); }; will appreciated thanks. so want update chart value has been written on server-side, right? mentioned in comment, using php statements in js block not work php code run on page load , won't change afterwards. instead, should use two-step approach: use recurring ajax call poll changes create php page reports changes js code (using jquery ): window.setinterval(function() { $.ajax('change-listener.php', { success: function(data) { if (data.changed) { for(var in data.newvalue) { dps.push(data

regex - simple Perl regular expression -

hi i'm quite new perl , seeking parse simple line of code. what need parse in of #include "filename" i need regular expression file name. i know there's split method in python this, don't know if there's similar func in perl thanks you could split in perl: my $fn = (split('"', $include_line))[1]; ...but that's pretty obtuse way of going it. i'd opt for my ($fn) = $line =~ /^#include +"([^"]+)"/; instead, clearer , has advantage of returning nothing on non- #include lines rather returning false positives if input file contains other lines double-quoted text.

wpf - C# Set translatetransform X and Y property relative to MainWindow -

i have wrappanel hosted inside itemscontrol wrapped in scrollviewer. items in wrappanel populated binding. every item has datatemplate datatrigger. trigger suposed animate item center of screen. trying translatetransform, problem x , y properties of translatetransform relative item , not host container, every item has different animation. seen here: webm 1 webm 2 the item template xaml: <datatemplate x:key="countryitemtemplate"> <grid x:name="gridmain" height="auto" width="auto" margin="3" rendertransformorigin="0 0" panel.zindex="{binding isvisible, mode=oneway, updatesourcetrigger=propertychanged}"> <materialdesign:card x:name="cardmain" height="350" width="310" rendertransformorigin="0.5, 0.5" materialdesign:shadowassist.shadow

Algorithm / pattern to process variable embedded loops in java without recursion -

i looking algorithm/pattern process undefined quantity of inner loops without recursion , in java. i suppose inner loops same (or similar) process. each loop produces/processes/stores datas, depending on outer loops. complexity exponential. usage: combinatorics example. looking generic solution. some examples (which dont comply): embedded not variable : if number of inner loops known : for (int i=0;...) { // process 1 (int j=0;...) { // process 2 (int k=0;...) { // process 3 } } } multiple loops, not embedded for (int which_loop = 1; ...) { // loop which_loop // problem: loops not embedded, cant reuse datas ... } one approach make iterators array of iterators, , use count. for simplicity, let assume variables go same number ( n ), , number of such variables num_dimensions . assumption can relaxed checking against array instead of value n . pseudo code: int[] arr = new int[num_dim

function - What does this MATLAB class to and why isn't it working on my PC? -

the first 1 in documentation: http://www.mathworks.com/help/matlab/matlab_oop/getting-familiar-with-classes.html the class is: classdef basicclass properties value end methods function r = roundoff(obj) r = round([obj.value],2); end function r = multiplyby(obj,n) r = [obj.value] * n; end end end when run way a = basicclass a.value = pi/3; it works fine , should piece of code a = basicclass(pi/3); gives following error: "error using round too many input arguments." what mean? (i'm using r2014a) stupid use oop in matlab? lol your error message doesn't correct compared code, whichever missing class constructor (as mentioned @ half way down link): classdef basicclass properties value end methods % class constructor -> can pass pi/3 into. function obj = basicclass ( varargin ) if nargin == 1 obj.value = varargin{1}; end end % met

php - Generating all combinations of possible clicked checkboxes to add the values -

i have generate possible combinations of 4 checkboxes order not matter. reason order not matter because add values connected checkboxes. the array of categories is: ['kw1','kw2','kw3','kw4'] this means kw1+kw2 = kw2+kw1 . must seen 1 combination. i've gotten pretty far, failing wrap head around it. first of all, user can click between 1 , 4 checkboxes, there no fixed amount of checked checkboxes required. can translated loop: for($i=1;$i<=4;$i++){ } when 1 checkbox can clicked, there 4 possible options. when 4 checkboxes checked, 1 option available. when 1st checkbox checked, there 3 options left. when 2nd checkbox checked, 2 options remain available. drill. i translated to: for($i=1;$i<=4;$i++){ $j = 5 - $i; $reverse_j = 0; $categories = array('kw1','kw2','kw3','kw4'); for($j;$j>0;$j--){ $reverse_j++; $counter = 0; foreach($categories $category){