Posts

Showing posts from September, 2010

Pass Interface to a generic attribute of a class in C#? -

when this: public class ball { iteste<iitem> teste{ get; set; } } i got error: 'iitem' must non-abstract type public parameterless constructor in order use parameter 't' in generic type or method iteste: public interface iteste<t> t : iitem, iequatable<t>, new() { //iteste code } iitem: public interface iitem : iequatable<iitem> { //iitem code } it seems simple question, not find answer. appreciated. remove new() constraints iteste iteste: public interface iteste<t>where t : iitem, iequatable<t> { //iteste code }

reactjs - How to refresh props with React/Redux when user enters a container -

i have competitionsection repeats competitions database. when user clicks on one, redirects him competition page, loads second , renders page details in it. far, good. but when users goes competition section , click on second competition, instantly loads previous competition, 0 loading time. from point of view, failing props of component not updating when render component (from second time). not router problem, first instinct because i'm seeing route.params changing acordingly, actions dispatch change props not dispatching. here's bit of code of said component. class competitionpage extends react.component { componentwillmount() { let id = getidbyname(this.props.params.shortname) this.props.dispatch(getcompaction(id)); this.props.dispatch(getcompmatches(id)); this.props.dispatch(getcompparticipants(id)); this.props.dispatch(getcompbracket(id)); } render() { let { comp, compmatches, compbracket, compparticipants } = this.props ... i tried every lifec

algorithm - Need a faster and efficient way to add elements to a list in python -

i trying create large list of numbers . a = '1 1 1 2 2 0 0 1 1 1 1 9 9 0 0' (it goes on ten million). i've tried these methods: %timeit l = list(map(int, a.split())) 4.07 µs per loop %timeit l = a.split(' ') 462 ns per loop %timeit l = [i in a.split()] took 1.19 µs per loop i understand 2nd , 3rd variants character lists whereas first integer list, fine. number of elements gets on ten million, can take 6 seconds create list. long purposes. tell me more faster , efficient way this. thanks in plain python, not using third-party extension, a.split() ought fastest way split input list. str.split() function has 1 job , specialized use.

java - Organize methods by return type or argument? -

i'm having bit of hard time articulating problem. different types, considerations there how organize methods traverse relationships convert different type? while being forgiving precise modelling, example, imagine there 3 classes many-to-many relationships between 1 another: car , garage , parkingpass . a car can have multiple parking passes parking passes allow cars park in garages the same pass can used multiple garages the same pass can used multiple cars i'll use pseudo-java syntax, don't think language specific (or oop specific matter, although more relevant there). if wants find out garages car can park in, following methods seem equivalently valid: asking car object garages: car { collection<garage> getgarages(); } asking garage object garages given car: garage { collection<garage> for(car); } either way, object need move through parkingpass class resolve relationship mapping, there's no direct conversion between 1 o

python - Django Rest Framework - return list of Users or single User with ModelViewSet based on Permissions -

i have seen several posts similar question, none solve issue. i using django rest framework's modelviewset. have 2 views, detail view , list view. i want if superuser accesses list view, gets users. if normal user accesses list view, can see himself. if superuser accesses detail view, can view user. if normal user accesses detail view not his, gets authentication error. i first attempted permissions only, realized query set of list view has_object_permission not run allowing authenticated non-superuser view everyone. because object permissions run command. attempted override get_object, get_object not called list view made no difference. tried override get_quertyset without get_objects, broke detail view. what understand get_object called first detail view, calls get_queryset if don't override either of them. if override get_queryset, breaks normal functionality of detail view , get_object (it doesn't filter based on primary key). there must more going on behi

ruby - Rails / CanCan allowing update of a single attribute for CarrierWave attachment -

in rails app have client model has_many :client_attachments . want non-admin users able create attachments, don't want them update other attributes client . i'm using cancan role authorization , carrierwave attachments. currently i'm doing: in models/client.rb : class client < applicationrecord has_many :client_attachments accepts_nested_attributes_for :client_attachments, allow_destroy: true end in models/client_attachment.rb : class clientattachment < applicationrecord mount_uploader :file, clientattachmentuploader belongs_to :client end in ability.rb : can [:update], client can [:create, :update, :destroy], clientattachment, :user_id => user.id in clients_controller.rb : private def client_params if current_user.admin? params.require(:client).permit(:name, :address, :etc, client_attachments_attributes: [:id, :client_id, :file, :user_id]) elsif current_user.user? params.require(:client).permi

python - Class Variables vs Methods in Django Class Based Views -

i self-taught amateur ever trying understand fundamentals of python, django , programming in general. i'm looking understand issue having. so have class class contractsview(inventoryview): template_name = "contracts.html" page = "contracts" primary_table, secondary_table = build_contracts_tables(**{"commodity": none}) and uses following function: def build_contracts_tables(**kwargs): print('fire') primary_table_query = purchase.inventory.current_contracts_totals(**kwargs) primary_table_fields = ("total_meats", "total_value", "meat_cost") primary_table_html = build_table([primary_table_query,], *primary_table_fields) if primary_table_query else err_str secondary_table_query = purchase.inventory.current_contracts(**kwargs) secondary_table_fields = ("invoice", "supplier", "variety", "meats", "value", "meat_cost"

Unable to Start Neo4j -

i using neo4j 3.2.2 on linux java 1.8 (open jdk). when try start neo4j using "systemctl start neo4j" - executing doesn't give me output. when execute "systemctl status neo4j" see has failed start database. error when check status when check journalctl, see enter image description here any appreciated. thanks , precise comment tom geudens. comment helped me. use filezilla move files (specifically, conf file) between windows , linux. once, edited , saved file (vi editor) within linux environment, up.

form submit - How do I display text above after submitting it into a textbox HTML -

Image
i'm trying create area in can enter text text box , display written text onto box above in html. i'm new html appreciated. drew beautiful picture of i'm trying make. the best way deal situation use javascript or jquery javascript's library itself. let me show how should in jquery <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgfzhoseeamdoygbf13fyquitwlaqgxvsngt4=" crossorigin="anonymous"></script> <script> $(document).ready(function(){ $("#form-to-be-submitted").click(function(){ $(".whatever-styling-you-want").html($("#textbox").val()); }); }); </script> <div class="whatever-styling-you-want"> </div> <!-- text box , submit button --> <div> <input type="text" id="textbox" placeholder="please input text here..."

eclipse - Drools can't find kjars referenced by the projects POM file -

i'm having hard time trying run spring boot application drools projects dependencies. the project spring boot application , references 2 different drools projects. runs fine on eclipse, when try run using java -jar , drools can't find 1 of 2 related projects. i describe steps application doing , guesses problem source make easier follow. step 1 : during spring cdi, call kieservices retrieve 1 of defined kiebases: kiecontainer kcontainer = kieservices.factory.get().getkieclasspathcontainer(); return kcontainer.getkiebase("kbase-common-rules"); the result of classpath search shown in logs: classpathkieproject:131 : found kmodule: jar:file:/home/credisfera-services/target/credisfera-services-3.3.0-snapshot.jar!/lib/credisfera-cep-1.0.1.jar!/meta-inf/kmodule.xml kierepositoryimpl:113 : kiemodule added: zipkiemodule[releaseid=br.com.credisfera:credisfera-services:3.3.0-snapshot,file=/home/credisfera-services/target/credisfera-services-3.3.0-snapshot.jar]

node.js - Original IP not passed to container on single container Docker image on AWS Elastic Beanstalk -

i have node.js server inside docker container on aws elastic beanstalk. have noticed if try access user's ip address via request headers, don't user's actual remote ip address. instead seems ip address of docker container - 172.19.0.1 . i'm sure there simple how docker or elastic beanstalk configured need change desired behaviour - don't know needs change. something in dockerfile? flag or in docker build command before push & deploy container? configuration on aws in elb or elastic beanstalk? would appreciate pointers on start! with hapi node.js, request headers not available request.info request.headers . using request.info returns network level informations. should use request.headers[ 'x-forwarded-for' ] request level informations. try displaying request.headers key-value pairs discover key linked value containing ip address want find.

c# - Proper way of storing ListView items' data - ResourceDictionary? -

i complete beginner c#, forgive me if question seems trivial. i have simple menu listview. every item in menu has text , image. should these values kept in resourcedictionary or should create list of these items somewhere in class , bind them? if never needed reuse piece of ui code, put inside page's resources; if reused on page, put in resource dictionary. ui code belongs xaml, it's clearer read (and view in vs designer) <button content="add" /> than var button = new button() { content = "add" }; this.mygrid.children.add(button);

html - Back button loaded page, not query -

i'm rendering content on site via queries , regenerating content on passed value. page not reload rather reinitializes js content. when go use button on browser, cycles through url query until initial url reached. what's best practice around happening? thanks!

python 3.x - Dice Rolling Simulator -

i making dice rolling simulator in python play dnd. new python please don't make fun of me if code bad. import random while 1 == 1: dice = input("what kind of dice roll?: ") # asking kind of dice roll (d20, d12, d10, etc.) number = int(input("how many times?: ")) # number of times program roll dice if dice == 'd20': print(random.randint(1,21) * number) elif dice == 'd12': print(random.randint(1,13) * number) elif dice == 'd10': print(random.randint(1,11) * number) elif dice == 'd8': print(random.randint(1,9) * number) elif dice == 'd6': print(random.randint(1,7) * number) elif dice == 'd4': print(random.randint(1,5) * number) elif dice == 'd100': print(random.randint(1,101) * number) elif dice == 'help': print("d100, d20, d12, d10, d8, d6, d4, help, quit") elif dice == 'qui

javascript - How to link to portfolio page with a specific filter? -

i'm playing portfolio section in page looks this: $(function() { var selectedclass = ""; $(".fil-cat").click(function() { selectedclass = $(this).attr("data-rel"); $("#portfolio").fadeto(100, 0.1); $("#portfolio div").not("." + selectedclass).fadeout().removeclass('scale-anm'); settimeout(function() { $("." + selectedclass).fadein().addclass('scale-anm'); $("#portfolio").fadeto(300, 1); }, 300); }); }); body { max-width: 900px; float: none; margin: auto; } #portfolio { margin: 1rem 0; -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; -webkit-column-gap: 1rem; -moz-column-gap: 1rem; column-gap: 1rem; -webkit-column-width: 33.33333333333333%; -moz-column-width: 33.33333333333333%; column-width: 33.33333333333333%; } .tile { -webkit-transform: scale(0); transform:

r - How can I hide the red line in timevis? -

Image
i'm working timeline using timevis don't know how hide red line marks current date. the red line indicates current time on timeline. however, once add data timeline, red line no longer there. nonetheless, line must exist points current time on timeline. from docs ?timevis : # basic timevis() # minimal data timevis( data.frame(id = 1:2, content = c("one", "two"), start = c("2016-01-10", "2016-01-12")) ) see timevis - create interactive timeline visualizations in r: advanced ecamples to customize of timeline. by default, timeline show current date red vertical line , have zoom in/out buttons. can supply many customization options timevis() in order right (see ?timevis() details). see files in www folder of repo guide customization. https://github.com/daattali/timevis/tree/master/inst/example/www

why3 - Need help defining a machine integer -

i'm using mach.int library in specification (see this question ), , i'm trying define constant of type int32 : let constant_out1: int32 = 1 in … however, when analyzing this, why3 returns message: this term has type int, expected have type int32 i noticed bounded_int (which int32 instantiates type int32 ) has following in it: val of_int (n:int) : t requires { "expl:integer overflow" in_bounds n } ensures { to_int result = n } however, not seem able use cast 1 int32 . example, if use: let constant_out1: int32 = int32.of_int(1) in … i message unbound symbol 'int32.of_int' . i've tried many permutations of this, without success. can provided guidance how tell why3 want 1 of type int32 ?

generics - java type inference in builder pattern -

i want create parameterized (generic) class mytype<t> , builder. builder have methods ignore type t , methods use type. seems using pattern have repeat t declaration: how omit declaration? | v mytype<string> mytype = builder.<string>of() .method1(argument_can_be_of_any_type) .method2(argument_must_be_of_type_t = string) .build(); is possible use java syntax tricks or other design patterns omit second type declaration , make api more user friendly? example: list<string> alist = lists.emptylist(); or list<string> alist = new linkedlist<>(); i don't want enforce order of methods in builder i've reworked things bit since original answer didn't work advertised. (thanks shmosel spotting problem, , daniel pryden suggested solution.)

excel vba - Creating a PowerPoint in vba by calling "slide" subroutines -

i creating powerpoint in vba, there lot of slides in it. thinking create macro calls lot of subroutines. within subroutines, actual "slide code" run. however, have created powerpoints of code in same subroutine. took shot @ , below code creates want. question is, public , private variables , use of "dim". bad code if put of in 1 module , use bunch of subroutines? or should separate on modules? prefer not have define each variable such ppslide , pppres, open suggestions. looking ideas on how set up. public ppapp powerpoint.application public pppres powerpoint.presentation public ppslide powerpoint.slide sub createpres() dim pptextbox powerpoint.shape dim slidescount long set ppapp = new powerpoint.application ppapp.visible = true ppapp.activate set pppres = ppapp.presentations.add slidescount = pppres.slides.count set ppslide = pppres.slides.add(slidescount + 1, pplayouttitle) ppslide.shapes(1).textframe.textrange.text = "hello world" ppslide.shape

lapply - R how to change dafaframe column name by using listname -

i have list y below. want change first column name of each data frame (rn) name of data frame (sa, ta). y1. > y $sa rn x1 x2 x3 x4 x5 x6 1: timepoint 0 3.75 4.25 4.5 4.75 5 2: plot 234 304 285 279 256 238 $ta rn x7 x8 x9 x10 x11 x12 1: timepoint 0 5 4.25 3.75 4.75 4.5 2: plot 208 299 272 261 254 218 > y1 $sa sa x1 x2 x3 x4 x5 x6 1: timepoint 0 3.75 4.25 4.5 4.75 5 2: plot 234 304 285 279 256 238 $ta ta x7 x8 x9 x10 x11 x12 1: timepoint 0 5 4.25 3.75 4.75 4.5 2: plot 208 299 272 261 254 218 those list elements data tables, should simple y1 <- map(setnames, y, "rn", names(y)) replace "rn" 1 if want index first column instead of column name "rn".

javascript - having problems setting a member variable on an ng2 component -

i'm having problems setting member variable on ng2 component. in component below, i'm trying set service results member variable. updatesearchresults1() sets member variable expected updatesearchresults2 delegates promise processsearchresults returns error: "typeerror: cannot set property 'blogpostlistitems' of null." understanding these 2 implementations functionally same. why can set this.blogpostlistitems updatesearchresults1() whereas error this.blogpostlistitems null updatesearchresults2()? import { component, oninit, viewchild, elementref } '@angular/core'; import { router } '@angular/router'; import { blogservice } '../../services/blog.service'; import { bloglanding } '../../entities/blog-landing'; import { response } '@angular/http'; @component({ selector: 'blog-landing', templateurl: '../../../ng2/templates/blog-landing.component.html' }) export class bloglandingcomponent impleme

tensorflow - Optimizing a subset of a tensor in Tensor Flow -

i have free varaible (tf.variable) x, , wish minimize error term respect subset of tensor x (for example minimizing error respect first row of 2d tensor). one way compute gradients , change gradient 0 irrelevant parts of tensor , apply gradients. way? you can use mask , tf.stop_gradient selectively make variable non-trainable: tf.stop_gradient(mask*x) . value in matrix mask 1 should denote parts apply gradient , 0 otherwise.

telegram bot prefill text for user to edit -

telegram bot sends me message text snippet, want edit, , send bot further processing. copy , paste takes time. typing message anew takes time. ideally i'd press inline button "edit" on bot's message , message text appear in reply input box editing.(a message id attached reply somehow plus). i tried use deep linking parameters other /start*, doesn't seem work. can use bot api (or other telegram api) have text ready editing in input box? it's unpossible in official apps yet. question working drafts - there no methods in both api create them or clear. nevertheless, fork official app stored on gihub , implement need if prefer hard way, compared copy/past solution seems more easier, isn't it? upd i can offer new idea how solve problem - hope helpful. this switch_inline_query_current_chat field of inlinekeyboardbutton . attach inline button messages need edit. set text field gotten recieved message , after pressing text i

join - How can work output on python? -

i want made script storage capacity modify have problem. my script has below error: traceback (most recent call last): file "test.py", line 20, in <module> mod_f.write(','.join(line) + '\n') typeerror: sequence item 3: expected string, float found below script. mod_f = open("mod_c_vol_size.txt", 'w') mod_f.write("vserver,volume,aggregate,total,avail,node,savea,saved,savec,snap,tused\n") unit = ['tb', 'gb', 'mb', 'kb', 'b'] open("find_c_vol_modify.txt", "r") f: next(f) line in f: if len(line.strip()) != 0: line = line.split(',') out = [] l in line[3:5] + line[6:11]: l = l.replace('\n','') try: ind = [unit[i] in l in range(5

javascript - Using knockout to progressively load an array of video metadata -

my page needs display grid of n video previews. browsers can have ~5-6 active connections given domain. prevent "waiting socket connection..." issue, i'm attempting progressively load video metadata. i have following: <!-- ko foreach: videos() --> <video data-bind="attr: {src: mediapath, preload: $parent.preloadcount() > $index() ? 'metadata' : 'none'}, event: {loadedmetadata: $parent.incrementpreloadcount}"></video> <!--/ko--> within viewmodel: vm.preloadcount = ko.observable(4); vm.incrementpreloadcount = function () { feedvm.preloadcount(feedvm.preloadcount() + 1); }; the idea being each time video's metadata loaded, loadedmetadata event fires off increment progressively switches none metadata . the problem videos reevaluating every increment, refetching src each time preloadcount updates. how can prevent "switched" videos being re-evaluated? resort

javascript - how to know if website is using cookies or not? -

i've requirement verify website need test. website shall not use cookies my question , how find out smartway if any whether entire website using cookies or not? i know way i'll disable cookies in browser , while accessing website browser should shout out cookies not enabled in browser. believe i'll have check each-and-every webpage confirm whole website not using cookies. you can run document.cookie in console read cookies accessible location. you open dev tools , view them there. in chrome, cookies can found in application tab of dev tools. more info

java - Spring Data JPA Criteria Join with child -

i working spring boot - spring data jpa in postgresql database. need know if possible spring data jpa. have classes these: @entity @inheritance(strategy = inheritancetype.table_per_class) public abstract class product { @id private string id; private string name; ... } @entity public class fridge extends product { private integer capacity; ... } @entity public class offer { @id private long id; .... @jsonignoreproperties({"hibernatelazyinitializer", "handler"}) @manytoone(fetch = fetchtype.eager) @joincolumn(name="product_id") private product product; ... } when trying build criteria specification, try do: @override public predicate topredicate(root<offer> root, criteriaquery<?> criteriaquery, criteriabuilder criteriabuilder) { string key; join<offer, fridge> join = root.join("product", jointype.left); path<string> expression = join.get(key); ... i

php - Overriding joomla core email template -

is there way can override core email template admin received once guest sent message on contact form? i customize , feel of received email. @ least can include email header , footer. i think easy override in joomla layouts , templates not possible. if want modify emails, can... change language files or make language overrides modify email (not you´re looking for) write own system plugin modifies email methods. email methods stored in /libraries/joomla/mail/mail.php . here can wrap template around content. use extension catches templates , wraps them templates joomla email beautifier . i´m you, hope in future there easy native option override mail templates.

How to manipulate a CSV file for Matplotlib using Python -

Image
if have following data , want draw multiple-line graph representing following [a snippet of] data, in format in csv file: the data: 1216,c210,3610 1217,c210,1863 1218,c210,2419 1224,c210,861 1299,c210,2517 1216,c211,3593 1217,c211,1849 1218,c211,2410 1224,c211,859 1299,c211,2504 1216,c212,3595 1217,c212,1847 1218,c212,2407 1224,c212,860 1299,c212,2501 the goal: i visually represent data as: q: how can manipulate csv data can create such graph matplotlib , python? the sticky: have done far got stuck: def processing_and_graphing(m_list, c_list): open(csv_dump, 'r') input_csv_dump_file: input_csv = csv.reader(input_csv_dump_file, delimiter=',', skipinitialspace=false) open(csv_temp, 'w', newline='') output_csv_temp_file: machine in m_list: write_into_csv_file = csv.writer(output_csv_temp_file, delimiter=',', quoting=csv.quote_minimal) row in input_csv: if row[0]

.htaccess - HTACCESS VARIABLE Regarding issue -

i have website, in making url clean of htaccess. example. example.com/fathers/?n=name open example.com/father/name i doing of below code. rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^father/([^\/]+)/(\/|)$ fathers/index.php?n=$1 [qsa] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^father/([^\/]+)(\/|)$ fathers/index.php?n=$1 [qsa] my question is, how make example.com/anythinghere/?n=name open example.com/anythinghere/name how can this? you can use rule in .htaccess : rewriterule ^anythinghere/([^/]*)$ /anythinghere/?n=$1 [l] just make sure clear cache before testing it.

How to place and order django objects from 2 models into template table? -

Image
i'm trying place "information" table has rows , columns called "categories" , "stylings". model , view shown below. model.py class headings(models.model): categories = models.charfield(max_length=20) stylings = models.charfield(max_length=20) class information(models.model): headings = models.foreignkey(headings) info = models.charfield(max_length=100) views.py class informationlistview(listview): model = information def get_context_data(self, **kwargs): context = super(informationlistview, self).get_context_data(**kwargs) context['categories_ordered'] = headings.objects.order_by('categories') context['stylings_ordered'] = headings.objects.order_by('stylings') return context so far i've been able start template table with <table> <tr> <th>styles</th> {% cols in categories_ordered %} &

JavaScript giving element key to array -

i'm kinda lost in figuring out logic javascript. currently, i'm extracting every element , pushing them array. i'm having hard time when want access object element. this data in text file: 1#1#test#tombstone#8#yes 2#3#test2#tombstone3#81#yes when access first array rowcells[0] . returns me 1 2 which first column itself. i hoping return first row. intended functionality follows: 1- push array 2- giving element key first column no,type,header,content,score 3- search row based on element key such type=2 4- search based on type , no, show content. any suggestions? in advance. <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script> <script> $.ajax({ url: 'content.txt', datatype: 'text', }).done(successfunction); function successfunction(data) { var allrows = data.split(/\r?\n|\r/); var table = '<table>'; (var singlerow = 0; sin

c# - How to create a new Task of type Task? -

i have: async task dowork() { console.writeline("do async work in method"); } task task = new task(dowork); //line x task.start(); task.wait(); line x gives compilation error: cs0407 'task form1.dowork()' has wrong return type how instantiate new task dowork ? i able use following gives me different set of problems. task task = dowork(); task.wait(); i want avoid second method. how instantiate new task of type async task @ line x? since dowork() has return type of task , declaration needs instance of generic task<tresult> - i.e. task<task>

knockout.js - Aggregate multiple max KO extend validations -

i using ko extend validation validate, trying follows. ko.extend not support multiple bindings same type (max in case) , adds first rule. there way conditionally pass params function? or way out writing custom validation? mymodel.prop2.extend({ max: { onlyif: function () { var test = mymodel.prop1() != undefined && mymodel.prop1() !== "percentage"; return test; }, params: 100000 } }).extend({ max: { onlyif: function() { return mymodel.prop1() != undefined && mymodel.prop1() === "percentage"; }, params: 100 } }); found solution, .extend({ validation: [{ validator: function (val, someotherval) { if (mymodel.prop1(

defining haskell functions that have Maybe in signature -

i'm unclear how write function signatures in haskell, using maybe . consider: f :: maybe -> maybe f = \a -> main = print (f (just 5)) this works why can't function signature this? f :: maybe -> maybe since f takes maybe type , returns maybe type. related: if wanted have maybe type more specific , maybe int , why doesn't work? f :: maybe int -> maybe int f = \a -> main = print (f (just (int 5))) (i'm running code using runhaskell test.hs ) seems confused type variables. first of all, in f :: maybe -> maybe f = \a -> the a 's in first line have nothing a 's in second line, have written: f :: maybe -> maybe f = \x -> x or even f :: maybe foo -> maybe foo f = \bar -> bar the a 's variables stand types. f here declaring f has whole bunch of types @ once: f :: maybe int -> maybe int f :: maybe string -> maybe string f :: maybe (maybe bool) -> maybe (maybe bool) ... and o

python - How do you iterate through groups in a pandas Dataframe, operate on each group, then assign values to the original dataframe? -

yearcount = df[['antibiotic', 'order_date', 'antiyearcount']] yeargroups = yearcount.groupby('order_date') year in yeargroups: yearcount['antiyearcount'] =year.groupby('antibiotic'['antibiotic'].transform(pd.series.value_counts) in case, yearcount dataframe containing 'order_date', 'antibiotic', 'antiyearcount'. have cleaned 'order_date' contain year of order. want group yearcount years in 'order_date', count number of times each 'antibiotic' appears in each "year group" assign value yearcount's 'antiyearcount' variable. help! i think need add new column order_date groupby , possible use size instead pd.series.value_counts same output: df = pd.dataframe({'antibiotic':list('accbbb'), 'antiyearcount':[4,5,4,5,5,4], 'c':[7,8,9,4,2,3],

hadoop - spark read data from hbase, did workers need to get paritions data from remote driver program? -

spark read data hbase,such //create rdd val hbaserdd = sc.newapihadooprdd(conf, classof[tableinputformat], classof[org.apache.hadoop.hbase.io.immutablebyteswritable], classof[org.apache.hadoop.hbase.client.result]) for example, hbaserdd has 5 partitions, executor on worker partition data compute, must data remote driver program? (not read hdfs, each worker hadoop slave has hdfs file replication) spark integrated hbase , data locality principles same in hadoop map-reduce jobs: spark try assign input partition (hbase region) worker on same physical machine, data fetched directly without remote driver.

java - JPA: how to set up key for historizing entities -

within jpa in spring boot / spring data, want set entity class. the business requirement historize processing of documents exist once per year each. the processing performed in bulk: documents processed together: there one processingtimestamp documents in database each processing sequence. later on, want access processed document, keep processed documents reference. i see following alternatives: use composite key @id private string documentid; @id private string yearofdocumentcreation; @id private java.sql.timestamp processingtimestamp; use auto generated key @id @generatedvalue(strategy = generationtype.auto) private long id; private string documentid; private string yearofdocumentcreation private java.sql.timestamp processingtimestamp; which alternative better/best practise regarding handling (e.g. storing list of documents bulk read before database , avoiding duplicates in database) performance or miss other alternatives/aspects? i recom

r - Finding best reciprocal matches -

this problem of finding best reciprocal matches between 2 sets of strings mapped 1 against other. what have 2 data.frame 's hold results of mapping first set against other ( df1 below) , of other mapping direction ( df2 below). the mapping obtains score . in addition, every string has parent , , several different strings have same parent . here simulated data: library(dplyr) set.seed(1) #generate first string set mapping data.frame df1 <- data.frame(query = paste("a",unlist(sapply(1:5,function(i) rep(i,ceiling(runif(1,1,3))))),sep="."),stringsasfactors = f) #add hits , scores df1 <- do.call(rbind,lapply(unique(df1$query),function(q) { dplyr::filter(df1,query == q) %>% dplyr::mutate(hit = paste("b",sample(5,nrow(.),replace = f),sep="."),score = runif(nrow(.),0,100)) })) #add parents df1 <- left_join(df1,data.frame(query=unique(df1$query),parent = paste("p.a",sample(3,5,replace=t),sep="."

ios - NSLayoutConstraint change not working -

i have code below changing nslayoutconstraint delay. value changing without delay , animation. please let me know issue code. self.heightconstraint.constant = 100; [self.animatingview setneedsupdateconstraints]; [uiview animatewithduration:3.0 delay:1.0 options:uiviewanimationoptioncurveeaseout animations:^{ [self.animatingview layoutifneeded]; } completion:^(bool finished) { }]; try calling layoutifneeded method on superview of animatingview.

java - Sum Aggregations in MongoDB Using Spring Data -

this data {"intentid" : "a1", "like" : "y"} {"intentid" : "a1", "like" : "y"} {"intentid" : "a1", "like" : "n"} {"intentid" : "a2", "like" : "y"} {"intentid" : "a2", "like" : "n"} {"intentid" : "a2", "like" : "n"} {"intentid" : "a2", "like" : "n"} and mondodb script run good. here code. db.getcollection('test').aggregate( [ { $project: { intentid: 1, likey: { $cond: [ { $eq: [ "$like", "y" ] }, 1, 0 ] }, liken: { $cond: [ { $eq: [ "$like", "n" ] }, 1, 0 ] } } }, { $group : { _id

objective c - SIngle master view controller and multiple single view controller using UISplitViewController -

i new in ios, i try work uisplitviewcontroller. single master view , single detail view in work add second detail view controller, it's not work first detail view controller it's override on first detail view controller, try it's display on right side of first detail view controller not override on first detail view controller. below display to try code first prepareforsegue method can't work: - (void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender { if ([segue.identifier isequaltostring:@"action"]) { nsindexpath *indexpath = [self.tableview indexpathforcell:sender]; viewcontroller *view = (viewcontroller *)[[segue destinationviewcontroller] topviewcontroller]; view.imagename = [_images objectatindex:indexpath.row]; view.navigationitem.leftitemssupplementbackbutton = yes; } } second didselectrowatindexpath it's work override first detail view controller: - (void)tableview:(uitablev

stored procedures - SQL Server - How would I insert a RANK function to rows that are already sorted in ranked order? -

so, apparently, have right according professor except 1 column shows rank of columns shown in code below. i'm thinking that, essentially, has show row numbers off left side in own column. here instructions: the sales manager create report ranks products both total sales , total sales quantity (each own column). create stored procedure returns following columns 2 new rank columns added. product name | orders count | total sales value | total sales quantity i know doesn't have column in assignment description, guess need it. here have far: use onlinestore go create proc spmanagerproductsalescount begin select p.name 'product name', isnull(count(distinct o.orderid), 0) 'orders count', sum(isnull(o.ordertotal, 0)) 'total sales value', sum (isnull(oi.orderitemquantity, 0)) 'total sales quantity' product p inner join orderitem oi on p.productid = oi.productid inner join orders o on o.order

java - How to get only the required tags from XML using JAXB -

This summary is not available. Please click here to view the post.

Deleting tomcat log files automatically for every 2 days. -

i automatically delete tomcat log files every 2 days.to that, wrote script in /etc/logrotate.d/tomcat not working.i using ubuntu 16.04 dist. /opt/tomcat/logs/*.*.* { daily missingok rotate 2 missingok nomail postrotate /usr/bin/find /opt/tomcat/logs/ -name "*.*.*" -type f - mtime +2 -exec rm {} \; endscript } suggest me answres delete tomcat logs. please help. just use simple cronjob execute simple bash-file removes files in wished directory https://wiki.ubuntuusers.de/cron/ rm -r /opt/tomcat/logs/* #or whatever want delete

c# - How to Count my pass fail test case and print at the end of execution -

i have multiple test cases , want write common method can count fail or pass test case , print total pass , fail test case @ end of execution. instead of using class count total pass , fail cases, can implement method this: int pass=0; int fail=0; for(int i=0;i<testcasescount;i++) { //read input using console.readline(); //check whether test case pass or fail , appropriately increment counter } //executed after loop i.e. test cases console.writeline(pass); console.writeline(fail);

module - Changes in Python scripts are not accepted -

i'm new python, think question fundamental , asked few times before cannot find (maybe because not know how search problem). installed module in python (reportlab). wanted modify python script in module seems python interpreter not notice updates in script. ironically import successful although python should not find package because deleted before. python uses cache or other storage modules? how can edit modules , use updated scripts? from saying, downloaded package , installed using either local pip or setup.py . when so, copies files python package directory. after install, can delete source folder because python not looking here. if want able modify, edit, , see changes, have install in editable mode. inside main folder do: python setup.py develop or pip install -e . this create symbolic link python package repository. able modify sources. careful changes effective, have restart python interpreter. cannot import again module or whatever else.

ios - How to call function from one viewcontroller to another controller? -

Image
settingsstore.h @interface settingsstore : iaskabstractsettingsstore { @public nsdictionary *dict; nsdictionary *changeddict; } - (void)removeaccount; @end menuview.m -(ibaction)onsignoutclick:(id)sender { settingsstore *foo = [[settingsstore alloc]init]; [foo removeaccount]; [self.navigationcontroller pushviewcontroller:foo animated:yes]; exit(0); } i want call removeaccount function menuview.m . getting error. how fix , call removeaccount. there few mistakes in code please find them below. [foo removeaccount]; calling method correct [self.navigationcontroller pushviewcontroller:foo animated:yes]; not correct because settingsstore not subclass of uiviewcontroller subclass of uiviewcontroller can pushed navigation controller exit(0); calling method not recommended apple

java - When I put ParcelFileDescriptor into my MediaExtractor setDataSource(),cause IOException -

i video data datagramsocket,and it's byte[] know,and can't decode byte[] exactly. have used mediaextractor work. here code: @override public void run() { eosreceived = false; try { socket.receive(packet); parcelfiledescriptor pfd = parcelfiledescriptor.fromdatagramsocket(socket); filedescriptor fd = pfd.getfiledescriptor(); mextractor.setdatasource(fd, 0, packet.getdata().length); (int = 0; < mextractor.gettrackcount(); i++) { mediaformat format = mextractor.gettrackformat(i); string mime = format.getstring(mediaformat.key_mime); if (mime.startswith(video)) { mextractor.selecttrack(i); mdecoder = mediacodec.createdecoderbytype(mime); try { log.d(tag, "format : " + format); mdecoder.configure(format, surface, null, 0 /* decoder */); } catch (illegalstateexception e) {

ActiveRecord Association Through that has many foreign_key in Joins table -

below example teacher has_many students student has_many teachers student has_many books book has_many colors class teacher < applicationrecord has_many :meetings has_many :books, through: :meetings end class student < applicationrecord has_many :meetings has_many :teachers, through: :meetings end class book < applicationrecord has_many :meetings has_many :colors, through: :meetings end class meeting < applicationrecord belongs_to :teacher belongs_to :student belongs_to :book belongs_to :color end i have problem result shows on index page not right. for example: @teacher.name @teacher.students.each |s| s.name s.books.each |b| book.name b.colors.each |c| c.name end end end please help! thanks, helen ta.

enterprise - Barcode scan from mobile in odoo 10 -

how can implement bar code within odoo mobile browsers can read bar code , odoo captures bar code details. for example, @ first scan bar code mobile, attach bar code detail relevant sales order. after attaching bar code, sales orders appears automatically when user scans bar code. we using enterprise version odoo 10.x purpose. flow: scan barcode -> attach bar code sales order -> sales order uniquely identified bar code -> whenever user scans bar code, related sales order opens automatically.

c# - Is there anything similar to DirectoryInfo for registry paths? (Same functions and attributes) -

due fact i'm using directoryinfo class every directory path have, decided use in order handle registry paths. mean, registry path nothing other directory path because both divided folders referenced backslashes. so, if pass string @"hkey_local_machine\hardware\devicemap\scsi\scsi port 0" new instance dir of type directoryinfo , print out dir.root my output d:\ . according this link, output should hkey_local_machine . or wrong asserting can handle registry path directory path? if doesn't work registry paths - there similar directoryinfo registry paths? best if it's contained in netcore app 1.1 framework target framework! edit: okay, experimented bit , seems directoryinfo needs drive letter @ beginning of every path or else search directory in applcation folder. directoryinfo.root returns correct string. question is: there similar directoryinfo registry paths?