Posts

Showing posts from June, 2015

indexing - R: row index list from list of column values? -

in r, how index list of values 1 r column based on specified list of values column? i know how select , modify specific row numbers, e.g.: > foo=data.frame(a=100*1:5,b=letters[5:1]) > foo b 1 100 e 2 200 d 3 300 c 4 400 b 5 500 > foo$a[c(1,3,5)]= foo$a[c(1,3,5)] + c(3,2,1) > foo b 1 103 e 2 200 d 3 302 c 4 400 b 5 501 but if instead want select , modify rows 'b' values "a", "e", , "c"? thought which might correct tool, best i've been able come is: > foo$a[which(is.element(foo$b,c("a","e","c")))] [1] 103 302 501 at point i'm stuck, because while i've selected correct rows, aren't in right order can't modify them individually. removing is.element , use %in% solution if don't care matching order [edit] - can remove which foo$a[foo$b %in% c("a","e", "c")] another possibility use match provide indices of each eleme

c# datetime format using singleline -

any easy way the date in (european) format? day/month/year hour/minute/sec i need date space between year , hour. if possible without saving string, because draw on images timestamp. this give date , time string can draw on images: datetimeobject.tostring("dd/mm/yyyy hh/mm/ss"); (edited due comment slashes required.)

ios - Is caching a NSDateformatter application-wide good idea? -

it's well known creating nsdateformatters ' expensive ' even apple's data formatting guide (updated 2014-02) states: creating date formatter not cheap operation. if use formatter frequently, typically more efficient cache single instance create , dispose of multiple instances. 1 approach use static variable. but doc seems not date swift , can't find in latest nsdateformatter class reference caching formatter can assume it's expensive swift objective-c. a lot of sources suggest caching formatter inside class using it, example controller or view. i wondering if handy or 'cheaper' add singleton class project store datepicker you're assured it's never necessary create again. used everywhere in app. create several shared instances containing multiple datepickers. example 1 datepicker displaying dates , 1 time notation: class dateformattermanager { var formatter = nsdateformatter() class var dateformatmanager : dateform

visual studio - Can I pass an argument/switch/parameter to a VSPackage MenuCommand? -

i hoping here might able me out this. i'm not experienced programmer i'm making progress on project. i've got need programmatically interact visual studio. success has been had using envdte interop stuff, seems of need needs done inside vs i'm attempting utilize vspackage menucommand various things. sorry vagueness. i'm creating custom menucommand vspackage extension, , able trigger menucommand programmatically application using dte. what i'm wondering is: possible define menucommand can take arguments passed along triggering external application? using vs package template in visual studio 2012 using menu command option, code lives inside method: private void menuitemcallback(object sender, eventargs e) { // code... } there lot of other auto-generated code plumbing together, code lives in method. there way alter method allow parameters passed it? other changes must make other files declare/register differently-functioning method

python - printing, splitting, and replacing in lists -

i'm trying make quiz using questions file, , choice between 2 answer files. going have user choose between printing questions , answers, or few randomly generated ones. problem having trouble getting display intended. need display like: 1. how many... etc. a.answer b.answer c.answer d.answer e.none of above but can't output right. text files consists of answers placed this: c,3,4,5,6 a,4o,30,20,10 e,65,245,456,756 so have replaced commas spaces, , have been succesful displaying them row rather 1 line using \n in place of spaces.. won't work answers more 1 word. need remove letter before answers (it's correct answer) , place list, , i'm unsure of how this. import random def main(): print("welcome garbology quiz \n") quizfilecheck = input("first off, quiz file name? ") while quizfilecheck != "questions.txt": quizfilecheck = input("file not found.. correct quiz file name? ") answerfile

python - How to use seaborn pointplot and violinplot in the same figure? (change xticks and marker of pointplot) -

Image
i trying create violinplots shows confidence intervals mean. thought easy way plot pointplot on top of violinplot, not working since seem using different indices xaxis in example: import matplotlib.pyplot plt import seaborn sns titanic = sns.load_dataset("titanic") titanic.dropna(inplace=true) fig, (ax1,ax2,ax3) = plt.subplots(1,3, sharey=true, figsize=(12,4)) #ax1 sns.pointplot("who", "age", data=titanic, join=false,n_boot=10, ax=ax1) #ax2 sns.violinplot(titanic.age, groupby=titanic.who, ax=ax2) #ax3 sns.pointplot("who", "age", data=titanic, join=false, n_boot=10, ax=ax3) sns.violinplot(titanic.age, groupby=titanic.who, ax=ax3) ax3.set_xlim([-0.5,4]) print(ax1.get_xticks(), ax2.get_xticks()) gives: [0 1 2] [1 2 3] why these plots not assigning same xtick numbers 'who'-variable , there way can change this? i wonder if there anyway can change marker pointplot, because can see in figure, point big covers entire

SQL Server query (view) Convert String to DateTime -

i'm bit rusty , seem have forgot how this. receiving data , datatime column in string format char(12) . example : 201411061900 how write query (view) convert datetime ? i've used convert (datetime, dbo.kwh.mr_dtm,120) , error conversion failed when converting date and/or time character string. i haven't had luck. thank in advance. if want suggest -5 time zone also, wouldn't mind. :) magnus answered question. wanted post here incase helps in future. here link answer. there no output format identifier (like example 120) lets convert char(12) datetime in sql server. use substring function: select cast(substring(dbo.kwh.mr_dtm,1,8) + ' ' + substring(dbo.kwh.mr_dtm,9,2)+':'+ substring(dbo.kwh.mr_dtm,11,2) datetime) thank everyone! appreciated. oh, , post me solve timezone setup. convert datetime column utc local time in select statement many michael goldshteyn timezone convert.

