Posts

Showing posts from July, 2011

c# - FileStream Cannot Access File Because It is Being Used by Another Process -

i have looked @ number of different posts, including the process cannot access file because being used process , ioexception: process cannot access file 'file path' because being used process , , better way of invoking thread , logging text file in c# i might missing simple, reason cannot figure out how safely write file in async method. making call web api, , when response comes in, want write file. code follows: static class program { private static object locker = new object(); static void main() { string line; streamreader reader = new streamreader(@"..\..\source.tsv"); int counter = 0; while((line = reader.readline()) != null) { if(++counter % 100 == 0) { console.writeline(counter); } string response = makerequest(line.trim()).result; if(response.length == 0)

How to avoid data loss in Spark Structured streaming when defining structure -

i have simple employee json string coming kafka, , have defined structured below, if of additional fields come in not able access like, "ssn field" showed in sample json. there way can put not-defined fields in key-value map. i don't want use infer schema option. please don't recommend answer public static void main(string[] args) throws exception { string brokers = "quickstart:9092"; string topics = "simple_topic_6"; string master = "local[*]"; sparksession sparksession = sparksession .builder().appname(simplekafkaprocessorext.class.getname()) .master(master).getorcreate(); sqlcontext sqlcontext = sparksession.sqlcontext(); sparkcontext context = sparksession.sparkcontext(); context.setloglevel("error"); list<structfield> employeefields = new arraylist<>(); employeefields.add(datatypes.createstructfield("firstname", datatypes.stringtype

java - Spring-Social Dependency not found -

i wanted add spring-social-facebook dependency. worked latest release 2.0.3 <dependency> <groupid>org.springframework.social</groupid> <artifactid>spring-social-facebook</artifactid> <version>2.0.3.release</version> </dependency> but when want add newer version (not release milestone) <dependency> <groupid>org.springframework.social</groupid> <artifactid>spring-social-facebook</artifactid> <version>3.0.0.m3</version> </dependency> then maven not find files. did forget anything? https://mvnrepository.com/artifact/org.springframework.social/spring-social-facebook for interested in whole pom.xml : <?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.or

angular - aot requires "component-relative" template urls? -

aot requires "component-relative" template urls i'm not sure what's meant this. can here provide additional insight on this? here's example of how ng2 app structured: ng2 => components test-component.ts => templates test.component.html the template referenced within component this: @component({ selector: 'test', templateurl: '../../ng2/templates/test.component.html' }) is example of proper component-relative template url or need change in way in order support aot? if i'm referencing template url in appropriate way what's common scenario in templateurl structure work jit not aot?

java - What is the purpose of adding a positive variable? -

this question has answer here: what purpose of java's unary plus operator? 7 answers i in java1 semester, , asked teacher question, not answer, because didn't know why. or rather couldn't think of purpose serve. let that, when setting variables a=5 , b=-4 . , wanted know value of a+b set system.out.println . i a + b , a + + b , means add positive b . although b negative positive variable still negative 4. however, if change equation a - - b , should come out b being positive 4. so question, purpose of creating equation positive variable if positive variable, variable. since opposite valid (adding negative such + - b) sign plus doesnt affects value.

c# - target .net framework class library with System.ServiceModel dependency from a .net core application -

it should possible reference .net framework class libraries .net core 2 projects in visual studio 2017 runtime exception when trying reference class library dependent system.servicemodel. create “console app (.net core)”. visual studio set target framework ".net core 2.0". create “class library (.net framework)”. visual studio set target framework ".net framework 4.6.1". reference “system.servicemodel 4.0.0.0” class library. fill class1 in class library following: public class class1 { public void test() { system.servicemodel.endpointaddress address = new system.servicemodel.endpointaddress(""); } } reference class library console app. main method of console app call test method in class1: class program { static void main(string[] args) { new class1().test(); } } build , run. exception thrown test() method tried executed: system.io.filenotfoundexception occurred hresult=0x80070002 message

angular - parent-component-binding with *ngIf on a shared service is not updated when triggered from child component -

i have parent , child component. parent component has menu. when child component says this.service.ismenuvisible(false) menu still visible in parent component. no error. afair angular checks updates parent down children components, means try change expression after parent component checked... how should correctly fix scenario shared singleton service? export class routerservice { public id: number = 0; constructor(private router: router,private route: activatedroute) { this.router.events.subscribe(event => { if (event instanceof routesrecognized) { if (event.url == "/projects/create") { console.log(event.url) this.setismenuvisible(false); } else { console.log(event.url); this.setismenuvisible(true); } var first = event.state.root.firstchild.firstchild; var id = first && event.state.root.firstchild.firstchild.params['id']; this.id =

c++ - CUDA: access value from thread based on a warp -

i'm working on domain specific language(dsl) embedded in c++. supports gpgpu backend via cuda c++. let me illustrate i'm trying do: double * out = new double[100]; double * = new double[100]; reducer r; //init values out <<= reduce(a, r); //syntax provided dsl this performs following: for (i = 0; < 100; i++) { // reducer r provides mapping given i, in terms of custom iterator (j = r.start(i); j != r.end(i); j = r.next(i)) { out (i) = out(i) + a(j); } } this straightforward on cuda backend achieve. assume i've syntax keyword called mapped_value() provides value based on reducer r included particular j in mapping or function helps validate given (i,j) pair. out <<= reduce(a * mapped_value(), r); //syntax provided dsl this doesn't seem straightforward achieve on cuda backend without storing o(n^2) elements every (i,j) pair. cuda executes warps of 32 threads. there way can access values on these 32 threads, thereby

css - Chrome bug: lose space between inline elements inside display:table -

it seems there bug in chrome: removes spaces between inline elements inside parent display:table. <div style="display:table;"> <span>text1</span> <span>text2</span> </div> edge/firefox display space without problem. ideas workarounds? you can use non-breaking space html character entity &nbsp; . <div style="display:table;"> <span>text1</span>&nbsp;<span>text2</span> </div> which space between items on browsers.

c++ - What is object slicing? -

someone mentioned in irc, google doesn't have answer. "slicing" assign object of derived class instance of base class, thereby losing part of information - of "sliced" away. for example, class { int foo; }; class b : public { int bar; }; so object of type b has 2 data members, foo , bar . then if write this: b b; a = b; then information in b member bar lost in a .

Java garbage collector fails to clean up memory while loading ontology files -

i facing issue of java.lang.outofmemoryerror in application every time try load , process bunch of .owl files. have 500 odd .owl files in directory , load them 1 one memory using loadontologyfromontologydocument() method of owl api inside for loop. however, after method loads few ontologies, memory starts getting exhausted. unused object references not getting cleaned garbage collector. googled problem , used -xmx increase heap size upto 5gb suggested many . problem still persists. appreciate in regard. owlontologymanager owlmanager = owlmanager.createowlontologymanager(); file folder = new file("g:\\owl , obo"); file[] listoffiles = folder.listfiles(); (int = 0; < listoffiles.length; i++) { if (listoffiles[i].isfile()) { system.out.println("file " + listoffiles[i].getname()); try{ file sourcefile = new file( "g:\\owl , obo\\" + listoffiles[i].getname()); owlontology ontology = owlmanager.loadontol

c - Do function parameters take up local memory space? -

in following example, taking local memory space in function "add"? , if not, parameter variables stored in memory? void add(int *a, int *b, int *result){ *result = *a + *b; } int main(){ int = 1, b = 2, result; add(&a, &b, &result); printf("result = %d\n", result); return 0; } do function parameters take local memory space? in following example, taking local memory space in function "add"? the answer these questions depends heavily upon implementation. perhaps implementation automatically inlines functions , , function parameters might eliminated entirely inlining process. implementation might hoist of runtime logic compile time ; i.e. entire example can optimised puts("result = 2"); during compilation. alternatively... where parameter variables stored in memory? often times, arguments stored register storage. register storage committed program, , might otherwise committed , u

python - Renaming a virtualenv folder without breaking it -

i've created folder , initialized virtualenv instance in it. $ mkdir myproject $ cd myproject $ virtualenv env when run (env)$ pip freeze , shows installed packages should. now want rename myproject/ project/ . $ mv myproject/ project/ however, when run $ . env/bin/activate (env)$ pip freeze it says pip not installed. how rename project folder without breaking environment? you need adjust install use relative paths. virtualenv provides --relocatable option. the docs : normally environments tied specific path. means cannot move environment around or copy computer. can fix environment make relocatable command: $ virtualenv --relocatable env note: env name of virtual environment , must run outside env directory. this make of files created setuptools or distribute use relative paths, , change scripts use activate_this.py instead of using location of python interpreter select environment. note: must run af

Setting default Python grammar version in Eclipse PyDev -

Image
i have fresh installation of eclipse , pydev, on mac has python 2.7 , python 3.6 installed. whenever start new pydev project, asks me choose grammar version, , 2.7 default. how can change 3.6 default grammar? in eclipse preferences -> pydev -> interpreters -> python interpreter have python 3.6 configured; else should look? this not implemented (albeit should use current interpreter selected define default version, so, please report in pydev tracker: https://www.brainwy.com/tracker/pydev )

PHP Add new once element in array and remove last once -

i want keep 3 element in array. so, want if new element added in array oldest element remove array , re-index array. best , fast way make it? this first array $foo = array( 'when', // [0] 'whom', // [1] 'what' // [2] ); if new element "how" added, want modify below. $foo = array( 'how', // [0] 'what', // [1] 'whom' // [2] ); php has many built in array functions including array_unshift allows add element beginning , array_pop allows remove element end: array_unshift($foo, 'how'); // add beginning array_pop($foo); // remove end example: https://eval.in/859692

c++ - How to set default value of a vector of int pairs to be empty? -

i want gave default value (of empty) vector of int pairs in constructor (c++ 98). i've tried things along following , (obviously) doesn't work. point me in right direction? someclassname( const int replace = 1, const std::vector<std::pair<int, int> > node = std::vector<std::pair<int, int>() >() ); std::vector<std::pair<int, int>() >() value-initialized (empty std::vector ) instance of vector of functions taking nothing , returning std::pair<int, int> . remove inner () vector of pairs: const std::vector<std::pair<int, int> > node = std::vector<std::pair<int, int> >() you might want consider typedef because there's lot of noise: typedef std::vector<std::pair<int, int> > node; ... const node node = node()

amazon web services - create custom latency metric in Cloudwatch -

i have application. basically, want measure time between starts , request done processing. call latency of processing request. i wonder if can create custom aws cloudwatch metric monitor using putmetricdata api. you can create custom metric. define metric name, dimension , value metric. can statistical methods on other standard metrics. also can create alarms based on metric too. if use nodejs use below documentation put metric. http://docs.aws.amazon.com/awsjavascriptsdk/latest/aws/cloudwatch.html#putmetricdata-property all custom metrics data appear under custom namespaces under cloudwatch > metrics

typescript - Vue fetch response.json promise not creating reactive getters -

i have vue application written typescript , i'm using fetch retrieve data api. in 1 of components have following interface defined: interface searchresult { device_id: string; location: string; sub_location: string; status: string; } in fetch method cast response.json() promise array of searchresult interface so: fetch(url).then(response => response.json() promise<searchresult[]>) .then(data => { this.results = data; }) the issue have is, if 'status' not included in response.json(), no reactive getter created this.results.status , meaning can't mutate data , have react on page. i tried manually setting value of 'status' after line this.results = data , , when inspect object using vuetools can see has status property value assigned it. reactive getter , setter still missing. i tried changing interface class constructor set default value 'status', failed create reactive getter

java - Duplicate rows when save() using JPA -

basically i'm creating gui using javafx alongside spring , hibernate. problem related jpa suppose first time user inserts data in db (column monday true , other columns false ) id employees start_time end_time monday tuesday wednessday thursday friday saturday sunday 1 5 1.0 7.0 true false false false false false false 2 7 9.0 11.0 true false false false false false false my problem second time when inserting data db, duplicates first 2 rows, not want. id employees start_time end_time monday tuesday wednessday thursday friday saturday sunday 1 5 1.0 7.0 true false false false false false false 2 7 9.0 11.0 true false false false false false false 3 5 1.0 7.0 t

React Native Animated Loop start callback -

i struggling react native animations here. outcome simple, have animated.image want spin. good, until want loop thru animation n times , when stops. have following code . animated.loop( animated.timing(this.state.spin, { tovalue: 360, duration: 1000, easing: easing.linear, usenativedriver: true, }), { iterations: 3 } ).start(() => { console.log('done'); }); it spins 3 times per loop iteration no callback fired when animation ends. here expo replicates this: https://snack.expo.io/s1pjnfb9- try code below animated.loop( animated.timing(this.state.spin, { tovalue: 360, duration: 1000, easing: easing.linear, usenativedriver: true, }), { iterations: 3 } ).start(event => { if (event.finished) { console.log('finished'); } }); i added check on event response. hope helps.

java - Purpose of resultAll in scalikejdbc -

what's purpose of resultall in below code? notice when there resultall sql statement doesn't include joined table jdbcselect(m.resultall) .from(member m) .innerjoin(group g) .on(m.groupid, g.id) sql statement = "select m.id i_on_m member m inner join group g on m.group_id = g.id" and jdbcselect .from(member m) .innerjoin(group g) .on(m.groupid, g.id) sql statement = "select m.id i_on_m, g.id i_on_g member m inner join group g on m.group_id = g.id"

html - how to fix css issue with height -

here code snippet: /* text types */ h1{font-family: 'open sans', arial, sans-serif; margin: 0; font-size: 24px; line-height: 125%;} h2{font-family: 'neuton', serif; margin: 5px 0px 10px 0px; font-size: 24px; font-weight: 200; line-height: 120%;} h3{font-family: 'open sans', arial, sans-serif; margin: 8px 0px 2px 0px; font-size: 16px; line-height: 130%; font-weight: 600;} h4{font-family: 'neuton', serif; font-size: 16px; margin: 2px 0px 6px 0px; line-height: 120%; font-weight: 200;} h5{font-family: 'open sans', arial, sans-serif; margin: 0; font-size: 12px;} h6{font-family: 'open sans', arial, sans-serif; font-size: 10px;} /* links */ a, a:hover, a:visited, a:active{text-decoration: none; outline: none; color: inherit;} a.underline:hover{text-decoration: underline; color: inherit;} a.readmore{font-family: 'raleway', serif; font-size: 15px; margin: 15px 0px 0px 0px; font-weight: 700; color: #428bca;} .thinner{

machine learning - Does dropout work for input nodes when the inputs can include zero? -

my understanding of neural network dropout set value of neuron want dropout zero. however, if 1 of inputs range of numbers can include zero, doesn't mean value 0 being set dropout confused value 0 legitimate input? yes, dropout set value of neuron want dropout zero, key implement randomly . each hidden layer , can set different dropout rate. input layer not part of dropout.

asp.net core mvc - Keycloak in infinite loop - `invalid_grant` -

"message contains error: 'invalid_grant', error_description: 'code expired', error_uri: 'error_uri null'." i receive error during onremotefailure event. not sure how tell keycloak reset. events = new openidconnectevents { onauthorizationcodereceived = context => { return task.fromresult(0); }, ontokenresponsereceived = context => { var idtoken = context.tokenendpointresponse.idtoken; refreshtoken = context.tokenendpointresponse.refreshtoken; return task.fromresult(0); }, onredirecttoidentityprovider = context => { return task.fromresult(0); }, ontokenvalidated = context => { accesstoken = context.tokenendpointres

angular - Display Angular4 Response Data From httpClient Iteration ngFor -

Image
i have code angular 4 and have (array objects)response in console and want use data in *ngfor iterate objects, how can this? thanks. since used {observe: 'reaponse'} httpclient.get , there full response(both header , body) back, can use *ngfor iterator data.body exposing public variable below: data: any; this.http.get(..., {observe: 'response'}) .subscribe(data => this.data = data.body); template code sample: <div *ngfor="let item of data"> {{item.address}} </div> httpclient.get return body of response default without {observe: 'response'} . can achieve without {observe: 'response'} below: data: any; this.http.get(...) // without observe: response .subscribe(data => this.data = data); template code sample: <div *ngfor="let item of data"> {{item.address}} </div> also can use async pipe subscribe , unsubscribe template without expose data pub

php - Pipling STDOUT to script not activating script -

i trying pipe stdout script bash script sends curl post info. this command looks like: rtl_fm -g 100 -d 3 -s 22050 -f ${pager_freq} - | multimon-ng -q -f alpha -a pocsag512 -t raw - | tee page-upload.sh when echo script text similar output script works expected: echo "pocsag512: address: 1210001 function: 0 alpha: p121 replace unit p116<lf>in station 116<lf>6825 tomken rd<lf>2017/09/11 17:23:50<eot>"|page-upload.sh i have tried doing curl directly after echo or inside bash scripts , php, reason no joy. any thoughts? you using tee wrong way. tee writes file, not call script. maybe mean this rtl_fm -g 100 -d 3 -s 22050 -f ${pager_freq} - | multimon-ng -q -f alpha -a pocsag512 -t raw - | tee upload.log | page-upload.sh

javascript - How to fetch data from database with json_encode of ajax -

i use ajax fetch data db. , chose alert(valdata) in success function test data, unlucky nothing return ajax. tested select contact idc id='5'; it works fine in mysql cmd line. here js code: var stnum = 5; $.ajax({ datatype:'json', type:"post", url:"get_ajax_csc.php", data:{stnum:stnum}, success:function(data) { var valdata = data; alert(valdata); $('#stcontact').val(data.stcnt); $('#stphone').val(data.stpho); } }); here html code: <div class="divfir"> <label>contact:</label><input type="text" id="stcontact" ><br /> <label>phone:</label><input type="text" id="stphone" ><br /> </div> here get_ajax_csc.php code: <?php if(isset($_post['stnum'])) { include("db.php"); $q=$_post[&q

java - Naive matrix multiplication improvement -

my cs teacher asked "add small change" code make run time complexity of n 3 - n 2 instead of normal n 3 . cannot life of me figure out , wondering if happened know. don't think talking strassens method. when looked @ it, maybe take advantage of fact cares square (diagonal) matrix. void multiply(int n, int a[][], int b[][], int c[][]) { (int = 0; < n; i++) { (int j = 0; j < n; j++) { c[i][j] = 0; (int k = 0; k < n; k++) { c[i][j] += a[i][k]*b[k][j]; } } } } you cannot achieve matrix multiplication in o(n 2 ) . however, can improve complexity o(n 3 ) . in linear algebra, there algorithms strasens algorithm reduces time complexity o(n 2.807 ) reducing number of multiplications required each 2x2 sub-matrix 8 7. coppersmith winograd algorithm fastest known matrix multiplication algorithm best time complexity o(n 2.3729 ) .

javascript - Uncaught TypeError: Cannot set property 'innerHTML' of null in Character Counting in multiple textareas -

Image
i coding page separately count characters in multiple textareas. function works fine, having error of 'uncaught typeerror: cannot set property 'innerhtml' of null' while starting type in first textarea. 2 questioned parts in console highlighted below. can please help? how can fixed? thank much! <script> function textcounter(textfield, showcountfield, maxamount,id) { if (textfield.value.length <= maxamount) { showcountfield.value = maxamount - textfield.value.length; document.getelementbyid('go'+id).innerhtml = ''; } else { document.getelementbyid('go'+id).innerhtml = '<span style="color:red">over!!</span>'; textfield.value = textfield.value.substring(0,maxamount); } } </script> <body> <form> <textarea id="q" name="w" onkeyup="textcounter(this.form.q,this.form.w,5,1);" onkeypress="textcou

Google Maps Infowindow error - always opened in one marker -

<script> function listing_mapa_init(){ var e=new google.maps.latlngbounds,t={ zoom:15, maptypeid:google.maps.maptypeid.roadmap }; var markers=[], places=[ [54.134363,37.581087,'scdasdcasdcv','september 11, 2017','/index.php?page=item&id=25','/img/no_photo.gif','check seller'], [54.134363,37.581087,'saefdefsd','september 11, 2017','/index.php?page=item&id=24','/img/no_photo.gif','check seller'], [55.755826,37.6173,'tru','september 11, 2017','/index.php?page=item&id=23','/img/no_photo.gif','124.00 usd'], [55.755826,37.6173,'mnu','september 11, 2017','/index.php?page=item&id=22','/img/no_photo.gif','check seller'], [52.287303,76.967402,'qwert','september 10, 2017','index.php?page=item&id=21

Add a dynamic header in angular 2 http provider -

i have http interceptor built via tutorial https://scotch.io/@kashyapmukkamala/using-http-interceptor-with-angular2 the problem need have dynamic header changes automatically once changes 'mode' in app. service able tell interceptor change header, or have interceptor pull header (which string)from service each request. able throwing away patch method, call http.patch('new header string') set header string. call in service controls 'mode' setting. wondering if there way interceptor pull recent value service each request or if can add method http provider via interceptor? i've tried call service in interceptor each request returns undefined. because creating new instance of service or copying value before service fired , loaded/changed data. i don't want pass header string every http provider call because defeats purpose of having interceptor, id able set once changes or have provider fetch service before makes request. tl;dr : need add autom

exchangewebservices - Using EWS SOAP requests in an Outlook web add-in -

i need use several ews requests (e.g. getuserconfiguration , updateuserconfiguration ) not supported using office.context.mailbox.makeewsrequestasync . i cannot use ews managed api in own web service broker, , must use xml soap requests directly add-in's javascript (those methods not available in graph or mail apis). there many examples (like this ) showing how getuseridentitytokenasync can used pass token web service (again, can't use) use there in whatever way need it. however, i'm guessing token retrieved getuseridentitytokenasync different , cannot used. simple , appropriate test, obtained oauth token o365 account , used token using soape test getuserconfiguratio n call , worked. tried using token getuseridentitytokenasync , didn't work ( 401 unauthorized ). i concede may poor test, , admit @ point unclear me how soap ews request javascript in outlook dd-in can authenticated without requiring explicit user login (hopefully can). , if can, how tok

Getting through in Machine Learning -

i have completed machine learning course andrew ng , proceed further. want python implementation of machine learning beginning can practice on kaggle. also, there better book or tutorial or resource can proceed further without wasting time searching such resources. the best book unequivocally has implementation of machine learning algorithms in python "introduction machine learning python: guide data scientists" andreas c. müller. machine learning algorithms in python can used package called scikit-learn. package has need machine learning. algorithms, scaling, cross validation. , book written chief developer of scikit-learn itself.

java - Sending Scroll event to another application -

i think question bit crazy, want send scroll event app app ( eg chrome ). if chrome opened , when user press vol or down button, background activity listen button event , if event scroll chrome opened webpage or down. not sure possible because reading through doc's google , saying need root permission sent event 1 app another. don't have code yet. 1 know possible android api ? thanks i cannot answer in context of chrome. however, can serialize need , send via intent system application. as example, in first application, receive touch event boolean ontouch(motionevent event){ if(event.getactionmasked() == motionevent.action_up){ intent startotherapplication = new intent(); startotherapplication.putextra("action_up_x",event.getx()); startotherapplication.putextra("action_up_y",event.gety()); startotherapplication.setcomponent(new componentname("com.your.other.application", "com.your.other.app

scala - How to permanently disable javadsl namespace when coding with Akka Streams -

Image
i have started learn akka streams. 1 of very big annoyances of product classes appear in both javadsl , scaladsl namespaces. somehow, intellij automatically import classes javadsl namespace first. leads syntax errors , lot of wasted time. problems disappear when import same class scaladsl namespace. how can block/hide javadsl namespace permanently? perhaps there setting in sbt when import akka streams dependency, tell sbt kill visibility javadsl namespace. or maybe other solution prevents intellij automatically importing classes javadsl namespace. you can in intellij idea: just add akka.stream.javadsl there, , should stop suggesting items javadsl package.

relative path - How to save generated file temporarily in servlet based web application -

i trying generate xml file , save in /web-inf/pages/ . below code uses relative path: file folder = new file("src/main/webapp/web-inf/pages/"); streamresult result = new streamresult(new file(folder, filename)); it's working fine when running application on local machine (c:\users\username\desktop\source\myproject\src\main\webapp\web-inf\pages\myfile.xml). but when deploying , running on server machine, throws below exception: javax.xml.transform.transformerexception: java.io.filenotfoundexception c:\project\eclipse-jee-luna-r-win32-x86_64\eclipse\src\main\webapp\web inf\pages\myfile.xml i tried getservletcontext().getrealpath() well, it's returning null on server. can help? never use relative local disk file system paths in java ee web application such new file("filename.xml") . in depth explanation, see getresourceasstream() vs fileinputstream . never use getrealpath() purpose obtain location write files. in depth ex

scala - Filter a list based on two parameters -

i want filter list based on parameter in scala case class student( name:string, age:int, subjects:list[subject] ) case class subject(name:string,id:int) val sub1=subject("maths",101) val sub2=subject("science",102) val sub3=subject("english",103) val s1=student("abc",20,list(sub1,sub2)) val s2=student("def",30,list(sub3,sub1)) val s3=student("xyz",40,list(sub3,sub2)) val slist=list(s1,s2) def findsubjectid(slist: list[student], subject:string) { slist.map(student => student.copy(subjects = student.subjects.filter(_.name == subject))) } parameter 1 - subject parameter 2 - age 20 or 30 result- should optional you can try this: slist .map(student => student.copy( subjects = student.subjects .filter(_.name == subject))) .filter(student => student.age == 20 || student.age == 30)

ios - Swift 3 create game hit before time is up -

i building game have random emoji appear in top corner , emoji appear on page. player should hit emoji before time , when emoji in page appears 1 in corner going lose. know have make emoji button , created array of image. how can link both emoji invoked each time randomly array? here code: class viewcontroller: uiviewcontroller { @iboutlet var mybutton: uibutton! var timer:timer? @ibaction func pressed(_ sender: any) { let imagearray:[uiimage] = [uiimage(named: "1.png")!, uiimage(named: "2.png")!, uiimage(named: "3.png")!, uiimage(named: "4.png")!, uiimage(named: "5.png")!, uiimage(named: "6.png")!, uiimage(named: "7.png")!, uiimage(named:

javascript - Service invoked too many times in a short time -

i'm getting error message following script. "service invoked many times in short time: exec qps. try utilities.sleep(1000) between calls." i've given code below. can me stop error message? note: i'm using array formula imported sheet. trigger set work on change. function onedit(e) { var ss = spreadsheetapp.getactivespreadsheet(); var sheet = ss.getsheetbyname('direct'); var range = sheet.getdatarange(); var values = range.getvalues(); var rows_deleted = 0; (var = 0; < values.length; i++) { (var j = 0; j < values[i].length; j++) { var value = values[i][j]; //row numbers 1-based, not zero-based for-loop, add 1 and... //every time delete row, of rows move down one, subtract count var row = + 1 - rows_deleted; //if type number, don't need if (typeof value === 'string') { var result = value.search("remove

json - Swagger-php - how to add paths programmatically? -

i'm using swagger documentation. generating json file annotation works great. further, want add more paths generated json file programmatically. i discovered swagger class has merge method tried deserialize json string , merge swagger object below, had no luck. $swagger = \swagger\scan($appdir); $jsonstring = json_encode([ "path" => [ "path" => "/api/task/{taskname}", "parameter" => [ "ref" => "#/parameters/taskname" ] ], ]); $objecttomerge = (new serializer())->deserialize($jsonstring, 'swagger\annotations\path'); $swagger->merge($object); i don't know i'm doing right way. had used swagger merge method or mergeproperties method? or there way achieve goal? okay figured out problem. the problem because json string put deserialize method first parameter not proper. the formation of json string no

ios - Changing label text to what user inputs into UITextField -

this basic question i'm not sure problem is. i'm trying make simple "hello world" program user inputs want textfield , whatever enter goes label. however, nothing seems happening , i'm unsure why since push function worked how expected to. import uikit class viewcontroller: uiviewcontroller { @iboutlet var popup: uitextfield! @iboutlet weak var helloworld: uilabel! @ibaction func push(_ sender: uibutton) { popup.ishidden = false popup.text = "hello world" } @ibaction func send(_ sender: uitextfield) { helloworld.text = sender.text } } based on code provided, func send unknown me, whether or not firing. func send might called, might not, either way, strange see _ sender: uitextfield ibaction . what event firing related uitextfield ? trying update helloworld uilabel user types in uitextfield ? to update uilabel whatever has been typed in uitextfield , need uibutton touch inside

python - Re-scale the probabilities to make the sum of the probabilities to 1 -

this question has answer here: normalize small probabilities in python 2 answers i have list of probabilities follows probability_list = [0.9, 0.8, 0.0, 0.2, 1.0] each value represents probability of appearing given word. e.g., 0.9 -> denotes probability of appearing word_1 0.9 e.g., 0.8 -> denotes probability of appearing word_2 0.8 , on. now want re-scale aforementioned probability_list way sum of becomes 1 . please suggest me suitable approach this. the easiest way sum of list , divide each element list comphrension: total = sum(probability_list) probability_list = [i/total in probability_list]