Posts

Showing posts from 2012

android - convert protobuff class as model and store its value using realm -

i generating protobuf class using squareup wire protobuf libary here proto file syntax = "proto2"; package squareup.dinosaurs; option java_package = "com.squareup.dinosaurs"; message dinosaur { // common name of dinosaur, "stegosaurus". optional string name = 1; // urls images of dinosaur. repeated string picture_urls = 2; } and here auto generated code // code generated wire protocol buffer compiler, not edit. // source file: dinosaur/dinosaur.proto @ 8:1 package com.squareup.dinosaurs; import com.squareup.wire.fieldencoding; import com.squareup.wire.message; import com.squareup.wire.protoadapter; import com.squareup.wire.protoreader; import com.squareup.wire.protowriter; import java.io.ioexception; import java.lang.object; import java.lang.override; import java.lang.string; import java.lang.stringbuilder; import java.util.list; import okio.bytestring; public final class dinosaur extends message<dinosaur, dinosaur.builder&g

Getting all of the variables of a dart class for json encoding -

i have class class person{ string _fn, _ln; person(this._fn, this._ln); } is there way list of variables , serialize it? want make tojson, wanted have generic enough such key variable name, , value value of variable name. in javascript like: var myobject = {}; //.... whatever want define as.. var tojson = function(){ var list = object.keys(myobject); var json = {}; ( var key in list ){ json[list[key]] = myobject[list[key]] ; } return json.stringify(json); } dart doesn't have built in functionality serialization. there several packages different strategies available @ pub.dartlang.org. use mirrors, harmful client applications because results in big or huge js output size. new reflectable packages replaces mirrors without disadvantage don't know if serialization packages ported use instead. there packages use code generation. there question answer lists available solutions. i'll when i'm back.

video - Why is youtube's "still" screen blurry? -

on youtube video @ bottom of this page , screencap blurry once hit play, it's clear. there way fix this? okay, think i'm understanding question... i'm not 100% sure. (you're asking why it's blurry in "thumbnail"/screencap before hit play, correct?) my guess youtube's embedding using frame @ beginning of video as it's fading in . if video, suggestion have eliminating delete video, go editing, , remove fade-in effect @ beginning of video. if youtube grabbing frame beginning of video i'm positive fix way. hope helps! best of luck!

postgresql - Django model reference like loop? -

i want know how django model circular reference... like, class family(models.model): fname = models.charfield(max_length=30,unique=true) member_id = models.foreignkey(member) class member(models.model): name = model.charfield(max_length=30,unique=true) family_id = models.foreignkey(family) these 2 familiy , member models. want circular reference... main goal bind member under each families. that's works fine. query parse family table , want main member of particular family like, want family head each family means shall do? explain circular reference or better method available that. or shall foreign key both. please solution. that's not right approach, shouldn't have circular reference in models. if want have relationships that, depend on requirement: if 1 person can has 1 family, put family foreign key in member model. if 1 person can have multiple families, put member manytomany field in family model. also, don't name fie

matlab - Caffe using hdf5 layer and imagedata input layer together in train_val.proto -

i using hdf5 data layer reading input images(around 30000) have , metadata images. i unable crop-flip data augmentation, since when use centre crops, storing data of 1500 images leads around 1.5 gb h5 file, total size of hdf5 dataset(30 h5 files) becomes ~40 gb, , can not use augmentation hdf5 dataset large. so, thinking if use imagedata layer reading images , hdf5 data layer metadata, problem can solved. didn't find material on this. possible so? yes is, thought getting error due else in proto file, below input layers proto layer { type: "hdf5data" name: "data" top: "meta" hdf5_data_param { source: "/path/to/train.txt" batch_size: 50 } include { phase: train } } layer { name: "data" type: "imagedata" top: "x" top: "labels" include { phase: train } transform_param { mirror: true crop_size: 227 mean_file: "data/ilsvrc12/imagenet_m

.net - WCF service multiple behaviors -

Image
i've done wcf, it's been while, , i've never had configure service scratch. apparently, while can have 1 behavior configuration , it's possible attach multiple behaviors wcf service: servicehost servicehost = new servicehost(typeof(services.fooservice), serviceendpointuri); webhttpbinding binding = new webhttpbinding(); serviceendpoint sep = servicehost.addserviceendpoint(typeof(contracts.ifooservice), binding, string.empty); sep.behaviors.add(new webhttpbehavior()); sep.behaviors.add(new mycustomendpointbehavior()); i'm wondering: is possible attach multiple service behaviors service? ... or, matter, multiple endpoint behaviors? or limited @ 1 of each? that's not clear me snippet (which closest thing answer i've turned far in search). is possible via configuration (rather programmatically)? you create named behavior list behaviors sub-items of named behavior. <system.servicemodel> <behaviors> <e

mesos - How to update the number of topic partitions on dcos-kafka? -

i'm using dcos-kafka on mesos , cannot figure out how update number of partitions topic. seems can update topic using dcos kafka update [topic-name] [parameter]=[value] unfortunately, can't figure out parameter updating number of partitions be. possible?

Dictionary corrupt the name of the key [Python] -

my problem when input accent dictionary stores different keyname, replace accented character wit character code. i'm new here accept every help. thank help! #!/usr/bin/python # -*- coding: utf-8 -*- products={} try: prodnum = int(raw_input(u"hány terméket kíván felvenni listába?\r\n")) count = 0 while (count < prodnum): prodname = raw_input(u"kérem üsse %d. termék nevét!\r\n" %(count + 1)) encodedname = prodname.decode('utf8') print(encodedname) prodval = int(raw_input(u"kérem üsse %d. termék darabszámát!\r\n" %(count + 1))) products[encodedname] = prodval count = count + 1 except valueerror: print (u"ide egy számot kellett volna írni. :)\r\n") print(products) output: hány terméket kíván felvenni listába? 1 kérem üsse 1. termék nevét! qpa kóla qpa kóla kérem üsse 1. termék darabszámát! 2 {u'qpa k\xf3la': 2}

Unusual JavaScript for loop with xml in Blockly -

i'm working on project google's blockly, parts of documentation incomprehensible. can me understand end condition of following loop (xml = allxml[i])? var allxml = blockly.xml.workspacetodom(workspace); var allcode = []; (var = 0, xml; xml = allxml[i]; i++) { var headless = new blockly.workspace(); blockly.xml.domtoworkspace(headless, xml); allcode.push(blockly.javascript.workspacetocode(headless)); headless.dispose(); } i imagine loop exit when allxml[i] undefined, how can iterate through xml object this? seems returning undefined , skipping loop entirely. thanks help definitions of function can found @ https://code.google.com/p/blockly/source/browse/trunk/core/xml.js?r=1614 and doc page pulled https://developers.google.com/blockly/custom-blocks/code-structure?hl=en i not find code in repo on github , guess bit older example in docs. but if have @ blockly.xml.workspacetodom() function's implementation, see similar thing there. var blo

javascript - ESLint's "no-undef" rule is calling my use of Underscore an undefined variable -

i using grunt build tool , eslint linting tool app working on. using underscore node package, , have made use of in app. unfortunately, when run eslint on code, thinks _ undefined variable in following line: return _.pluck(objects, namecolumn); this error giving me: 78:21 error "_" not defined no-undef i prefer not disable no-undef rule eslint, , have tried installing underscore plugin, still receiving error. if else has ideas try this, appreciative! if there further information can give helping me figured out, let me know! the official documentation should give idea on how fix this. the easiest fix add /* global _ */ at top of file. but since you'll have each new js file, can annoying. if using underscore often, i'd suggest add globals .eslintrc file , example: { "globals": { "_": false } } and save .eslintrc in project root, or optionally in user home directory. although latter not recommen

sql - How to update datetime field to contain only the date or time part -

how can update field contains date/time information contain date part of data? following: update [events] set [event_date] = dateadd(dd, 0, datediff(dd, 0, [event_date]) event_num = '8592' i need equivalent set time component? you can truncate timestamp date or time casting it: cast(event_date date) cast(event_date time) this documented in interbase 6 embedded sql guide, section casting sql datatypes datetime datatypes on page 188. manual available firebird website. this works in dialect 3. if still working dialect 1 database, need use intermediate cast varchar (with locale specific length of 10 or 11) in maxims answer strip off time portion. because date in dialect 1 timestamp (and not date).

Extract image from wpf image control and save it to a png file on my local PCc# -

i have image control in wpf c#. <image x:name="icon01" mousedown="icon_mousedown" cursor="hand" source="favicon\01.png" height="48" width="48" margin="10"/> how can save image (favicon\01.png) file on pc? use c# .net 4.0. use icon01.source ( imagesource ) create filestream via pngbitmapencoder , here example using savefiledialog private void icon_mousedown(object sender, mousebuttoneventargs e) { try { var savefiledialog = new savefiledialog() { filter = "image files (*.bmp, *.png, *.jpg)|*.bmp;*.png;*.jpg" }; if (savefiledialog.showdialog() == true) { var encoder = new pngbitmapencoder(); encoder.frames.add(bitmapframe.create((bitmapsource)icon01.source)); using (filestream stream = new filestream(savefiledialog.filename, filemode.create

sorting - WPF DataGrid loses virtualization when sorted by specific columns -

i using wpf datagrid bound custom itemssource implements ilist (and not ienumerable). custom itemssource performs data virtualization , loads pages of items needed. mydatagrid inherits datagrid , overrides handling of datagrid sort methods can maintain data virtualization while sorting. have ui virtualization turned on mydatagrid. when run application, mydatagrid displays fine, tells me have 20,000 items, , asks itemssource first 20 or items. can click on column headers sort various columns , again itemssource has reload first page of 40 items because mydatagrid has asked refresh first 20 or so. but, when click on last name column sort, mydatagrid loses ui virtualization , asks itemssource load every single item though needs first 20 or so. can watch asks every single item index (this[0]). i've tried researching icollectionview, ui virtualization, , data virtualization , thing i've read seems may apply regarding multiple row selection (at datagrid row request pat

c++ - Mutex causes access violation when debugging - works fine otherwise -

the following bar() function has never caused me trouble: class foo { public: void bar(); private: std::mutex mutex_; }; void foo::bar() { std::unique_lock<std::mutex> lock{ mutex_ }; // ... } now, have unit test cover bar() - using gtest. test passes fine, when try debug exception thrown: read access violation in line unique lock. the code breaks in mutex.c : if (mtx->thread_id != static_cast<long>(getcurrentthreadid())) mtx->_get_cs()->lock(); here _get_cs() returns uninitialized. questions: 1) can me understand or point me right direction? 2) need worry this? what works , doesn't work: running application command line application: works (no access violation) debugging application visual studio: works (let's me step on line unique lock) running application windows service , attaching debugger: works running unit test within visual studio (with resharper): works running unit test command line: works debugging

java - How to recognize a person from an Image in OpenCv -

i made program detects face image: import org.opencv.core.core; import org.opencv.core.mat; import org.opencv.core.matofrect; import org.opencv.core.point; import org.opencv.core.rect; import org.opencv.core.scalar; import org.opencv.highgui.highgui; import org.opencv.objdetect.cascadeclassifier; class detectfacedemo { public void run() { system.out.println("\nrunning detectfacedemo"); cascadeclassifier facedetector = new cascadeclassifier("c:\\users\\hm\\documents\\netbeansprojects\\vision\\src\\lbpcascade_frontalface.xml"); mat image = highgui.imread("c:\\users\\hm\\downloads\\john-lennon.jpg"); matofrect facedetections = new matofrect(); facedetector.detectmultiscale(image, facedetections); system.out.println(string.format("faces detected: %s ", facedetections.toarray().length)); (rect rect : facedetections.toarray()) { core.rectangle(image, new point(rect.x, rect.y), new point(rect.x + rect.width, rect.y + rect.height), new sca

javascript - Is there a way hide database's map data when displaying entire map to a user -

i building website allows users find locations , areas around world based on data other users allowed submit. have database containing of location data, latitudes , longitudes. have implemented google maps javascript api, static api simple things in website. allow users view of database's map points on world map user drag , zoom different areas view , select pin more information location. there example on google's site shows how here . if i'd hide data client, rather passing them entire xml file locations? i supposed make more difficult intercept of coordinates , save them computer. might subjective question because of novice understanding of , understand trade-off type situation. so basically, don't want make easy take data @ once? a straight-forward strategy provide search , filter controls interact discrete apis (ajax services). have api provides summary data how many points in 1 area , provide guided search constraints let user drill down further

ios - Variable going back to 0 when label saved -

i made app save label can make go or down 1 number in app. if lose out of app , open up, if make label go again resets 0 , goes one. because have set variable value zero. here code: @iboutlet var goal: uilabel! @ibaction func player1button(sender: anyobject) { nsuserdefaults.standarduserdefaults().setvalue(goal.text!, forkey:"firstgoal") } var goal1 = 0 @ibaction func goalup(sender: anyobject) { goal1++ goal.text = "\(goal1)" } override func viewdidload() { super.viewdidload() goal.text = (nsuserdefaults.standarduserdefaults().objectforkey("firstgoal") as? string) } im saving goal number calling later in text. please show me way fix adds on previous number. in viewdidload() add goal1 = int((nsuserdefaults.standarduserdefaults().objectforkey("firstgoal") as? string)!) this set int variable using keep track of goals correct value when app loads. setting text la

run docker commands from command prompt versus jenkins script -

i have test ubuntu server docker-machine installed. have number of docker containers running on servers. including jenkins container. run jenkins following command docker run -d --name jenkins -v /var/run/docker.sock:/var/run/docker.sock -v $(which docker):/usr/bin/docker --restart=always -p 8080:8080 -v ~/jenkinshome:/var/jenkins_home docker-jenkins i working on managing images through jenkins. can start 1 of containers via jenkins shell script. 1 container fails appears start in script (i docker ps after docker run in script). however, container stops after script completes. using same docker run command works on command prompt, fails in jenkins script: sudo docker run -d --net=host -v ~/plex-config:/config -v ~/media:/media -p 32400:32400 wernight/plex-media-server i have double checked folder permissions , correct. can direct me possible reasons run command failing in jenkins, not @ command prompt? using docker ps =a able id stopped container. using d

c# - Getting access to MainWindow.xaml.cs properties from outsourced ResourceDictionary -

i working on new usercontrol lately , have make customizable, wasn't problem until figured out, have put datatemplates in external resourcedictionary in order make control more customizable. so have? have customizable usercontrol, able call constructor so-called "templatepath" resourcedictionary loaded in usercontrol.resources . works fine! so what's problem? datatemplates, in sepperate resourcedictionary should able bound properties of usercontrol.xaml(.cs) in order check i.e. if specific object selected. but that's not problem. furthermore usercontrol has predefined commands , should able bound datatemplates. wasn't problem before when datatemplates still in usercontrol.xaml obviously. the bad thing is, have outsource datatemplates , because control available users .dll , in case, there wouldn't opportunity add custom templates afterwards. does have idea of how implement this? in advance! €dit : be, example, resourcedictionary, dynami

java - How to get return type of constructor lambda -

i wondering if possible return type of supplier assigned constructor. e.g. supplier<foo> sfoo = foo::new; how "foo.class" supplier? have been using typetools solve problem other things. this works, example: supplier<foo> sfoo = () -> new foo(); class<?> fooclasss = net.jodah.typetools.typeresolver.resolverawarguments(supplier.class, sfoo.getclass())[0]; // fooclass == foo.class but if assign supplier like: supplier<foo> sfoo = foo::new , return type cannot resolved... any thoughts? don't have use typetools btw... seems parsing method references not supported typetools. there's open issue similar problem. in general such feature quite fragile runtime lambda representation not specified , implementation dependent. may break 1 day. if need class suggest passing actual class<?> argument.

python - Issue in generating all permutations of columns in a dataframe in Ipython -

i working in ipython , trying generate permutations of columns present in dataframe . issue have 15 columns in dataframe , code doesn't reach end , keeps on executing. here current code: df = pd.read_csv(filename, sep = ';', error_bad_lines=false) def all_perms(str): if len(str) <=1: yield str else: perm in all_perms(str[1:]): in range(len(str)): #nb str[0:1] works in both string , list contexts yield perm[:i] + str[0:1] + perm[i:] allperms_list = [] p in all_perms(df.columns[:len(df.columns)]): allperms_list.append(p) i followed this example . have 16 core , 32gb memory system , have been running code last 1.5 hours still executing , doesn't reaching end. there fundamental issue in code have? how can make run faster without affecting final result? read itertools.permutations option. how can modify current code include itertools.permutations , achieve same result?

yii2 - Yii 2 FileValidator -

i'm new yii 2 , reading documentation , experimenting. using activeform , trying file upload, keep getting error "please upload file" though appears file has been uploaded when step through code. model code public function upload() { if ($this->validate()) { $destination = yii::getalias('@app/uploads'); $this->brochure->saveas($destination . '/' . $this->product_id . '.' . $this->brochure->extension); return true; } else { return false; } } controller code public function actionupdate($id) { $model = $this->findmodel($id); if (yii::$app->request->ispost) { $model->load(yii::$app->request->post()); $upload = uploadedfile::getinstance($model, 'brochure'); if ($upload !== null) { $model->brochure = $upload; $result = $model->upload(); } // if model

Efficiently get largest 3 integers in C++ Linked List (unsorted) -

i heard there std functions give largest n integers of array, how linked list? i think solution have few loops iterate on linked list, seems if there simpler solution in c++ libraries. thanks. i if can't use data structure: typedef std::list<int> intlist; instlist list = <your_values>; int top[3]; (size_t = 0; < 3; i++) top[i] = std::numeric_limits<int>::min(); intlist::iterator it, end; (it = list.begin(), end = list.end(); != end; ++it) { const int& value = *it; if (value > top[2]) { top[0] = top[1]; top[1] = top[2]; top[2] = value; } else if (value > top[1]) { top[0] = top[1]; top[1] = value; } else if (value > top[0]) { top[0] = value; } }

c++ - Why can't I call a class's non-default constructor in another file? -

this question has answer here: “undefined reference to” in g++ cpp 2 answers i new c++. have started writing class called row, , trying call non-default constructor create row object in separate main.cpp file, keep getting error not understand. can explain me i've done wrong? here 3 files: row.h #ifndef row_h #define row_h #include<vector> #include<iostream> class row { std::vector<int> row; public: // constructor row(std::vector<int> row); }; #endif row.cpp #include<vector> #include<iostream> #include "row.h" // constructor row::row(std::vector<int> row_arg) { row = row_arg; } main.cpp #include<vector> #include<iostream> #include "row.h" using namespace std; int main() { vector<int> v = {1, 2, 3, 4}; row row(v); return 0; } the error re

multisite - How to use an IP address for a multi-site in Drupal 8? -

this url seems claim it's not possible. workarounds on site doesn't work, , information dated. question is... why work in drupal 8, when put in sites.php file: $sites = array( // url ==> path 'test.localhost' => 'default', 'test2.localhost' => 'somepath', ); but not this: $sites = array( // url ==> path 'test.localhost' => 'default', '127.0.0.1' => 'somepath', ); and how make work? it known bug dont go way. have setup additional virtual host , setup drupal there. can partially link site , modify configuration - filesystem related opration not drupal nor apache/nginx operation.

java - How to apply operator precedence for calculator? Library? Is ANTLR the right library to use? -

i'm trying make calculator app applies operator precedence. however, haven't been able find clear references on how apply in java. understand have use recursive descent parser (unless there's method or better way this). if so, better me code parser myself? or should utilize library. while browsing forums, came upon answer suggested using antlr find seems language grammar rather applying operator precedence in expressions. if it's better me code recursive descent parser myself, please link me references on how so? if should use library, please link me 1 examples how apply operator precedence? i'm not sure how apply antlr operator precedence , haven't seen clear references in docs either on how apply leaves me doubts whether or not right library use. thanks! i don't see why mixing antlr operator precedence. antlr parser (and lexer) generator. use bison/flex same result. now, precedence if given grammar (there might error, i've se

Magento events are not firing -

i have weird situation. trying hook on sales_order_save_after event won't work. debug doing mage::log() in mage.php see events firing. suprirsing, printing resource_get_tablename , core_collection_abstract_load_before few times (24 lines altogether) , nothing else. make more confusing, when save product (by going manage products) prints big list of events (as expected). idea how debug this? want send email out on sales_order_save_after event. just confirm, have logging enable under system->configuration->developer->logging

java - Convert string to JSON and get value -

i have string: {"markers":[{"tag":"1","dep":"2"}]} how convert json , value tag , dep ? you need jsonobject this jsonobjectrequest jsobjrequest = new jsonobjectrequest(request.method.get,url, null, new response.listener<jsonobject>() { @override public void onresponse(jsonobject response) { string tag, dep; jsonarray jarray = response.getjsonarray("markers"); jsonobject msg = jarray.getjsonobject(0); tag = msg.getstring("tag"); dep = msg.getstring("dep"); } }

elasticsearch - Aggregations on an array in a nested query -

i trying query users have @ least 1 color in common particular user , have been able unable figure out how aggregate results can user along colors have in common. part of document sample user follows: { // ... other fields "colors" : [ { "id" : 1, "name" : "green" }, { "id" : 7, "name" : "blue" } ] } this query getting colors in common user has colors red, orange , green: { "query": { "nested": { "path": "colors", "scoremode": "sum", "query": { "function_score": { "filter": { "terms": { "colors.name": [ "red","orange","green" ] } }, "functions&

java - Is it possible to use Predicate<T> when creating queries for Jinq? -

my question jinq , , using version 1.8.9 latest release. i trying use jinq implementing general reusable jpa (java persistence api) typesafe query method java 8 lambda (functional interface) predicate method parameter. unfortunately, can not make work java 8 predicate instead can use similar predicate type (provided jinq) method parameter, avoid dependencies jinq in method signatures, , therefore prefer java 8 predicate if possible? jinq provides functional interface "where": package org.jinq.orm.stream; public interface jinqstream<t> extends stream<t> { @functionalinterface public static interface where<u, e extends exception> extends serializable { public boolean where(u obj) throws e; } i can implement query method want (but undesirable coupling) using above interface in method signature this: public list<t> select(jinqstream.where<t, exception> wherepredicate) instead of above coupling jinq in method signa

ruby on rails - switching from pg gem to mysql, causing error -

my app using pg gem faced issues switched pg mysql when run bundle cause error. my gem file source 'https://rubygems.org' # bundle edge rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.0.13' # use pg database active record # gem 'pg' gem 'mysql2' # use scss stylesheets gem 'sass' gem 'sass-rails', '~> 5.0' # use uglifier compressor javascript assets gem 'uglifier', '>= 1.3.0' # use coffeescript .js.coffee assets , views gem 'coffee-rails', '~> 4.0.0' # user authentication gem 'devise', '~> 3.2' # use materialize css gem 'materialize-sass' gem 'material_icons' # use jquery javascript library gem 'jquery-rails' # build json apis ease. read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 1.2' #for authorization gem 'the_role' group :doc # bundle e

Wordpress user roles - gravity form User Registration - conditionally add_role -

Image
my wordpress site has 2 types of user. when sign up, nominate user type, , want assign 1 of 2 roles, depending on user type are. my user registration page has radio button, new user chooses whether between 2 types of registration. lets call registration types 'cat' , 'dog' purpose of discussion. i have added cat/dog radio button gravity form, user can select 'dog' - radio button defaults 'cat'. field 'registeras'. gravity form user registration allows me set role on new user. choose 'dog' new registrations the gravity form used gather new user data has confirmation redirect them cat-or-dog page: the cat-or-dog page has template assigned - let's call 'cat-or-dog.php'. contains code: <?php /* template name: cat or dog */ if (isset($_get['regas'])) { if ($_get['regas']=='dog') { global $current_user; var_dump($current_user->roles); $current_user->add_role('dog'); echo "

excel - Handle many ComboBox_Change Event -

well i'm new in vba programming. i'm creating form helps me quotations, , there part of form shows items i've registered, this: my form comboboxes so purpose of comboboxes change or delete correponding item according option choose, , have lot of them in userform, making hard create many combobox event programs (like combobox1_change, combobox2_change, ... combobox50_change). , then, main question is: how in vba without loosing lot of time making same code different objects? create 1 code comboboxes. i understand can in way below, i'm sure has better way do. sub combobox1_change() call mycode end sub sub combobox2_change() call mycode end sub sub combobox50_change() call mycode end sub sub mycode() i=1 50 if controls("combobox" & i).value = "change" call mysecondcode end if next end sub i spent 30 minutes searching question, didn't find me. hope guys understood question. in advance. update: axel richter,

Can't log into ASP.NET MVC site once on IIS -

i got asp.net mvc application hosted on local windows/iis server. went login page when try log in says, error: error occurred while processing request this non-descript... my gut feeling when did web deploy, didn't deploy localdb(?) users' credentials stored. before try re-deploy entire app, i'd see if can offer guidance. on right track? there other possible causes/solutions should investigate? i'm using default registration/login system in project start with, , woks fine in vs. did regular web deploy iis server, , site works fine until go log in. fixed: issue caused (as suspected) inaccessibility of localdb users' credentials stored. vs uses light db instead of making install sql express or alternative (much iis express works better debugging full iis). when push application iis vs, database wasn't connecting. found other question, , top answer fixed issue. how deploy asp.net mvc 4 application using localdb local iis on wind

Fast append before string on each new line -

i have couple of pretty large text-files (1 gb each) have 1 generated word on each line. want append string before each of generated words. whether it's java, c#, c, c++, or ruby doesn't matter. while can't program myself, can compile , run it. example: file.txt: aoos ahsd gaata sdffg output: appendaoos appendahsd appendgaata appendsdffg any welcome! depending on tools have available, can use sed , awk or perl : sed 's/^/append/' inputfile >outputfile awk '{print "append"$0}' inputfile >outputfile perl -pne 's/^/append/' inputfile >outputfile if want write own program, can filter programs relatively easy in c: #include <stdio.h> int main (void) { int ch, lastch = '\n'; while ((ch = getchar()) != eof) { if (lastch == '\n') printf ("append"); putchar (ch); lastch = ch; } return 0; } just compile as, example, myprog , run: mypr

django - Should Entry.author be a ForeignKey to User or UserProfile? -

in django, want filter queryset using list of user s active user following . i've opted extend user class rather replace custom class, although i'm not sure right choice. hence have userprofile class, has manytomanyfield other userprofiles, , onetoonefield user . my queryset looks entry.objects.filter(author__in=request.user.userprofile.following.all()) author foreignkeyfield user rather userprofile , i'm change entry.author point userprofile s instead. so questions are, in decreasing priority: is right have author userprofile instead? because have entry.author.user.username not intuitive. might better replace builtin user class custom class has data need? is right userprofile 's following manytomanyfield other userprofile rather user ? since users can follow each other , entries people, makes totally sense make author userprofile both models logically in same level

Laravel 4: Dynamic db selection using Capsule -

just trying understand how capsule works in laravel. works correctly defined, however, new page opened again take backs old connection information instead of new connection defined. i believed setasglobal() makes available particular session atleast, however, guess conceptually wrong here. it nice if can guide through right way make new database connection available globally via capsule, there various other ways, seems more promising. it nice if explain following commands in more simpler way (the comments written per in documentation, however, above nice): // set event dispatcher used eloquent models... (optional) $capsule->seteventdispatcher(new dispatcher(new container)); // set cache manager instance used connections... (optional) $capsule->setcachemanager(...); // make capsule instance available globally via static methods... (optional) $capsule->setasglobal(); // setup eloquent orm... (optional; unless you've used seteventdispatcher()) $capsule-&

python - How to check if an input matches a set of desired values without repeating myself? -

this question has answer here: how test 1 variable against multiple values? 16 answers i want able this, inputs of 1, "d" or "dog" call do_something() , whereas other input call do_something_else() . command = input("type command") if command == (1 or "d" or "dog"): do_something() else: do_something_else() currently, not work, because python evaluating truthiness of (1 or "d" or "dog") , true , of course. then, since command true string, do_something called. i know how 1 way: if command == 1 or command = "d" or command = "dog" . works fine; however, involves lot of repetition, , i'm sure there must way shorten that. i suppose make list of valid commands, valid_commands = [1,"d","dog"] , check if command in valid_commands , seems workaro

MYSQL for selecting values from table and show with comma separator -

i have 2 tables: sales table =============================== id cust_id total_price =============================== 1 1 1000 2 2 1500 sales_item table ====================================================== id sales_id cust_id product quantity ====================================================== 1 2 2 pen 2 2 2 2 pencil 3 3 1 1 book 2 4 1 1 pencil 2 i need query these 2 tables inorder following result: ========================================= sales_id cust_id product ========================================= 2 2 pen,pencil 1 1 book,pencil can me query these 2 tables inorder above result?? i tried using group_concat. hers have

android - How to get text's coordinate inside a TextView? -

i have situation:there 2 textviews, one's gravity left|centervertical , other's right|centervertical. when wraping them, texts must wrap positions exactly, left left ,right right. achive this, have coordinate of text inside textview, can calculate offset, how text's coordinate inside textview without inner padding? i think there no solution text's coordinate inside textview without inner padding value. if want text's coordinate, should calculate using view's location , inner padding value. public float gettextpositionx(textview textview) { return textview.getx() + textview.getpaddingleft(); } public float gettextpositiony(textview textview) { return textview.gety() + textview.getpaddingtop(); }

android - Implementing BootstrapNotifier on Activity instead of Application class -

i using altbeacon library beacon detection. after checking out sample codes on beacon detection, implement interface bootstrapnotifier on application class instead of activity , used detecting beacons in background. have noticed beacon detection in background stops when bootstrapnotifier implemented on activity . don't want app detect beacons launched hence have not implemented bootstrapnotifier on application class.i have specific requirement want beacons detected after particular activity launched , thereafter beacons should detected in background. altbeacon library have provisions achieving this? thanks. sample code yes, possible detect beacons in background after activity starts, still need make custom application class implements bootstrapnotifier . the reason necessary because of android lifecycle. activity may exited backing out of it, going on new activity , or operating system terminating in low memory condition if have taken foreground. in lo

java - Spring security 4.x login redirects to '.../favicon' instead of expected URL -

i have spring security java configuration @configuration @enablewebsecurity public class blogwebsecurityconfigurer extends websecurityconfigureradapter { @override public void configure(websecurity web) throws exception { web.ignoring().antmatchers("/resources/**"); } @override protected void configure(httpsecurity http) throws exception { http .authorizerequests() .antmatchers("/").permitall() .antmatchers("/resources/**").permitall() .antmatchers("/detail/**").permitall() .antmatchers("/post/**").hasrole("admin") .anyrequest().authenticated() .and() .formlogin() .loginpage("/login").defaultsuccessurl("/")

java - Tasks in Spring -

i have application (spring 4 mvc+ jpa + mysql+maven integration example using annotations) , integrating spring hibernate using annotation based configuration; , want create task in order use in controller having task: @configurable public class smssendertask implements runnable { protected static final logger logger = loggerfactory.getlogger(smssendertask.class); @autowired smssender smsservice; private string msg; private string to; public smssendertask(string msg, string to) { super(); this.msg = msg; this.to = to; } @override public void run() { try { smsservice.sendsms(msg, to); } catch (unsupportedencodingexception e) { logger.error(e.getmessage()); } catch (clientprotocolexception e) { logger.error(e.getmessage()); } catch (ioexception e) { logger.error(e.getmessage()); } } } and other one public class smss

exception for filling matrix in C# -

i have code block below, when i'm filling matrix , if put enter or space instead of numbers mistake, program stop, know needs add exception don't know or how add trycatch in code or should write in body of trycatch code: int row = 0; int col = 0; int[ , ] matrix1; row = convert.toint16( console.readline( ) ); col = convert.toint16( console.readline( ) ); matrix1 = new int[ row, col ]; console.writeline( "enter numbers" ); ( int = 0; < row; i++ ) { ( int j = 0; j < col; j++ ) { matrix1[ i, j ] = convert.toint16( console.readline( ) ); } } if want display message , exit can use int row = 0; int col = 0; int[ , ] matrix1; int row = 0; int col = 0; int[ , ] matrix1; row = convert.toint16( console.readline( ) ); col = convert.toint16( console.readline( ) ); matrix1 = new int[ row, col ]; console.writeline( "enter numbers" ); try { ( int = 0; < row; i++ ) { ( int j = 0; j < col; j++ ) { m

c++ - Visual Studio Programming -

i have assignment not understanding. focusing on for, while, , while statements chapter. question goes follows... "the payroll manager @ kenton incorporated wants program allows him enter unknown number of payroll amounts each of 3 stores: store 1, store 2, , store 3. program should calculate total payroll , display te result on screen." i lost on start. guess confusing me "an unknown number of payroll amounts". don't know how make user transistion entering next stores payroll amounts. question says nothings using sentinel value, doesn't not use sentinel value. any or advice appreciated!!!! since there 3 stores, may want keep payroll amounts each separate though specs don't seem care. way can use special store code of 0 indicate you're done. pseudo-code follows: store1 = 0 store2 = 0 store3 = 0 print "enter store, or 0 end: " input storenum while storenum <> 0: print "enter payroll amount: "

python - Get xpath of a link in a webpage containing "sometext" -

i'm using scrapy (web crawling framework). there way can xpath of element (containing "sometext") in web page can extract elements similar xpaths? don't want xpaths hardcoded because crawling multiple websites. i'm new scrapy , have been searching days , can't find :( you have explicitly specify element want scrape either use xpath or regular expression or library beautifulsoup . 1 way of not explicitly specifying xpath traverse dom , extracting elements need. in case need kind of mechanism identifying elements want scrape. should write different spiders scraping different websites. scraping multiple website single spider make task harder , not practice either. for deploying , running spiders can scrapyd

sql - Postgres select (group by type) -

this question has answer here: grouped limit in postgresql: show first n rows each group? 5 answers i have table like: id name type rating 1 name1 1 98 2 name2 1 17 3 name3 2 77 4 name4 2 53 5 name5 2 23 6 name6 4 64 7 name7 3 78 8 name8 3 56 9 name9 3 22 10 name10 4 56 11 name11 4 99 . ... . .. how can select table, , example (2,3...etc, n) rows of each 'type' highest rating? result example(for 2 rows): id name type rating 1 name1 1 98 2 name2 1 17 3 name3 2 77 4 name4 2 53 7 name7 3 78 8 name8 3 56 6 name6 4 64 11 name11 4 99 . ...

.net - "Could not resolve coreclr" path on Ubuntu 14.04 -

tl;dr i'm following documentation @ http://dotnet.github.io/getting-started/ ubuntu 14.04. when run dotnet run outputs could not resolve coreclr path , immediatly exit non 0 return code, , can't find in documentation i'm supposed do. more details actually, unexpected occured before that: though added deb [arch=amd64] http://apt-mo.trafficmanager.net/repos/dotnet/ trusty main sources, there's not dotnet package. there's dotnet-dev package, it's package installed. when run dotnet new , dotnet restore , or dotnet compile , seems ok. when run locate coreclr find several files match. in particular there's /usr/share/dotnet-dev/runtime/coreclr directory several .dll s , .so s in it. there's $home/.dnx/packages/runtime.ubuntu.14.04-x64.microsoft.netcore.runtime.coreclr/1.0.1-rc2-23616/runtimes/ubuntu.14.04-x64/native/libcoreclr.so file use dotnet-nightly . tried, still working. dotnet not installing , dotnet-dev broken. sou

jquery - Remove class not working -

why removeclass function not working in case? button turn grey-background once not active. add class seems work fine. $(".tiles").click(function() { var divname = this.value; $(this).addclass("active") $("#material" + divname).fadein('3000').siblings('.material').hide(); $(this).siblings('.tiles').removeclass("active") }); .material { display: none; } .active { background: red; color: #13223d; border: 1px solid #13223d; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='type' id='type3'> <h3>1.2.valj material</h3> <div class='tile_btn'><span id='marmorskivorcount'>0</span> <button class='tiles' type='button' name='material' value='1'>marmorskivor</button> </div