c# - Unable to handle http error 404.13 in mvc 5 app on iis 8.0 -

i working on mvc5 project allows users upload files. have methods filter out invalid file extensions (only pictures , pdfs allowed). however, when try upload large file, regardless of extension, error: http error 404.13 - not found request filtering module configured deny request exceeds request content length. the method upload doesn't called, goes straight error page. one post found expressed needed modify project's web.config file, , did such: <security> <requestfiltering> <requestlimits maxallowedcontentlength="6000000" /> </requestfiltering> </security> i still error, tried adding <httpruntime maxrequestlength="6000" executiontimeout="3600" /> <system.web> , threw error: http error 500.19 - internal server error requested page cannot accessed because related configuration data page invalid. obviously line must earlier versions of iis. i found solution suggested editing a

Simple clojure java interop (swing) program can't quite get it to work -

i close getting program below work. using lighttable. have included java exception @ end. passing in nil jdatepanelimpl constructor wrong, not sure how build property: //this java definition public jdatepanelimpl(datemodel<?> model, properties i18nstrings) { ... } ​ this project.clj (defproject jdatepickertest "0.1.0-snapshot" :description "fixme: write description" :url "http://example.com/fixme" :license {:name "eclipse public license" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [ [org.clojure/clojure "1.6.0"] [org.jdatepicker/jdatepicker "1.3.4"] ] ) code follows (ns jdatepickertest.core) (import '(java.util enumeration locale properties resourcebundle) '(org.jdatepicker jdatepicker jdatepanel) '(org.jdatepicker.i18n) '(org.jdatepicker.impl jdatepanelimpl jdatepickerimpl utildatemodel utilcalendarmodel

python - Merge two lists of objects containing lists -

i have directory tree containing html files called slides. like: slides_root | |_slide-1 | |_slide-1.html | |_slide-2.html | |_slide-2 | | | |_slide-1 | | |_slide-1.html | | |_slide-2.html | | |_slide-3.html | | | |_slide-2 | |_slide-1.html ...and on. go deeper. imagine have replace slides in structure merging tree subset of this. with example: want replace slide-1.html , slide-3.html inside "slides_root/slide-2/slide-1" merging "slides_root" with: slide_to_change | |_slide-2 | |_slide-1 |_slide-1.html |_slide-3.html i merge "slide_to_change" "slides_root". structure same goes fine. have in python object representation of scheme. so 2 trees represented 2 instances - slides1, slides2 - of same "slide" class structured follows: slide(object): def __init__(self, path): self.path = path self.slides = [slide(path)] both slide1 , slide2 contains path , list contain other slide objects other

bash - Base64 data in awk -

i have file , process awk tool. awk -f "|" '{print $3 "|" $7 "|" $1 "|" $2}' animals.csv | grep cats >> data.txt how can make $3 encode base64 format? thank you. try doing : awk -f "|" ' { "echo "$3" | base64" | getline x print x, $7, $1, $2 } ' ofs='|' animals.csv | grep cats >> data.txt the awk's getline read variable system command.

python - redis-py pipeline hset not saving -

i have set pipeline on redis-py save 2 diferent hashes p = self.app.redis.pipeline() key_id = '{}{}'.format(self.prefix,article.id) key_url = '{}{}'.format(self.prefix,article.url) # add common fields articlemodel p.hset(key_id, 'shorturl', shorturl) p.hset(key_url,'shorturl', shorturl) k in article.__table__.columns: k = k.name if k not in ['url','id']: p.hset(key_id, k, article.__getattribute__(k)) p.hset(key_url, k, article.__getattribute__(k)) # add different fields , finish transaction p.hset(key_id, 'url', article.url) p.hset(key_url, 'id', article.id) p.expireat(key_id, self.expiration_window) p.expireat(key_url, self.expiration_window) p.execute() the pipeline before executing is: [(('hset', 'article/1', 'shorturl', 'qp'), {}), (('hset', 'article/http://pytest.org/latest/contents.html', 'shorturl', 'qp'), {}), ((

apache spark streaming - kafka - reading older messages -

i trying read older messages kafka spark streaming. however, able retrieve messages sent in real time (i.e., if populate new messages, while spark program running - messages). i changing groupid , consumerid make sure zookeeper isn't not giving messages knows program has seen before. assuming spark seeing offset in zookeeper -1, shouldn't read old messages in queue? misunderstanding way kafka queue can used? i'm new spark , kafka, can't rule out i'm misunderstanding something. package com.kibblesandbits import org.apache.spark.sparkcontext import org.apache.spark.streaming.{seconds, streamingcontext} import org.apache.spark.streaming.kafka.kafkautils import net.liftweb.json._ object kafkastreamingtest { val cfg = new configloader().load val zookeeperhost = cfg.zookeeper.host val zookeeperport = cfg.zookeeper.port val zookeeper_kafka_chroot = cfg.zookeeper.kafka_chroot implicit val formats = defaultformats def parser(json: string): strin

python - How to use django registration redux? -

when enter email id in registration form , submit it, redirected page saying check email id. don't see mail in inbox. in terminal email printed, contains activation link. also, when goto activation link, says account activated. able logout. tried logging in, before logging out after logging out. both time failed log in. says please enter correct username , password. these settings. tried in both modes - debug = true , debug = false. account_activation_days = 7 registration_auto_login = true login_url = '/accounts/login/' registration_email_subject_prefix = '[django registration test app]' send_activation_email = true registration_open = true email_backend = 'django.core.mail.backends.console.emailbackend' email_host='smtp-auth.iitb.ac.in' email_port=587 email_host_user='ngreloaded@iitb.ac.in' email_host_password='wrong.password' email_use_ssl = true email_use_tls = true default_from_email = 'ngreloaded@iitb.ac.in'

html - CSS overlay that takes 100% of parent element height -

i need element in snippet tinted darker. this, have overlay element black partial transparency. cover red element in it's entirety. problem is, can't overlay 100% height. why won't work, , how can work without specifying exact heights? .overlay-shell { position: relative; top: 0; left: 0; } .overlay { background-color: rgba(0, 0, 0, 0.5); top: 0; left: 0; height: 60px; /* how take 100% of height? */ width: 100%; position: absolute; } ul.alarms { list-style: none; margin: 0 30px; } ul.alarms li.alarm { background-size: 100%; background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #c53635), color-stop(50%, #9d2b2a), color-stop(51%, #952928), color-stop(100%, #9d2b2a)); background-image: -moz-linear-gradient(#c53635 0%, #9d2b2a 50%, #952928 51%, #9d2b2a 100%); background-image: -webkit-linear-gradient(#c53635 0%, #9d2b2a 50%, #952928 51%, #9d2b2a 100%); background-image: linear-gradient(#

multimedia - How to get the album artwork from a music file using PHP? -

i can hold multitude of music files in folder, on server. range among formats : mp3, mp4, wma, ra, mid , ogg. album art embedded (if any) newly uploaded , store in folder, using pure php. possible? if yes how? note : learning scenario, rather implementation. know few ready-made php scripts meta tags, want know thoroughly. anyone kind enough please explain. i think, id3_get_tag friend. php.net documentation id3_get_tag read musicfile function, check returned associative array, key value album art contains. should bytestream. save bytestream in file jpg or anythig else, bytestream possibly say, type of image cover is. it's theory, if try answer, please let me know, if works.

linked list - Writing a method to sort a singly linkedlist in ascending order (java) -

the method 'insertascending' gives me first number after enter new ones. can i'm doing wrong? thanks. public class linkedlist13 { // private inner class node private class node{ int data; node link; public node(){ data = integer.min_value; link = null; } public node(int x, node p){ data = x; link = p; } } // end of node class public node head; public linkedlist13(){ head = null; } public void insertascending(int data){ node node = new node(); node.data = data; if (head == null) head = node; node p = head; while (p.link != null) { if (p.link.data > data) { node.link = p.link; p.link = node; break; } p= p.link; } } } first of all, should return after setting head of list (when first element added). second of all, should handle case newly inserted node smallest in list (and theref

c++ - g++ 4.7 bug with SFINAE + decltype? -

i have constructed following mcve illustrate issue i'm having g++ 4.7. uses sfinae via decltype() determine if functor type can called given argument type (specialized test if functor type can called no arguments when argument type void ). #include <iostream> #include <utility> template <typename f, typename a> class can_call_functor_impl { private: typedef char yes[1]; typedef char no[2]; template <typename u> static auto test(u *) -> decltype(void(std::declval<u const &>()(std::declval<a &>())), std::declval<yes &>()); template <typename> static no & test(...); public: static constexpr bool value = sizeof(test<f>(0)) == sizeof(yes); }; template <typename f> class can_call_functor_impl<f, void> { private: typedef char yes[1]; typedef char no[2]; template <typename u> static auto test(u *) -> decl

symfony - Symfony2, how to pass a parameter off route -

id know how pass parameter off route route: frontend_agences_list: path: /agences/{page} defaults: { _controller: projectfrontendbundle:frontend:listagences, page: 1 } is ? twig: <a href="{{ path('frontend_agences_list') }}?mode=list"> <a href="{{ path('frontend_agences_list') }}?mode=grid"> <a href="{{ path('frontend_agences_list') }}?mode=block"> in fact, i'd display results in 3 modes, list , grid , block . in controller test ,if mode=list render " list-view.html.twig ", elseif mode=grid render " grid-view.html.twig " .... is way or there way ? twig: <a href="{{ path('frontend_agences_list', {'mode': 'list'}) }}">list mode</a> <a href="{{ path('frontend_agences_list', {'mode': 'grid'}) }}">grid mode</a> <a href="{{ path('frontend_agences_list

javascript - Web Audio onaudioprocess works in Firefox, JSFiddle in Chrome, but not Chrome Itself -

i'm working in chrome 39.0.2171.71 (64-bit) on webaudio/webmidi app. have jazz-soft webmidi plugin installed. i'm having trouble getting onaudioprocess fire @ all. i've stripped things down basic code: <!doctype html> <html lang="en"> <head></head> <body> page loaded. <script> var context; if (window.audiocontext) { context = new audiocontext(); } else { context = new webkitaudiocontext(); } console.log('javascript working.'); oscillator = context.createoscillator(); oscillator.start(0); myscriptnode = context.createscriptprocessor(4096, 1, 1); myscriptnode.onaudioprocess = function(event) { console.log('onaudioprocess works!'); }; oscillator.connect(myscriptnode); </scri

ASP.NET 5 project hosting on IIS -

i want host asp.net 5 project uses mvc 6 , entity framework 7 on amazon free micro instance. can't find step-by-step manual on how host asp.net 5 projects on iis, materials mention possible without guides. basically, i'm deploying local folder , copying newly created site, nothing working. unfortunately, can't use azure has 1 month free trial, not year. i'm using visual studio 2015 preview create asp.net 5 projects. don't think that's difficult deploy on iis now. first publish website publishing file system in vs 2015 preview, copy published folder server, create application in iis , set application folder wwwroot folder (rather root folder), that's all. aware, check if "microsoft.aspnet.server.iis" exists in website project.json before publishing it. edit: there should web.config in wwwroot folder, content of web.config may (with precompile option when publishing): <?xml version="1.0" encoding="utf-8"?> &

c - Scanning values from file using fscanf -

hey need read data file , print it(i have use fscanf). code works first value when add more it's not working. here code char name[5]; //this value fixed size char isworking; double latitude; //the length may vary double longitude; //the length may vary while(fscanf(fp2,"%s %c %lf %lf",name,isworking,latitude,longitude) == 4) { printf("\n%s %c %lf %lf",id,type,latitude,longitude); i++; } my file looks that bob1 y 122.232323 -9.323232 bob2 n 9.0001 -9.001 it doesn't print except when remove other values , try read name

How do you clear form inputs when a model changes in AngularJS? -

i have form has common inputs , inputs specific model 'type'. when user selects 'type', select dropdown, these specific fields change. i'm using ng-include include specific 'partial' based on model.type. in 'edit' mode, how can reset these specific inputs when model 'type' changes? use ng-change property on select . then tie function clears models bound form inputs (e.g. sets '' ). jsfiddle

Java Graphics fillrec() method with double parameters -

i working on graphics project university. trying use fillrect method java graphics class. the problem method takes in integer values: fillrect(int x, int y, int width, int height) i need take in decimal values double instead of integers. possible or there sneaky way pass this? thanks remember, pixel whole number, unless you're doing high resolution printing, don't need double value. having said that, use rectangle2d.double shape , use graphics2d#fill if feel need it have @ working gemoetry more details

android - Shuffling in a gridview -

i having trouble shuffling images in gridview. makin npuzzle slider , can slide blank image. main problem set tags on imageview in gridviewadapter. if shuffle images, these tags stay same supposed change images. example suppose got bitmaparraylist of bitmaps: {bm0,bm1,bm2,bm3,bm4,bm5,bm6,bm7,bm8} , set tags {0,1,2,3,4,5,6,7,8} in image adapter. if shuffle bitmap, how supposed shuffle imagetags them? here code of imageadapter: private arraylist<bitmap> crops; private list id; private context mcontext; public imageadapter(context c, arraylist<bitmap> crops, list id) { mcontext = c; this.crops = crops; this.id = id; } public int getcount() { return crops.size(); } public object getitem(int position) { return null; } public long getitemid(int position) { return 0; } public view getview(int position, view convertview, viewgroup parent) { imageview imageview; if (convertview == null) { // if it's not recycled, initialize attrib

c++ - division by zero with a template argument -

i have template template<size_t n> class foo { int bar(int a) { if (n == 0) return 0; return / n; } } when instantiate 0 foo<0> bar; gcc smart , reports division 0 @ compile time i tried class foo<size_t n> { template<size_t m> int bar(int a) { return / n; } template<> int bar<0>(int a) { return 0; } }; but gives me error: error: explicit specialization in non-namespace scope 'class foo' error: template-id 'bar<0>' in declaration of primary template any ideas how solve/workaround this? you can create template specialization foo<0> . template <> class foo<0> { public: bool bar () { return true; } }; if want address issue bar alone, , not touch other part of foo , can create companion method avoid issue: template <size_t n> class foo { bool bar(int n) { if (n == 0) return true

linux - Node spawn stdout.on data delay -

i checking usb drive removal on linux. monitoring output of command line process child_process.spawn. reason child's stdout data event doesn't emit until 20 lines have been printed, makes unable detect removed drive. after removing drive many times, go. won't do. original: var udevmonitor = require("child_process").spawn("udevadm", ["monitor", "--udev"]); udevmonitor.stdout.on("data", function(data) { return console.log(data.tostring()); }); pretty simple. figure it's issue piping node using internally. instead of using pipe, figure i'll use simple passthrough stream. solve problem , give me real-time output. code is: var stdout = new require('stream').passthrough(); require("child_process").spawn("udevadm", ["monitor", "--udev"], { stdio: ['pipe', stdout, 'pipe'] }); stdout.on("data", function(data) {

html - Insert &trade or &nbsp; using jquery text -

i know can solve using .html() have use text(). there way these values inserted on page shows trademark symbol or empty space ? can add trademark symbol directly text string? this: html: <p></p> js: $('p').text('™'); jsfiddle: http://jsfiddle.net/zr8geb36/

viewcontroller - Presenting a view controller programmatically in swift -

hi trying convert following objective c code swift navigate 1 view controller view controller when button clicked. appreciated this taken apple's programming guide - (void)add:(id)sender { // create root view controller navigation controller // new view controller configures cancel , done button // navigation bar. recipeaddviewcontroller *addcontroller = [[recipeaddviewcontroller alloc] init]; // configure recipeaddviewcontroller. in case, reports // changes custom delegate object. addcontroller.delegate = self; // create navigation controller , present it. uinavigationcontroller *navigationcontroller = [[uinavigationcontroller alloc] initwithrootviewcontroller:addcontroller]; [self presentviewcontroller:navigationcontroller animated:yes completion: nil]; } my code indicated below, not sure how implement in navigation controller, in storyboard mainsectionviewcontroller embedded navigation controller f

java - How to display a JLabel without a layout manager -

i making game final project , need have label big "x" appear in middle of jpanel. have jpanels appearing label not appear because dont have layout manager, if use layout manager entire project gets changed. project have can see i'm trying do. create game helps new mouse users improve hand-eye coordination. within jframe, display array of 48 jpanels in gridlayout using 8 rows , 6 columns. randomly display x on 1 of panels. when user clicks correct panel(the 1 displaying x), remove x , display on different panel. after user has “hit” correct panel 10 times, display congratulation message includes user’s percentage(hits divided clicks). save file jcatchthemouse.java. here's code package catchthemouse; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class catchthemouse extends jframe implements actionlistener, mouselistener{ final int rows = 8; final int cols = 6; final int gap = 2; final int max_panels = rows

php - regex find or return the second one -

i have text this `state`.`stateid` and want write regex select second part, stateid , i'm not in regex, can me solve please? it's example want second part of every given strings as example, if have: `alabama`.`al` `alaska .`ak` `arizona`.`az` `arkansas`.`ar` `california`.`ca` use regex capture second text: /.+`(\w+)/g

java - Ordinal hour-of-day "Hour Ending" conversion to date-time value -

some businesses track events in time "hour ending". each hour of day represented ordinal number: 1…24 utc 1…23, 1…24, , 1…25 time zones one-hour daylight saving time (dst) adjustment. so first hour of day, midnight 01:00 hour ending 01 . to me, seems silly way track time. more sensible using time-of-day half-open approach, [) , beginning inclusive, , ending exclusive. so: 2014-12-05t01:00:00.000 mark hour ending 01 2014-12-06t00:00:00.000 (midnight) mark hour ending 24 . indeed, want store in database ( postgres ), timestamp time zone value converted date & ordinal hour number. question is: given date , ordinal "hour ending" number (1…23/24/25 locality 1-hour dst), how convert date-time value? i'm familiar joda-time , java.time . either of them offer way convert? if not, kind of algorithm handles both ordinal number conversion , dst? or should not fight this, , store local date string suffix of ordinal hour number?

python - how to make a Matplotlib 3D Scatter Plot bigger? -

i have piece of code: from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(data.fac1_1, data.fac2_1, data.fac3_1, c='r', marker='o') ax.set_xlabel('x label') ax.set_ylabel('y label') ax.set_zlabel('z label') plt.show() everything works perfeclty fine. issue scatter plot comes out tiny. there ay make bigger? ooked @ documentation wasn't able find it. thank you you can make figure bigger using figsize: fig = plt.figure(figsize=(12,10)) to make markers scatter plot bigger use s : ax.scatter(data.fac1_1, data.fac2_1, data.fac3_1, s=500, c='r', marker='o')

windows - “The application was unable to start correctly (0xc000007b)." -

i use visual studio 2013, opencv , c++. when run program, said "mscvp110.dll missing".i downloaded 32/64 bit dll file , put 32 bit under c/windows/system32,64 bit under c/windows/syswow64. error via “the application unable start correctly (0xc000007b)." how can fix problem?

output - Format the print statement in Python -

i have script takes in txt file list of attributes go input program. each attribute, prints out attribute name if satisfies conditions of script. however, each attribute may satisfied multiple times , output prints many times. i'd now: condition 1 satisfied a,b,c,d condition 2 satisfied a,b condition 3 satisfied b,d how do this? current output looks like a condition 3 not satisfied b b b condition 1 not satisfied c condition 2 not satisfied c c d condition 2 not satisfied d d how (in pseudo python code) import collections result = collections.defaultdict(list) attr in [a, b, c, d]: cond in [condition1, condition2, ...]: if attr satisfies cond: result[cond].append(attr) print result output: {cond1: [a, b], cond2: [a], cond3: [c,d], ...} i'm not sure want. haven't stated (enough) input looks , want output.

android - simple adapter listview horizontal -

i want fill listview images drawable folder, listview has horizontal listview, have seen lot of tutorial on this, personalized listview. why dont use viewpager can add number of fragments dynamically similar how populate listview.

windows ce - Magento CE 1.9.0.1 robots.txt not showing when called -

if put robots.txt in public_html (permissions 755) , try see in browser websitename/robots.txt error magento: server temporarily unable service request due maintenance downtime or capacity problems. please try again later. ce 1.9.0.1 rest of site works fine. robots.txt file has following in (for now): user-agent: * disallow: drives me crazy. where put robots.txt or doing else wrong? the website www.holiseeds.com if need know. i can see robots.txt. clear browser's cache , remove cookies.

c++ - How to declare an operator-like expression as a function call? -

goal: describe way provide function calls in such way given function "t f(t a, t b)" expression "e" written in code "aeb" calls function "f(a, b)"! motivation: to provide abbreviated forms of function calls, when syntax increase clarity of code versus standard form. example: #include <iostream> #include <random> #include <valarray> using namespace std; constexpr unsigned int sides = 20u; random_device rndngen; uniform_int_distribution<unsigned int> dice[sides]; // function called via in-order unsigned int operatord(unsigned int number, unsigned int sides) { valarray<unsigned int> dice(number); for(unsigned int & : dice) { = dice[sides](rndngen); } return dice.sum(); } int main() { // desired call syntax int x = 1 + 1d6; // executes operator=(x, operator+(1, operatord(1, 6))) cout << x << endl; // displays number in [2, 7] } note chosen expression d cannot c

php - Allowed memory size of bytes exhausted - Codeigniter -

when call library upload controller, error fatal error: allowed memory size of 1073741824 bytes exhausted (tried allocate 65488 bytes) in d:\xampp\htdocs\symfony\web\system\core\log.php on line 478 controller method edit: function edit($id){ $this->action ="edit"; if (empty($_post["id"])) $_post["id"] = $id; if(isset($_post['edit'])){ $_post['image'] = $this->model_img_upload->imageupload($this->imuploadconfig); if($this->model_akcii->edit_data($_post)){ $this->session->set_flashdata('msg',$this->lang->line('msg_edit')); redirect('akcii'); } } $this->item = $this->model_akcii->get_info($id); $this->item_lang = $this->model_akcii->get_lang_info($id); $this->load->view("edit",$this); } imageupload method: function imageupload ($config=array()){ if(isset($_files['userfile'])){ $_files['

frequency - table() in R needs to return zero if value is not present -

i relatively new r, , i'm doing dna sequence analysis. wanted know how table function return 0 if there no n's in sequence. instead of returning 0 returns subscript out of bounds. if statement thought there might simple way fix this? help! library(seqinr) firstset<-read.fasta("nc_000912.fna") seqfirstset<-firstset[[1]] length(seqfirstset) count(seqfirstset,1) count(seqfirstset,2) seqtable<-table(seqfirstset) seqtable[["g"]] seqtable[["n"]] if data factor appropriate levels, you'll have no problem: > x <- factor(letters[1:3]) > y <- factor(letters[1:3], levels = letters) > table(x) x b c 1 1 1 > table(y) y b c d e f g h j k l m n o p q r s t u v w x y z 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 > table(x)[["g"]] error in table(x)[["g"]] : subscript out of bounds > table(y)[["g"]] [1] 0 just set levels !

html - Jquery arrow keys navigation -

i new programming in jquery. want make page scroll down next "container" class everytime press arrow down, , reverse arrow up. have tried googling lot, couldn't seem find manageable solution. this html code: <div class="containers"> <div class="boxed" class="container"> <p class="overskrift1">internet kriminalitet</p> <div id="demo"></div> </div> <div class="boxed2" class="container"> </div> </div> i want arrow keys navigate between different containers. edit this best jquery code have far: $('body').on('keypress'), (function () { var ele = $(this).closest("section").find(".container"); $("body").animate({ scrolltop: $(ele).offset().top }, 100); return false; }); thank you morten what have is: put event on body li

jquery - Feed Style Similar to this -

i've been pondering on around 3-4 hours , can't wrap head around how it. i've been looking @ this feed , trying replicate wordpress blog i'm working on, i've looked around numerous jquery plugins none seem keep them in rows - appreciated. the problem having feed on link above has lovely , nice laid out feed, it's not cascading pinterest, keen eye might spot each row aligned , start @ same position , end @ same position images variable heights. tl;dr wanting feed similar link supplied. static row height variable image height inside row. any great. the best way make table. <table> <tr> //a table row <td>content</td> <td>content</td> <td>content</td> </tr> </table> then css: table { position:relative; table-layout:fixed; width:100%; margin:1em auto 1em auto; } td { border-color:transparent; width:20%; height:450px;

javascript - ng-switch inside ng-repeat Angularjs -

Image
i have question how use ng-switch inside ng-repeat , use scope switch-on ? example : <div ng-repeat="item in submenu"> <div class="animate-switch" ng-switch-when="{{item.filter}}"> <div class="navbar navbar-default navbar-static-top {{item.filter}}"> <div class="navbar-collapse collapse" id="navbar-{{item.filter}}"> <ul class="nav navbar-nav subnav"> <li ng-repeat="subitem in item.sub" class="items" > <a ng-href="{{subitem.link}}" class="{{selected }}" ng-click="selectfiltersub(subitem.filter)">{{item.name}}</a> </li> </ul> </div> </div> </div>

Python - lists with mathematical operations inside -

how create function takes list alternating math symbols (plus, minus) , integers return result. example, 4, '+', 5, '-', 1 should return 8. i'll give 1 liner. if homework, teacher's going raise eyebrow's @ this. given words = [4, '+', 5, '-', 1] then result = sum(digit * (-1 if sign == '-' else 1) digit, sign in zip(words[0::2], ['+'] + words[1::2])) what we're leveraging here said '+' , '-' operands. type of number sentence can rewritten (+4) + (+5) + (-1) . in other words, view +/- sign indicator, , sum them all. so decomposing above... # extract slice digits digits = words[0::2] # --> [4, 5, 1] # extract slice signs signs = words[1::2] # --> ['+', '-'] # our signs needs have same size digits, there's implicit '+' preceding first digit signs = ['+'] + signs # --> ['+', '+', '-'] # use if else , list comprehensio

php - Symfony2 dublicate the id in 2 fields (id and idbis) with strategy="AUTO" -

i symfony/doctrine duplicate id in 2 different field every time record created. possible in 1 shot (i use stragegy="auto") ? if yes how can this? for instence entity category have 2 attribut id (auto). on named id, other idbis. (in exemple work on entity contains parent , children records, have idparent link children categories parent category) if record parent category, id , idbis same integer: => id=2, idbis=2, idparent = null if record child category (let parent category id=2) then: => id=3, idparent=2, idcategory1=2 that great because then retrieve categories (parent , children) linked category id 2. you should take nested set structures. it's made retrieve sub elements in simple query using bounds. otherwise can creating trigger on insert/update.

android - [LibGDX]Delay between button presses -

im making simple game , have started making each menu. there 3 menus in row - main menu - playher select menu - gamemode menu problem facing atm adding delay between touches. code have uses sprites buttons , detects whether touch point within bounding rectangle. like so: if(gdx.input.istouched()){ cam.unproject(playermenutp.set(gdx.input.getx(), gdx.input.gety(), 0)); if(sprites[1].getboundingrectangle().contains(playermenutp.x, playermenutp.y)){ game.changescreen(2); }} this works first menu since buttons in exact same position on each menu if hold finger on screen skips through menus. i don't know how modify wait until previous touch no longer occurring continue scan one. any appreciated. thanks i suggest use scene2d ui related stuff, it's not hard implement or learn, , easy mantain. anyway if want keep going in way, can this: make screens implement inputprocessor. se

Excel 2010 automation constants not working in Delphi XE7 -

i trying convert program delphi 2010 delphi xe7 (32 bit/windows vcl). code used work in d2010 automated excel via late binding ole gives exception "unable set window state property of application class" in delphi xe7, when app maximized or minimized. i getting constants xlmaximized , xlminimized excelxp unit has these constants: xlmaximized = $ffffefd7; xlminimized = $ffffefd4; however, if use simple constant values -4137 , -4140 program work ok. realize must doing simple wrong. below sample code illustrates problem. tested , works in delphi 2010, not in delphi xe7. suppose must how constants handled in newer versions(?) can point me in right direction? in advance! //xla global variable of type olevariant; //program uses comobj , excelxp unit //this proc runs or connects excel procedure tform3.runexcelclick(sender: tobject); begin try xla := getactiveoleobject('excel.application'); except try xla := createoleobject('excel

c# - Is anyone having trouble Ctrl-R, T running a specific locally highlighted test when it is set to async? -

i noticed today ctrl-r, ctrl-t on highlighted test method in gui not debug test wrote when looks like: [testmethod] public async void test() { await asyncmethod(); } the project builds, test doesn't run. there no fail message or error message found anyplace. if remove async keyword, works fine. what's this? in code, i'm awaiting asynchronous call. don't see why test runner couldn't deal it. edit: after looking @ tests output, message this: uta007: method blah defined in class blah not have correct signature. test method marked [testmethod] attribute must non-static, public, return-type void , should not take parameter. example: public void test.class1.test(). additionally, return-type must task if running async unit tests. example: public async task test.class1.test2() ========== discover test finished: 3 found (0:00:00.1367583) ========== i don't @ it, visual studio wants show me build output , errors more often.

html - Bootstrap 3 offset ignores sizes -

i have offset set medium sized screen offset still occurs when screen in large. here snippet of html, how can solve issue? <div class="col-lg-6 col-sm-12"> <div class="row"> <div class="col-lg-12 col-md-3 col-md-offset-3"></div> </div> </div> in bootstrap, device-size-specific classes affect size of class and higher sizes , unless overridden. so, of course, col-md-offset-3 present in large screens well. can "override" class large screens col-lg-offset-0 . <div class="col-lg-6 col-sm-12"> <div class="row"> <div class="col-lg-12 col-md-3 col-md-offset-3 col-lg-offset-0"></div> </div> </div> from docs : grid classes apply devices screen widths greater or equal breakpoint sizes, , override grid classes targeted @ smaller devices. therefore, applying .col-md- class element not affect styling on medium de

oop - using functions inside javascript constructors -

i need write constructor object gives random value object's color property. wrote var ghost = function() { // code goes here var num = math.floor(math.rand()*4); if(num === 0){ this.color = "white"; } else if(num === 1){ this.color = "yellow"; } else if(num === 2){ this.color = "purple"; } else if(num === 3){ this.color = "red"; } }; i error message test suite on code wars typeerror: object #<object> has no method 'rand' @ new ghost @ test.describe am not allowed use functions inside constructor or there test suite don't understand? the name of function math.random , not math.rand . to interpret error message: typeerror: object #<object> has no method 'rand' first try find object "rand" method trying call. in case, math. verify object in question indeed has method. on unrelated note, selection code can simplified to: var c

Using a java library in Android Studio -

i want use this java library in android studio project. it's java library, not android library. how import java library android studio project can use in android app? add .jar app/libs directory. you should have in build.gradle file, if not you'll need add it: dependencies { compile filetree(dir: 'libs', include: ['*.jar']) }