id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23525400
I am trying to oversample some data in pyspark, as mllib doesn't have inbuilt support for it, i decided to create it myself using smote. my approach till now has been to convert all the categorical distance into index using stringtoindex so that i can find the euclidean distance and neighbors and hence perform smote. I am fairly new to spark and ml. Any help would be appreciated. A: Not tried but Ive found this script: https://github.com/jakac/spark-python-knn/blob/master/python/gaussalgo/knn/knn.py If your data are dataframe, you should first merge your column into a vector with vectorASsembler https://spark.apache.org/docs/latest/ml-features.html#vectorassembler, then use df.select("id", "yourColumnVector") The library I provided seems to work only with rdd, so you should convert your dataframe to RDD using df.rdd
doc_23525401
How I can do this? A: guideArray = < YOUR SECOND ARRAY WITH STRING OBJECT >; unsortedArray = < YOUR FIRST ARRAY WITH CUSTOM OBJECT >; [unsortedArray sortUsingComparator:^(id o1, id o2) { Items *item1 = o1; Items *item2 = o2; NSInteger idx1 = [guideArray indexOfObject:item1.ItemID]; NSInteger idx2 = [guideArray indexOfObject:item2.ItemID]; return idx1 - idx2; }]; NSLog(@"%@",unsortedArray); A: Store the custom objects in an dictionary with itemID as key, use this dictionary as lookup to sort the objects: NSArray *objects; // your objects NSMutableArray *hintArray; // your sorted IDs NSMutableDictionary *lookupDict = [[NSMutableDictionary alloc] initWithCapacity:[objects count]]; NSMutableArray *sortedObjects = [[NSMutableArray alloc] initWithCapacity:[hintArray count]]; for (id object in objects) { [lookupDict setValue:object forKey:[object itemID]]; } for (id hint in hintArray) { [sortedObjects addObject:[lookupDict valueForKey:hint]]; } EDIT: Solution with inplace sort of objects: NSMutableArray *objects; NSMutableArray *hintArray; NSMutableDictionary *lookupDict = [[NSMutableDictionary alloc] initWithCapacity:[hintArray count]]; int i = 0; for (NSString *itemID in hintArray) { [lookupDict setValue:[NSNumber numberWithInt:i] forKey:itemID]; i++; } [objects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [[lookupDict valueForKey:[obj1 itemID]] compare:[lookupDict valueForKey:[obj2 itemID]]]; }]; A: You can compare your two objects using following syntax :- [items sortUsingComparator:^NSComparisonResult(Attribute *obj1, Attribute *obj2) { return [[NSNumber numberWithInt:[stringOrder indexOfObject:obj1.itemID]] compare:[NSNumber numberWithInt:[stringOrder indexOfObject:obj2.itemID]]] }]; or else you can use following snippet : NSArray* sortedKeys = [dict keysSortedByValueUsingComparator:^(id obj1, id obj2) { return [obj1 compareTo:obj2]; } Enjoy Programming !
doc_23525402
A: I'm having the same problem, with an installation fresh as of today (January 24th, 2013) relating to IE9 playing an MP4 file. The video's playing fine for Chrome, Firefox, and Safari, but it's not starting with IE.
doc_23525403
{=IFERROR(INDEX(Creation_Series_R!C:C;SMALL(IF(Creation_Series_R!$C$3:$C$20402<>"";ROW(Creation_Series_R!$C$3:$C$20402));ROW()-ROW(Creation_Series_R!$C$3)+1));"")} And the formula works very well. Except, when I did my proof of concept I only had a few rows but with the final data, I need to work on 20400 rows... adding to the fact that I have 17 columns, and 3 similar sheets with similar formula, my workbook takes an hour to compute every time I input just one value. This workbook is designed as a way for a client to enter data, and then it reorganize the data so that it can be imported directly in our software. I already limited the number of data the user can enter per workbook (to their very big disappointment), so I can't really reduce it to less than 20400 rows (it's only a 100 funds financial data). Is there a way, even maybe using macro, I could do this more efficiently ? A: The big block of array formulas is killing your performance (time-wise). If your data is in column A through Q, then I would use column R as a "helper" column. In R2 insert: =COUNTA(A2:Q2) and copy down. The macro would: * *AutoFilter column R *Hide all rows showing 0 in column R *Copy the visible rows and paste elsewhere as a block
doc_23525404
var exp = /he|hell/; When I run it on a string it will give me the first match, fx: var str = "hello world"; var match = exp.exec(str); // match contains ["he"]; I want the first and longest possible match, and by that i mean sorted by index, then length. Since the expression is combined from an array of RegExp's, I am looking for a way to find the longest match without having to rewrite the regular expression. Is that even possible? If it isn't, I am looking for a way to easily analyze the expression, and arrange it in the proper order. But I can't figure out how since the expressions could be a lot more complex, fx: var exp = /h..|hel*/ A: How about /hell|he/ ? A: All regex implementations I know of will (try to) match characters/patterns from left to right and terminate whenever they find an over-all match. In other words: if you want to make sure you get the longest possible match, you'll need to try all your patterns (separately), store all matches and then get the longest match from all possible matches. A: You can do it. It's explained here: http://www.regular-expressions.info/alternation.html (In summary, change the operand order or group with question mark the second part of the search.) A: You cannot do "longest match" (or anything involving counting, minus look-aheads) with regular expressions. Your best bet is to find all matches, and simply compare the lengths in the program. A: I don't know if this is what you're looking for (Considering this question is almost 8 years old...), but here's my grain of salt: (Switching the he for hell will perform the search based on the biggest first) var exp = /hell|he/; var str = "hello world"; var match = exp.exec(str); if(match) { match.sort(function(a, b){return b.length - a.length;}); console.log(match[0]); } Where match[0] is going to be the longest of all the strings matched.
doc_23525405
{ "high" : 4686.87, "low" : 4671.11, "open" : 4671.12, "count" : 833, "volume" : 283.194184560001, "close" : 4678.51 } ... { "high" : 4735, "low" : 4670.82, "open" : 4734.88, "count" : 1586, "volume" : 405.721894079999, "close" : 4671.12 } ... I want to group then every 7 days (every 7 documents). Something like this: db.getCollection('ticks').aggregate({$sort:{_id: -1}}, {$group: { id: // every 7 docs, open: { $first: '$open' }, close: { $last: '$close' }, high: { $max: '$high' }, low: { $min: '$low' }, volume: { $sum: '$volume' } }}); What "id" should I use or how I add a new field that allows me to make it work? NOTE: I know I can use the data to group it every week of the year, but don't want every week. I already have a weekly aggregated. I want to have the last 7 days aggregated, that could be spread on two weekOfYear
doc_23525406
Hi, I'm trying to develop Javascript that will get this Email form to work properly. Basically, I need to make sure that the user fills out both fields when the “Submit” button is clicked. If the fields are not filled, an alert message should show up and the cursor should move back to that field. Here is my HTML: <html> <head> <title>Castaway Vacations, LLC</title> <script src="form.js"></script> </head> <body leftmargin=0 rightmargin=0> <br> <table width=100% border=0 cellpadding=0 cellspacing=0> <tr> <td width=95% align=right bgcolor=#ffffff><img src="castaway_logo.jpg"> <br> <font face=arial>Vacations, LLC</font></td> <td bgcolor=#ffffff>&nbsp;</td> </tr> </table> <br><br> <center> <table width=85%> <tr> <td valign=top> <form id="emailform" method="post" action="form.html">Name:<br> <input id="name" name="textname" size=35><br><br>E-mail:<br> <input id = "email" name="textname" size=35><br><br> <input type=submit name="button1" value="Submit"> </form> </td> </tr> </center> </body> </html> And Javascript: var $ = function (id) { return document.getElementById(id); } submit = function () { var name = $("name").value; var email = $("email").value; var isValid = true; } //validate entry for "Name:" if (name == "") { $("name_error").firstChild.nodeValue = "Name is required."; isValid = false; } else { $("name_error").firstChild.nodeValue = ""; } //validate entry for "E-Mail:" if (email == "") { $("email_error").firstChild.nodeValue = "E-mail is required."; isValid = false; } else { $("email_error").firstChild.nodeValue = ""; } if (isValid) { //use the submit method of the form object to submit the form $(emailform).submit(); } Right now nothing is happening at all - whether the fields are filled out or not. I'm new to Javascript and am trying to learn, so please provide explanation if possible. The "firstChild node" concept is especially confusing to me. Thank you! JSfiddle link: http://jsfiddle.net/HappyHands31/kx1q9wo7/ A: It's obvious you're a beginner. So please don't take this the wrong way. There is so much wrong with what you're doing is difficult to know where to start. First, you aren't using jquery, but it appears that the code you've been looking up on how to do this was primarily jQuery code. It doesn't appear that you know how to declare a function or use a function as an event handler. You don't understand variable scope. You're trying to set values on elements with the id's of 'name_error' and 'email-error' but those elements don't exist in your HTML. And besides the javascript issues, you're using table layouts for your page. Do yourself a favor and learn CSS and use div's instead of tables. Here's a working validation (non-jQuery) of your form. I'd also recommend you learn jQuery as it is the future (actually the present) of javascript. http://jsfiddle.net/3ykvwxu9/1/ HTML: <div id="content"> <div id="logo-wrapper"> <img src="castaway_logo.jpg"><br /> Vacations, LLC </div> <div id="errors"></div> <form id="emailform" method="post" onsubmit="return validateEmailForm();" action="form.html">Name:<br> <input id="name" name="textname" size=35><br><br>E-mail:<br> <input id = "email" name="textname" size=35><br><br> <input type="submit" name="button1" value="Submit"> </form> </div> CSS: #content { width: 100%; position: relative; } #logo-wrapper { float: right; text-align: center; padding-right: 15px; } #errors { clear:both; margin: 15px auto; width: 300px; height: 40px; color: red; } form#emailform { margin: 0 auto; display: block; width: 300px; } Javascript: function validateEmailForm(){ var name = document.getElementById('name'); var email = document.getElementById('email'); var errDiv = document.getElementById('errors'); var error = ''; var focusElem; if(name.value.length == 0){ error += "Name is required<br />"; focusElem = name; } if(email.value.length == 0){ error += "Email is required<br />"; if(focusElem == undefined){ focusElem = email; } } if(error.length > 0){ errDiv.innerHTML = error; focusElem.focus(); return false; } return true; } A: Try to remove var word in the submit() function. var tells to javascript engine that the scope of this variable is inside the function, so in another functions doesn't exists. Removing var you are attaching the variable to the global window object. It doesn't works in strict mode, but you don't define it so it works for you A: Alright lets go through a number of issues that are going to prevent your code from working.. var submit = function () { var name = $("name").value; var email = $("email").value; var isValid = true; //These are all local variables so they won't be accessible any where else. Nor are you really checking anything. This function just sets isValid = true locally. } This isn't really the proper way to define an event listener or a function. I'm not really sure what you were going for here.. If this is supposed to attach to the submit event of the form you might want to look at the onsubmit property https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit If you're just wanting a global function, you should be defining it like so: function submit() { //Insert code here } //validate entry for "Name:" if (name == "") { $("name_error").firstChild.nodeValue = "Name is required."; isValid = false; } else { $("name_error").firstChild.nodeValue = ""; } This isn't attached to anything, it'll run once when the script is parsed then never again. Also it looks like name_error doesn't actually exist in your HTML, so that will of course not find anything. //validate entry for "E-Mail:" if (email == "") { $("email_error").firstChild.nodeValue = "E-mail is required."; isValid = false; } else { $("email_error").firstChild.nodeValue = ""; } Same here, you're just arbitrarily running this script when the script is loaded. Not actually checking for anything. if (isValid) { //use the submit method of the form object to submit the form $(emailform).submit(); } This code will, like the rest, run one time. Check if isValid is true, which it won't be because your isValid variable is not accessible globally. If it is magically available though it will automatically submit your form. Here's a basic jsfiddle showing you how to properly attach an event handler as well as define global variables instead of variables in closures. http://jsfiddle.net/pbu78npx/1/ It should be a good starting point for what you're wanting. A: Here's the cleaner version of how you can do it: $("#emailform").submit(function(e) { var isValid = Validate(); if(!isValid) { e.preventDefault(); } }); function Validate() { var isValid = true; if($.trim($("#name").val()) == "") { isValid = false; $("#name_error").text("Name is required."); } else $("#name_error").text(""); if($.trim($("#email").val()) == "") { isValid = false; $("#email_error").text("Email is required."); } else $("#email_error").text(""); return isValid; } <table width=100% border=0 cellpadding=0 cellspacing=0> <tr> <td width=95% align=right bgcolor=#ffffff><img src="castaway_logo.jpg"> <br> <font face=arial>Vacations, LLC</font></td> <td bgcolor=#ffffff>&nbsp;</td> </tr> </table> <br><br> <center> <table width=85%> <tr> <td valign=top> <form id="emailform" method="post" action="form.html">Name:<br> <div id="name_error"></div> <input id="name" name="textname" size=35><br><br>E-mail:<br> <div id="email_error"></div> <input id = "email" name="textname" size=35><br><br> <input type="submit" name="button1" value="Submit"> </form> </td> </tr> </center> Fiddle : http://jsfiddle.net/gy1oj8dz/2/
doc_23525407
The problem is that when i run the project, it loads the candlestick chart fine and the indicators. But as soon as it updates by the interval it, then disapears, and it will do that on every update if i try to wing it back from the legends tab. Also the chart works fine, and updates fine if its alone, and without the indicators, but when they are added into the chart it removes the candlestick charts visability after 1 update. The data is being pulled from a Websocket stream and converted into SQL, then into pandas dataframe. This is an image of what happens: This is the code: import dash from dash.dependencies import Output, Input from dash import dcc from dash import html import pandas as pd import plotly.graph_objs as go import flask import waitress from waitress import serve server = flask.Flask(__name__) # define flask app.server app = dash.Dash(__name__, server=server) # call flask server app.layout = html.Div( html.Div([ dcc.Graph(id='live-update-graph-scatter', animate=True), dcc.Interval( id='interval-component', disabled=False, interval=1*5000, n_intervals=0 ) ]) ) @app.callback(Output('live-update-graph-scatter', 'figure'), [Input('interval-component', 'n_intervals')]) def update_graph_scatter(n): rec = pd.read_sql_table('crypto', engine) rec1 = pd.DataFrame(rec) print(rec1) rec1.columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'EMA', 'EMA2'] rec1['date'] = pd.to_datetime(rec1['date']) rec1.set_index('date', inplace=True) ###SUBPLOT AND Candlestick CHART fig = make_subplots(rows=4, cols=1) fig.add_trace(go.Candlestick( x=rec1.index, open=rec1['open'], high=rec1['high'], low=rec1['low'], close=rec1['close']), row=1, col=1, ) ###### ADD INDICATOR TRACES: fig.add_trace( go.Scatter( x=rec1.index, y=rec1['EMA'], marker=dict(color='blue') ), row=1, col=1 ) fig.add_trace( go.Scatter( x=rec1.index, y=rec1['EMA2'], marker=dict(color='red') ), row=1, col=1 ) return fig if __name__ == '__main__': serve(app.server, host="localhost", port=5005) Do you have any suggestions as to what i can do i would be happy to hear that. Best regards. Mathias A: The solution is to look at the attribute animate in the graph object. https://dash.plotly.com/dash-core-components/graph You have to specify the animation option, with redraw = True, otherwise it wont draw it out. Maybe if you dont want it to redraw you can make some appending function so only the current candle gets redrawn. But my problem got fixed.
doc_23525408
HttpTransportBasicAuth aht = new HttpTransportBasicAuth(URL, username , pass); When I run the program I get the following exception. 02-08 16:57:27.014: E/AndroidRuntime(331): java.lang.NoClassDefFoundError: javax.microedition.io.Connector How can I get that class to our KSOAP2 Library? A: This is error can also be raised if you have more than one Activity and if you try to access one Activity without Registering in the AndroidManifest.xml file. So make sure that you have registered all your Activity class under this xml file. eg. if u have an activity called Act you will register as <application ...............> ---------- ---------- <activity android:name=".Act2" /> here goes your registration. </application> A: This class is not in android, its in j2me. A: You are probably not using the correct kSoap package for Android. See this post: java.lang.NoClassDefFoundError: javax.microedition.io.Connector and the following link
doc_23525409
$("#myDiv").html("<ul><li>foo</li><li>bar</li></ul><p>This is a list</p>"); I would like to wrap those in "something with a technical id attached" so that my jQuery selectors can be targetted to these specific fragmeents of the page. Something like that : var techId = ...; $("#myDiv").html(wrap(techId, "<ul id="myList"><li>foo</li><li>bar</li></ul><p>This is a list</p>")); $(document).on("click", "#"+techId+" #myList", function(event){ alert("List clicked"); }); What should be the content of the "wrap" function knowing that the wrapper cannot have any visual impact one the page, in any situation. Calling .remove() on the wrapper should remove the wrapped element but there should be a way of removing the wrapper without modifying the elements inside (at the expense of breaking the selectors).
doc_23525410
Possible Duplicate: Why is the ‘t’ in Hash Table(Hashtable) in Java not capitalized Why java.util.Hashtable not follow java naming convention ? here 't' is lowercase, if it follow the class name would be HashTable... A: java.util.HashMap; java.util.HashSet; java.util.Hashtable Because Map and Set are the Interfaces which come under Collection Framework, but table is not a keyword in current version. So camelcase is not used. A: Hashtable was created in Java v1 not like other which were released in Java2. A: See this question: Why is the 't' in Hash Table(Hashtable) in Java not capitalized Hashtable was created in Java v1. The consistent naming conventions for collections were established later, in Java2, when the other classes were published as part of the brand new Java Collection Framework. Which btw made Hashtable obsolete, so it should not be used in new code. Hope that helps.
doc_23525411
I set this meta too: <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> HTML Page: PHPMyAdmin: PS.: This question is not a replication of other question! If it is please tell me the link because I searched the same question and nothing found!!!
doc_23525412
I want to send the values to these parameters using powershell and trigger the pipeline. Any idea how to do it using Powershell. A: I'll leave a script that you can then modify to your needs: Login-AzureRmAccount Select-AzureRmSubscription -Subscription "yourSubId" $dfname = "youDataFActoryName" $rgName = "yourResourceGroupName" $pipe = "pipeName" $parameters = @{ "param1" = "asdasd" "param2" = "123456" } Invoke-AzureRmDataFactoryV2Pipeline -DataFactoryName $dfname -ResourceGroupName $rgName -PipelineName $pipe -Parameter $parameters Hope this helped! A: Parameter is to be passed as a hashtable. The hashtable is created using @ e.g : $param = @{"year" = "2022"} Invoke-AzDataFactoryV2Pipeline -ResourceGroupName "UAT" -DataFactoryName "ADF" -PipelineName "Snapshot" -Parameter $param
doc_23525413
I understand that, if I validate anything in @ResponseBody in the controller , it throws a MethodArgumentNotValidException. But for some custom validations(eg. @MyCustomValidation) at the class level it is throwing ConstraintViolationException even if it is being validated in @ResponseValidation. And for some other custom validation for a different REST endpoint, it throws MethodArgumentNotValidException. I am finding it a bit difficult to understand its behavior. @PostMapping(path = "/someEndPoint") @Validated(OnASave.class) public ResponseEntity<ClassA> saveObjA(@Valid @RequestBody ClassA objA) Result - throws MethodArgumentNotValidException @PostMapping(path = "/someOtherEndPoint") @Validated(OnBSave.class) public ResponseEntity<ClassB> saveObjB(@Valid @RequestBody ClassB objB) Result - throws ConstraintViolationException Both ClassA and ClassB has custom validations. A: When you use @Valid, you are applying validation which is defined by you on your model class fields, while there are different types of validations, you can choose like @NotNull, @Max, @Min and so on, you will get the matching type. In general, all of these are parallel to MethodArgumentNotValidException which will be thrown in all cases. From official document Exception to be thrown when validation on an argument annotated with @Valid fails. ConstraintViolationException is thrown by hibernate entity manager when some constrain violated, so this means you violated some fields in some entity you are using. A: for a simple understanding, if validation happens at controller/service layer by using @Valid annotation, it generates MethodArgumentNotValidException, you can add handler for this and return the response accordingly, this class is part of spring framework and validation is performed by spring framework see sample below @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Response> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { logger.info("Invalid arguments found : " + ex.getMessage()); // Get the error messages for invalid fields List<FieldError> errors = ex.getBindingResult() .getFieldErrors() .stream() .map(fieldError -> new FieldError(fieldError.getField(), fieldError.getDefaultMessage())) .collect(Collectors.toList()); String message = messageSource.getMessage("invalid.data.message", null, LocaleContextHolder.getLocale()); Response response = new Response(false, message) .setErrors(errors); ResponseEntity<Response> responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); return responseEntity; } and if you do not validate using @Valid annotation, and exception is raised by hibernate at jpa layer it generates ConstraintViolationException, this exception is part of Javax bean validation framework, and raised at the time of performing persistence operation (before the actual sql execution) see sample below @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<Response> handleConstraintViolationException(ConstraintViolationException ex) { List<FieldError> errors = ex.getConstraintViolations() .stream() .map(constraintViolation -> { return new FieldError(constraintViolation.getRootBeanClass().getName() + " " + constraintViolation.getPropertyPath(), constraintViolation.getMessage()); }) .collect(Collectors.toList()); String message = messageSource.getMessage("invalid.data.message", null, LocaleContextHolder.getLocale()); Response response = new Response(false, message) .setErrors(errors); ResponseEntity<Response> responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); return responseEntity; } A: Take a look at this article. These exceptions are thrown under different situations when you mix spring's validation framework with bean validation.
doc_23525414
<Edited - added sample query> SELECT (COUNT(?var) as ?varCount) ?var2 WHERE{ { ?var a abc:Class; } UNION { SERVICE <https://sample1.org> { ?var a abc:Class; ?var abc:var2 ?var2. } } UNION { SERVICE <https://sample2.org> { ?var a abc:Class; ?var abc:var2 ?var2. } } } group by ?var2
doc_23525415
function getbook(){ MongoClient.connect("mongodb://localhost:27017", function (err, client) { const db = client.db('mydb') db.collection('books',(err,collection)=>{ collection.find().toArray((err,items)=>{ books = items; }) }) }) } console.log(getbook()) A: Since MongoClient is a callback function, you can't simple call the function like that. There is two option * *promisify getbook() >> recommended *add callback function when calling getbook promisify getbook (assume the code below is wrap : function getbook(){ return new Promise((resolve, reject) => { MongoClient.connect("mongodb://localhost:27017", function (err, client) { if(err) { reject(err) } else { const db = client.db('mydb') db.collection('books',(err,collection)=>{ if (err) { reject(err) } else { collection.find().toArray((err,items)=>{ if (err) { reject(err) } resolve(items) }) } }) } }) } } in the code block where you call the function, it has to be an async function async function main() { const book = await getbook() console.log(book) } Using callback function getbook(callback){ MongoClient.connect("mongodb://localhost:27017", function (err, client) { const db = client.db('mydb') db.collection('books',(err,collection)=>{ collection.find().toArray((err,items)=>{ callback(items) }) }) }) } function main () { getbook((book) => { console.log(book) }) }
doc_23525416
ie: I want my user to be able search for Facebook Users from my website without requiring them to allow access with my application. I simply want my web page to return a list of matching names. A: AFAIK, you can't do that. Allways you need at least an user token, so after he/she authenticate you can search "impersonating" that user,
doc_23525417
I searched the internet but it made me confused! What's the difference between those? A: The main diffrence is setInterval fires again and again in intervals, while setTimeout only fires once. you can get more differnces in simple words in setTimeout or setInterval? 'setInterval' vs 'setTimeout' A: tha major difference is that setTimeout will execute some code just once, after a given delay, while setInterval will execute a code always, with a delay between each call e.g. try these on your console: setTimeout(function() { console.log('Wait 3 seconds and I appear just once'); }, 3000); and setInterval(function() { console.log('Every 3 seconds I appear on your console'); }, 3000) A: From Javascript timers MDN setTimeout() Calls a function or executes a code snippet after specified delay. setInterval() Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
doc_23525418
So my compose file look like this: version: '2' services: app: restart: always nginx: restart: always ports: - "80:80" Now if I scale "app" service to multiple instances, docker-compose will perform round robin on each call to the internal dns "app". Is there a way to tell docker-compose load balancer to apply sticky sessions? Another solution - is there a way to solve it using nginx? Possible solution that I don't like: multiple definitions of app version: '2' services: app1: restart: always app2: restart: always nginx: restart: always ports: - "80:80" (And then on nginx config file I can define sticky sessions between app1 and app2). Best result I got from searching: https://github.com/docker/dockercloud-haproxy But this requires me to add another service (maybe replace nginx?) and the docs is pretty poor about sticky sessions there. I wish docker would just allow configuring it with simple line in the compose file. Thanks! A: Take a look at jwilder/nginx-proxy. This image provides an nginx reverse proxy that listens for containers that define the VIRTUAL_HOST variable and automatically updates its configuration on container creation and removal. tpcwang's fork allows you to use the IP_HASH directive on a container level to enable sticky sessions. Consider the following Compose file: nginx: image: tpcwang/nginx-proxy ports: - "80:80" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro app: image: tutum/hello-world environment: - VIRTUAL_HOST=<your_ip_or_domain_name> - USE_IP_HASH=1 Let's get it up and running and then scale app to three instances: docker-compose up -d docker-compose scale app=3 If you check the nginx configuration file you'll see something like this: docker-compose exec nginx cat /etc/nginx/conf.d/default.conf ... upstream 172.16.102.132 { ip_hash; # desktop_app_3 server 172.17.0.7:80; # desktop_app_2 server 172.17.0.6:80; # desktop_app_1 server 172.17.0.4:80; } server { server_name 172.16.102.132; listen 80 ; access_log /var/log/nginx/access.log vhost; location / { proxy_pass http://172.16.102.132; } } The nginx container has automatically detected the three instances and has updated its configuration to route requests to all of them using sticky sessions. If we try to access the app we can see that it always reports the same hostname on each refresh. If we remove the USE_IP_HASH environment variable we'll see that the hostname actually changes, this is, the nginx proxy is using round robin to balance our requests.
doc_23525419
WHERE (dbo.Dosje.gjendja = 2) AND (dbo.Bashko.id IS NULL or dbo.Dosje.uniqueCode <> CONVERT(varchar(20), dbo.Dosje.qyteti + '_' + dbo.Bashko.kodiDytesor)) so is a condition like this A and (B or C) and it can normally transformed into (A and B) or (A and C) but strange thing happens that sqlserver transform my where clause when i try to save or execute like this WHERE (dbo.Dosje.gjendja = 2) AND (dbo.Bashko.id IS NULL) OR (dbo.Dosje.gjendja = 2) AND (dbo.Dosje.uniqueCode <> CONVERT(varchar(20), dbo.Dosje.qyteti + '_' + dbo.Bashko.kodiDytesor)) this is not the same logic. this is (A and B or A and C). that's not the same logic, why is sql server changing my query like this?? A: It is the same logic. AND operator has higher priority than OR operator so it is always evaluated first. A and B or A and C is the same thing as (A and B) or (A and C).
doc_23525420
SELECT * FROM TABLE GROUP BY Column1 A: Assuming the columns actually contain the literal string values 'TRUE' and 'FALSE', we could use: SELECT Column1, MAX(Column2) AS Column2, MAX(Column3) AS Column3 FROM yourTable GROUP BY Column1;
doc_23525421
So, from my main script, how do I dynamically call one of these scripts? The script name is a variable coming from the API, and it's in a subfolder of the main script - not the standard library location. I could use subprocess.popen or os.system, but I want everything to stay as in-house as possible. There's gotta be a way to accomplish this within one Python instance, right? A: There is a Python built-in function that can handle calling scripts. It is called execfile and you can learn more about it at: https://docs.python.org/2/library/functions.html#execfile If I have a file called testmeagain.py with the contents: print "test print" You can do this without importing additional libraries: In [1]: execfile("testmeagain.py") test print A: Assuming you run your main Python program from the directory, which see protocols as subfolder, you shall add empty __init__.py into protocols directory to make it a package. Then you shall be able importing your protocol specific modules from there, e.g. from protocols.http import process_it Here I assume, you would have there some function named process_it There are also other methods, how to import package with name defined in a variable as described e.g. in this SO answer enter link description here. In your case it would look somehow like: def process_it(protocol="http"): mod = __import__("protocols." + protocol) mod.process_it() A: Yes, there is a possibility to accomplish this within one Python instance. It is possible to load individual python scripts dynamically as the following: * *Load only the module dynamically with importlib.import_module() *Load a module and class dynamically with getattr(). Alternative 1 Use importlib.import_module(), if you only want to load the module dynamically. Let’s assume you have the following protocols in the subfolder protocols: protocols/protocol_1.py containing the following class: class Protocol(): # some protocol specific code protocols/protocol_2.py containing the following class: class Protocol(): # some protocol specific code First we define the dynamic variables with the protocol name that will be returned from the Web API: module = 'protocols.protocol_1' Then we import the importlib and load the module dynamically. The Protocol class has in both files the same class name but protocol specific code. Afterwards, we instantiate the api_protocol with the dynamically loaded Protocol: import importlib Protocol = importlib.import_module(module).Protocol api_protocol = Protocol() Alternative 2 Use getattr, if you also want to load the class dynamically. Let’s assume you have the following protocols in the subfolder protocols: protocols/protocol_1.py containing the following class: class Protocol_1(): # some protocol specific code protocols/protocol_2.py containing the following class: class Protocol_2(): # some protocol specific code First we define the dynamically variables with the protocol name that will be returned from the Web API: module = 'protocols.protocol_1' class_name = 'Protocol_1' Then we call the __import__ function in order to load dynamically the class of a dynamic module. Afterwards we can create the new class with getattr and instantiate the api_protocol with the dynamically loaded Protocol: mod = __import__(module, fromlist=[class_name]) Protocol = getattr(mod, class_name) api_protocol = Protocol()
doc_23525422
doc_23525423
what should i do to it? I checked many times ady,all the pins are placed, but still got warnings there module DataPath_Unit(clk,Clr,En,Op,W,X,Y,Z,Sel_1,Sel_2,Result); input clk,Clr,En,Op; input [7:0] W, X, Y, Z; input Sel_1,Sel_2; output[13:0] Result; reg[13:0]Result; reg[13:0]Alu_out; wire[7:0] Mux_out; assign Mux_out=(Sel_1==0)?((Sel_2==0)?X:Y):((Sel_2==0)?W:Z); //assign Alu_out=(Op==1)?(Mux_out+Result):(Result-Mux_out); /*always@(*) begin case(Sel_1,Sel_2) 0:Mux_out=W; 1:Mux_out=X; 2:Mux_out=Y; 3:Mux_out=Z; endcase end*/ always@(*) begin case(Op) 0:Alu_out=Mux_out+Result; 1:Alu_out=Result-Mux_out; endcase end always@(posedge clk) begin if(Clr) Result<=0; else if(En) Result<=Alu_out; end endmodule module Control_Unit(clk,Start,Clr,En,Sel_1,Sel_2,Op); output Clr,En; output Sel_1,Sel_2; output Op; input clk,Start; reg Clr,En; reg Sel_1,Sel_2; reg Op; reg[3:0] next_state; reg[3:0] present_state; parameter[3:0] S0=0,S1=1,S2=2,S3=3,S4=4,S5=5,S6=6,S7=7,S8=8,S9=9,S10=10,S11=11,S12=12; always@(present_state,Start) begin case(present_state) S0:if(Start==0) next_state <=S0; else next_state <=S1; S1:next_state<=S2; S2:next_state<=S3; S3:next_state<=S4; S4:next_state<=S5; S5:next_state<=S6; S6:next_state<=S7; S7:next_state<=S8; S8:next_state<=S9; S9:next_state<=S10; S10:next_state<=S11; S11:next_state<=S12; S12:next_state<=S0; default:next_state<=S0; endcase end always@(posedge clk) begin present_state<=next_state; end always@(present_state) begin case(present_state) S0: {Clr,En,Sel_1,Sel_2,Op} = 5'b00000 ; S1: {Clr,En,Sel_1,Sel_2,Op} = 5'b10000 ; S2: {Clr,En,Sel_1,Sel_2,Op} = 5'b01111 ; S3: {Clr,En,Sel_1,Sel_2,Op} = 5'b01111 ; S4: {Clr,En,Sel_1,Sel_2,Op} = 5'b01100 ; S5: {Clr,En,Sel_1,Sel_2,Op} = 5'b01100 ; S6: {Clr,En,Sel_1,Sel_2,Op} = 5'b01011 ; S7: {Clr,En,Sel_1,Sel_2,Op} = 5'b01011 ; S8: {Clr,En,Sel_1,Sel_2,Op} = 5'b01011 ; S9: {Clr,En,Sel_1,Sel_2,Op} = 5'b01011 ; S10: {Clr,En,Sel_1,Sel_2,Op} = 5'b01101; S11: {Clr,En,Sel_1,Sel_2,Op} = 5'b01101; S12: {Clr,En,Sel_1,Sel_2,Op} = 5'b01101; default : {Clr,En,Sel_1,Sel_2,Op} = 5'b00000; endcase end /*assign Clr=(present_state==S1); assign En=(present_state==S2)||(present_state==S3)||(present_state==S4)||(present_state==S5)||(present_state==S6)||(present_state==S7)||(present_state==S8)||(present_state==S9)||(present_state==S10)||(present_state==S11)||(present_state==S12); assign Sel=(present_state==S12); assign Op=(present_state==S12);*/ endmodule module ControlDataPath_Unit(clk,Start, W, X, Y, Z,Result); input clk,Start; input [7:0] W, X, Y, Z; output [13:0] Result; wire Clr,En,Sel_1,Sel_2,Op; Control_Unit P(.clk(clk),.Start(Start),.Clr(Clr),.En(En),.Sel_1(Sel_1),.Sel_2(Sel_2),.Op(Op)); DataPath_Unit P2(.clk(clk),.Clr(Clr),.En(En),.Op(Op),.W(W),.X(X),.Y(Y),.Z(Z),.Sel_1(Sel_1),.Sel_2(Sel_2),.Result(Result)); endmodule Here's my code. Hope anyone can help me.
doc_23525424
I know the properties ( Max, Min and Value ) and also to increment the value. But i don't know to use it while loading data from database for example. Or how to use it by downloading a file from database. Or loading datagridview (e.g.with 1000 row), so it takes time, but i want to display a progress bar for it. How can i know the max value for these examples? i mean the concept of the use of progress bar. A: I would suggest getting the size of byte from the data your dealing with, then use an asynchronous operation which will pass parameter to another method each time new bytes are gained. in this case you can use something like this: setProgress(byte[] bytesx){ progressbar.value = dProgress = 100.0 * bytesx / FileSize; }
doc_23525425
http://dl.dropbox.com/u/13722201/Dorset%20Designs/home.html when i resize my browser the top div #header expands below my navigation bar and i want it to stay flush, but i still want the images to adjust size sorry about the messy code thanks in advance arran, 16 A: This is a super simple fix, you just need to define the width of your divs in css. A: Remove the width: 100% and height: auto from the images and give them a fixed height, equivalent to the distance between the top of the frame and the top of the navigation bar. For example, changing #webdesign to just height:95px fixes the image's dimensions.
doc_23525426
messageBox.html("Processing, please wait..."); // run hefty script messageBox.html("Finished!"); But the page blocks before the message is displayed, even though the messageBox.html() statement comes first. Why is this? A: Sometimes it makes sense to fire the "hefty script" in a timeout. messageBox.html("Processing, please wait..."); setTimeout(function () { heftyScript(); messageBox.html("Finished!"); }, 1); The reason this happens is because it often holds UI updates until the end of the event loop (after your "hefty" script has finished). Setting a timeout ensures that hefty script doesn't run until a subsequent iteration of the event loop (letting the UI update at the end of the current iteration beforehand). A: I would consider Web Workers in this case: http://www.html5rocks.com/en/tutorials/workers/basics/ UPDATE: If for some reason you cannot use them then you should split your processing on smaller chunks and run them asynchronously. Locking UI is not an option. Here is what you can do: function heftyScript() { var arr = [...]; var chunk_start = 0; function do_chunk() { for( var i = 0; i < 100; ++i ) { // 100 items per chunk if( chunk_start >= arr.length) return; process( arr[chunk_start++] ); // process one element } window.setTimeout(do_chunk,10); } do_chunk(); } A: It depends where the time is being spent. If it's downloading and parsing the JavaScript file, the messageBox.html() must be pure html or you do it in a script block before referencing the external file. If the time spent is running that long function then setTimeout(function () { heftyScript(); messageBox.html('finished'); }, 1); works wonderfully.
doc_23525427
import numpy import scikits.statsmodels.api as sm y = numpy.random.randn(10) x = numpy.random.randn(10, 18) x = sm.add_constant(x, prepend=True) model = sm.OLS(y,x).fit() model.summary() #CREATES DIVIDE BY ZERO ERROR In the traceback the divide by zero occurs in linear_model.pyc @cache_readonly def rsquared_adj(self): return 1 - (self.nobs - 1)/sef.df_resid * (1 - self.rsquared) @cache_readonly A: In the example there are more variables (columns) in x than observations (rows). As a consequence you have a perfect fit. None of the result statistics make any statistical sense in this case. The zero division error in rsquared_adj occurs since df_resid is zero. summary() is calling some attributes and methods that raise the exception. You will also get similar exceptions when you call any of those attributes yourself. I think statsmodels should raise a proper informative exception in this case, instead of letting it break at some arbitrary points. A: This has been fixed in master. Now, summary() will simply print nan. https://github.com/statsmodels/statsmodels/issues/868
doc_23525428
A: Check out System.DirectoryServices (An ASP.NET 2.0 reference): C#-example to get groups: using System.DirectoryServices; public class test { private void main() { foreach (string @group in GetGroups()) { Debug.Print(@group); } } public List<string> GetGroups() { DirectoryEntry objADAM = default(DirectoryEntry); // Binding object. DirectoryEntry objGroupEntry = default(DirectoryEntry); // Group Results. DirectorySearcher objSearchADAM = default(DirectorySearcher); // Search object. SearchResultCollection objSearchResults = default(SearchResultCollection); // Results collection. string strPath = null; // Binding path. List<string> result = new List<string>(); // Construct the binding string. strPath = "LDAP://stefanserver.stefannet.local"; //Change to your ADserver // Get the AD LDS object. try { objADAM = new DirectoryEntry(strPath); objADAM.RefreshCache(); } catch (Exception e) { throw e; } // Get search object, specify filter and scope, // perform search. try { objSearchADAM = new DirectorySearcher(objADAM); objSearchADAM.Filter = "(&(objectClass=group))"; objSearchADAM.SearchScope = SearchScope.Subtree; objSearchResults = objSearchADAM.FindAll(); } catch (Exception e) { throw e; } // Enumerate groups try { if (objSearchResults.Count != 0) { foreach (SearchResult objResult in objSearchResults) { objGroupEntry = objResult.GetDirectoryEntry(); result.Add(objGroupEntry.Name); } } else { throw new Exception("No groups found"); } } catch (Exception e) { throw new Exception(e.Message); } return result; } } VB-example to get groups: Imports System.DirectoryServices Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load For Each group As String In GetGroups() Debug.Print(group) Next End Sub Public Function GetGroups() As List(Of String) Dim objADAM As DirectoryEntry ' Binding object. Dim objGroupEntry As DirectoryEntry ' Group Results. Dim objSearchADAM As DirectorySearcher ' Search object. Dim objSearchResults As SearchResultCollection ' Results collection. Dim strPath As String ' Binding path. Dim result As New List(Of String) ' Construct the binding string. strPath = "LDAP://stefanserver.stefannet.local" 'Change to your ADserver ' Get the AD LDS object. Try objADAM = New DirectoryEntry(strPath) objADAM.RefreshCache() Catch e As Exception Throw e End Try ' Get search object, specify filter and scope, ' perform search. Try objSearchADAM = New DirectorySearcher(objADAM) objSearchADAM.Filter = "(&(objectClass=group))" objSearchADAM.SearchScope = SearchScope.Subtree objSearchResults = objSearchADAM.FindAll() Catch e As Exception Throw e End Try ' Enumerate groups Try If objSearchResults.Count <> 0 Then Dim objResult As SearchResult For Each objResult In objSearchResults objGroupEntry = objResult.GetDirectoryEntry result.Add(objGroupEntry.Name) Next objResult Else Throw New Exception("No groups found") End If Catch e As Exception Throw New Exception(e.Message) End Try Return result End Function End Class A: Microsoft .NET Framework provides a standard library for working with Active Directory: System.DirectoryServices namespace in the System.DirectoryServices.dll. Microsoft recommends using two main classes from the System.DirectoryServices namespace: DirectoryEntry and DirectorySearcher. In most cases, it is enough to use DirectorySearcher class only. You can find some examples in this CodeProject article.
doc_23525429
<div ng-controller="MainController"> <div ng-if="!isLoggedIn"> <!-- Should include MAININDEX.HTML here.........---> <div ng-include="'templates/mainindex.html'"></div> </div> <div ng-if="isLoggedIn"> <!-- Should include MAINLOGGEDIN.HTML here.........---> <div ng-include="'templates/mainloggedin.html'"></div> </div> </div> Once i logged in the second div will be showed. It is working perfectly but on my load of second div i wish to display a ui-view in that partials like below. <!----Header bar, Side bar, Navigation bar code goes here---> <section class="content-wrapper"> <div ui-view=""></div> </section> <!--footer bar code here---> My header bar and footer bar loads clearly as soon as my login is sucessfull but my ui-view is not loading up. I wish my home route to be loaded initially. But it is blank and i have to click someother route and then click the home to display it in my UI-View portion. My state routing code goes like this..... // For any unmatched url, redirect to /state1 $urlRouterProvider.otherwise("/home"); // // Now set up the states $stateProvider .state('index', { url: "/home", templateUrl: 'templates/main.html', controller: 'MainController', resolve: { loggedin: checkLoggedin } }) am i going wrong some where. Is my url routing goes fine.
doc_23525430
So when Im translating it always prints out each word written together without spaces inbetween. Heres what I have. Im using StringBuilder for obvious reasons. public class MorseCodeDecoder { public static String decode(String morseCode) { String word = ""; String character = ""; //count how much space is inbetween lines. StringBuilder codeTwo = new StringBuilder(); String[] output = morseCode.split(" "); for (int i = 0; i < output.length; i++) { Inside here I tried to do an seperate if-statement. if morseCode contains three spaces back to back append one space. //if(morseCode.contains(" ")) codeTwo.append(" "); (or \\s maybe, doesnt matter) switch (output[i]) { case " ": codeTwo.append(" "); break; case ".-": codeTwo.append("A"); break; case "-...": codeTwo.append("B"); break; case "-.-.": codeTwo.append("C"); break; case "-..": codeTwo.append("D"); break; case ".": codeTwo.append("E"); break; case "..-.": codeTwo.append("F"); break; case "--.": codeTwo.append("G"); break; case "....": codeTwo.append("H"); break; case "..": codeTwo.append("I"); break; case ".---": codeTwo.append("J"); break; case "-.-": codeTwo.append("K"); break; case ".-..": codeTwo.append("L"); break; case "--": codeTwo.append("M"); break; case "-.": codeTwo.append("N"); break; case "---": codeTwo.append("O"); break; case ".--.": codeTwo.append("P"); break; case "--.-": codeTwo.append("Q"); break; case ".-.": codeTwo.append("R"); break; case "...": codeTwo.append("S"); break; case "-": codeTwo.append("T"); break; case "..-": codeTwo.append("U"); break; case "...-": codeTwo.append("V"); break; case ".--": codeTwo.append("W"); break; case "-..-": codeTwo.append("X"); break; case "-.--": codeTwo.append("Y"); break; case "--..": codeTwo.append("Z"); break; } } return codeTwo.toString(); } } For input: .... . -.-- .--- ..- -.. . Expected output: "HEY JUDE" A: You can use regex instead of splitting by spaces... Something like this pattern: ([._])+\s* Explanation: We're looking for at least 1 instance of a dot (.) or underscore (_) followed by zero or more spaces... I've used it over this example: ._ _... _._ .._ ..._ .__ Which is: ABC UVW I'm not near a computer - but the program should look something like that: public static String decode(final String morseCode) { final Matcher matcher = pattern.matcher(morseCode); final StringBuilder builder = new StringBuilder(); while(matcher.find()) { builder.append(getLetter(matcher.group().trim())); } return builder.toString(); } Assuming getLetter() is your switch case. More of a nitpick - instead of using this massive switch case you should use a static map that will contain the mapping between the symbols and letters and initialize it on the static constructor ( https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html ) Hope that helps. A: Your problem is that since your letters and your words share a delimiter, when you split by a single space, you are effectively removing your word spacing completely, so the switch statement never gets a chance to read them. There are two solutions I can imagine. The first is the code I have below. Since morse code only uses a specific set of characters, you can simply replace your word delimiter with a character outside of the alphabet and then detect that instead. For the second possible solution, if you would like to keep the integrity of the input, then you could also first split by the three spaces to separate each word, and then use your switch statement on each word, appending a space after each word has been successfully translated. This would require two loops (outer loop for the words and inner loop for the letters). public class MorseCodeDecoder { public static String decode(String morseCode) { String word = ""; String character = ""; //count how much space is inbetween lines. StringBuilder codeTwo = new StringBuilder(); morseCode.replace(" ", "|"); String[] output = morseCode.split(" "); for (int i = 0; i < output.length; i++) { switch (output[i]) { case "|": codeTwo.append(" "); break; case ".-": codeTwo.append("A"); break; //etc. } return codeTwo.toString(); } }
doc_23525431
@SpringBootApplication(scanBasePackages = "com.project.subproject") public class Application { public static void main(String args[]) { new SpringApplicationBuilder(Application.class) .properties("spring.config.name=application-subproject-default").run(args); } } This application works perfectly fine with its own datasource, controllers & advice Child project is added : <dependency> <groupId>com.project.subproject</groupId> <artifactId>subproject</artifactId> <version>0.0.1-SNAPSHOT</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </exclusion> </exclusions> Parent project Spring boot application : @SpringBootApplication(scanBasePackages = "com.project") public class MainApplication { public static void main(String args[]) { new SpringApplicationBuilder(MainApplication.class).properties("spring.config.name=application-parent-default").run(args); } } application-parent-default.yml spring: application: name: parent Subproject is getting scanned from the parent, but the datasource initialization is failing. Unsatisfied dependency expressed through field 'jdbcTemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active) Looks like the @SpringBootApplication in the child project is not getting invoked to initialize the yml file. Any insights will be helpful
doc_23525432
<!DOCTYPE html> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <title>Home</title> <link rel="stylesheet" href="/site/themes/theme/css/theme.css"> </head> <body class="flexible-layout"> <div id="app"> <header style="background-image: url(/site/themes/theme/img/covers/cover-18.jpg)"> <b-container> <div class="component-nav"> <b-navbar type="dark" variant="dark" class="bg-transparent" fixed="top"> <b-navbar-nav> <b-navbar-brand href="/" tag="h1" class="mb-0 logo">Hallowelt.io</b-navbar-brand> <b-nav-item href="/">Home</b-nav-item> <b-nav-item href="/about">About</b-nav-item> </b-navbar-nav> </b-navbar> </div> </b-container> <b-container> <b-card> Test </b-card> </b-container> </header> <b-container class="content"> <main role="main" class="container mt-4"> <div class="hero"> <b-jumbotron header="Test" lead="Test"> <p>Dies ist ein <strong>test</strong></p> </b-jumbotron> </div> <p>Dies ist ein Test</p> </main> </b-container> <footer class="pt-4"> <div class="text-center py-3">© 2019 </div> </footer> </div> <script src="/site/themes/theme/js/theme.js"></script> </body> </html> This is my custom css: html, body { margin: 0; padding: 0; width: 100%; } body { font-family: "Helvetica Neue", sans-serif; font-weight: lighter; } header { width: 100%; height: 75vh; background-size: cover; } .navbar { padding-top: 0.625rem; padding-bottom: 0.625rem; min-height: 75px; margin-bottom: 20px; box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.15); font-weight: normal; font-size: large; -webkit-transition: all .3s ease 0s; transition: all .3s ease 0s; } .navbar.bg-transparent{ background-color: #343a40 !important; opacity: 0.6; filter: alpha(opacity=50) !important; } .navbar a { vertical-align: middle; } Alright - now what I'd like to archive: I would like to add some content to the <header>: Maybe something like a slider or just a simple card. I could do something like this: header .container { padding-top: 100px; } But I don't think that's the right way how to do that. So my question: What is a valid way to add elements like cards, jumbotron etc. inside the <header> section? A: It's just like inside any other section. Just add the element in the html code and in the css file you do the styling. A: Just give your card a class name. Then, using css selectors, find your class and add some styling to it. Otherwise, you can use the boostrap-vue properties for a b-card and style it with that. https://bootstrap-vue.js.org/docs/components/card so instead of... <b-card> Test </b-card> use the props, from the link above... <b-card title="Card Title" img-src="https://picsum.photos/600/300/?image=25" img-alt="Image" img-top tag="article" style="max-width: 20rem;" class="mb-2"> <b-card-text> Some quick example text to build on the card title and make up the bulk of the card's content. </b-card-text> <b-button href="#" variant="primary">Go somewhere</b-button>
doc_23525433
#pragma mark UIActionSheetDelegate - (IBAction)displayActionSheet:(id)sender { UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Take photo", @"Choose photo from gallery", nil]; actionSheet.actionSheetStyle = UIActionSheetStyleDefault; [actionSheet showInView:self.view]; } - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { switch (buttonIndex) { case 0: [self takePhoto]; break; case 1: [self choosePhoto]; break; } } #pragma mark UIImagePickerControllerDelegate - (void)takePhoto { UIImagePickerController *pickerControllerTakePhoto = [[UIImagePickerController alloc] init]; [pickerControllerTakePhoto setSourceType:UIImagePickerControllerSourceTypeCamera]; [pickerControllerTakePhoto setDelegate:self]; [self presentViewController:pickerControllerTakePhoto animated:YES completion:nil]; } - (void)choosePhoto { UIImagePickerController *pickerControllerChoosePhoto = [[UIImagePickerController alloc] init]; [pickerControllerChoosePhoto setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; [pickerControllerChoosePhoto setDelegate:self]; [self presentViewController:pickerControllerChoosePhoto animated:YES completion:nil]; } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *myPhoto = [info objectForKey:UIImagePickerControllerOriginalImage]; [photoView setImage:myPhoto]; [self dismissViewControllerAnimated:YES completion:NULL]; } My 'plus' or 'add' button calls action sheet with dialog, so I choose the photo from gallery and result is like on second screenshot. A: Set the image views properties: imageView.clipsToBounds = YES; imageView.contentMode = UIViewContentModeScaleAspectFill; Both can be set in Interface Builder. A: So I've found the line of code that disturbed me, this all because of my custom cells which I put in order to my tableview: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = nil; if (indexPath.row == 0) { photoView = (UIImageView *)[photoCell viewWithTag:1]; // this is the first custom cell in my tableview and this line which I put on the model of the book isn't needed cell = photoCell; ...............................
doc_23525434
There have been many suggestions made on Stack Overflow which do not work for me, not limited to: * *flex grow 1 *flex 1 *onStartShouldSetResponder={() => true} *import { ScrollView } from 'react-native-gesture-handler'; *Wrapping ScrollView in a View component *nestedScrollEnabled={true} Is there a way to force scroll or android or is it just impossible? Here is the code: import { StyleSheet, Text, View, TextInput, Pressable, ScrollView } from 'react-native'; import {useState, useEffect} from 'react' import axios from 'axios' import SelectDropdown from 'react-native-select-dropdown' import { Formik } from 'formik' export default function App() { const [price, setPrice] = useState(); const options = ["ARS", "ARD", "BRL", "CAD", "CHF", "CLP", "CNY", "CZK", "DKK", "EUR", "GBP", "HKD", "HRK", "HUF", "INR", "ISK", "JPK", "KRW", "NZD", "PLN", "RON", "RUB", "SEK", "SGD", "THB", "TRY", "TWD", "USD"] const [selected, setSelected] = useState(options[0]) const [amount, setAmount] = useState('') const [calculatedAmount, setCalculatedAmount] = useState() useEffect(() => { axios.get('https://blockchain.info/ticker') .then(data => { setPrice(data) }) }, []) const fetchData = () => { axios.get(`https://blockhain.info/tobtc?currency=${selected}&value=${amount}`) .then(data => { setCalculatedAmount(data.data) console.log(calculatedAmount) }) } const handleSubmit = (e) => { e.preventDefault() fetchData() } const handleAmountChange = (e) => { e.preventDefault() setAmount(e.target.value) } if (!price || price === undefined ) { return null } const Form = ({ onSubmit }) => { <View> <Text className="py-10 text-xl">Enter value: <TextInput className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" id="amount" placeholder="Enter value in selected currency" value={amount} onChange={handleAmountChange} data-cy="amount"></TextInput></Text> <Text className="text-center"><Pressable className="p-5 mb-2 mr-2 overflow-hidden text-2xl text-gray-900 rounded-lg group bg-gradient-to-br from-purple-600 to-blue-500 group-hover:from-purple-600 group-hover:to-blue-500 hover:text-white text-black font-bold focus:ring-4 focus:outline-none focus:ring-blue-300 dark:focus:ring-blue-800" id="convert-button" type="submit"><Text>Calculate!</Text></Pressable></Text> <Text id="#calculatedamount" className="text-xl py-8 bg-gray-100 px-2 font-bold rounded-md" data-cy="submit">Value: {calculatedAmount} BTC</Text> </View> } return ( <ScrollView className="h-screen bg-blue-100" nestedScrollEnabled={true}> <View className="py-10"> <Text className="text-xl text-center m-auto text-black font-bold">Current Prices</Text> </View> <View className="md:flex justify-around h-full"> <View className="text-center text-2xl m-auto bg-gray-100 p-20 rounded-md shadow-2xl max-w-[75%]"> <Text className="text-md font-bold">(£) {price.data.GBP.symbol} {price.data.GBP.last} BTC</Text> </View> <View className="text-center text-2xl m-auto bg-gray-100 p-20 rounded-md shadow-2xl max-w-[75%]"> <Text className="text-md font-bold">(€) {price.data.EUR.symbol} {price.data.EUR.last} BTC</Text> </View> <View className="text-center text-2xl m-auto bg-gray-100 p-20 rounded-md shadow-2xl max-w-[75%]"> <Text className="text-md font-bold">($) {price.data.USD.symbol} {price.data.USD.last} BTC</Text> </View> </View> <View className="h-screen flex "> <View className="m-auto bg-blue-300 p-20 rounded-md shadow-2xl"> <Text className="text-3xl font-bold py-10">Convert Currency into BTC</Text> <Text className="text-xl"> Select a currency: <SelectDropdown className="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" id='currency' value={selected} data-cy="select" onChange={(e) => setSelected(e.target.value)}> {options.map((value) => (<Text> <Text value={value} key={value}> <Text> {value}</Text> </Text> </Text>))} </SelectDropdown></Text> <Formik initialValues={{ amount: '' }} onSubmit={handleSubmit}> {({ handleSubmit }) => <Form onSubmit={handleSubmit} />} </Formik> </View> </View> </ScrollView> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
doc_23525435
Thank you! Research and reading up
doc_23525436
Edit: Not sure of its importance but decided to add this anyway, im using oculus rift controller's Here's the (edit: UPDATED) code: using System.Collections; using System.Collections.Generic; using UnityEngine; using EZEffects; public class adamadam : MonoBehaviour { public SteamVR_TrackedController controllerRight; private SteamVR_TrackedObject trackedObj; private SteamVR_Controller.Device device; private SteamVR_TrackedController controller; public EffectTracer TracerEffect; public Transform muzzleTransform; // Use this for initialization void Start() { // controller = controllerRight.GetComponent<SteamVR_TrackedController>(); controller.TriggerClicked += TriggerPressed; // trackedObj = controllerRight.GetComponent<SteamVR_TrackedObject>(); } private void TriggerPressed(object sender, ClickedEventArgs e) { Debug.Log("Clicked"); ShootWeapon(); } public void ShootWeapon() { RaycastHit hit = new RaycastHit(); Ray ray = new Ray(muzzleTransform.position, muzzleTransform.forward); device = SteamVR_Controller.Input((int)trackedObj.index); device.TriggerHapticPulse(750); TracerEffect.ShowTracerEffect(muzzleTransform.position, muzzleTransform.forward, 250f); if (Physics.Raycast(ray, out hit, 5000f)) { if (hit.collider.attachedRigidbody) { Debug.Log("Hit" + hit.collider.gameObject.name); } } } }
doc_23525437
if ( null == name ) { ... } Basically, null should be always on the right side of statement e.g. if ( name == null ) { ... } A: Sevntu has a custom check called AvoidConstantAsFirstOperandInConditionCheck which does what you want. $ cat TestClass.java public class TestClass { void method() { if ( null == name ) {} // violation if ( name == null ) {} // OK } } $ cat TestConfig.xml <?xml version="1.0"?> <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "https://checkstyle.org/dtds/configuration_1_3.dtd"> <module name="Checker"> <property name="charset" value="UTF-8"/> <module name="TreeWalker"> <module name="com.github.sevntu.checkstyle.checks.coding.AvoidConstantAsFirstOperandInConditionCheck" /> </module> </module> $ java -jar checkstyle-8.9-sevntu-1.29.0-all.jar -c TestConfig.xml TestClass.java Starting audit... [ERROR] TestClass.java:3: Constant have to be second operand of '=='. [AvoidConstantAsFirstOperandInCondition] Audit done. Checkstyle ends with 1 errors.
doc_23525438
Here is an excerpt from the directory: 0091_000100_0000_0000_0001_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000110_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000120_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000200_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000300_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000310_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000320_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000330_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000400_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000410_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000420_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_001120_0102_0000_0003_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0096_000100_0000_0000_0001_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000110_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000120_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000200_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000300_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000310_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000320_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000330_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000400_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000410_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000420_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000430_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000440_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000450_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0097_000100_0000_0000_0001_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000110_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000120_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000200_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000300_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000310_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000320_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000330_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000400_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000410_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000420_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000430_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps This is what I'm trying to get: 0091_000100_0000_0000_0001_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000110_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000120_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0091_000200_0000_0000_0002_000000__66_5_32_6_9_82856598585_60_3560351294_L_40_1_52_9_42_97_58_53.ps 0096_000100_0000_0000_0001_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000110_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000120_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0096_000200_0000_0000_0002_000000__85_5_2__2_37732144298_48_1790154593_L_52_26_17_77_41_43.ps 0097_000100_0000_0000_0001_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000110_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000120_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps 0097_000200_0000_0000_0002_000000__81_5_46_2_48_2146991211_65_1953946853_L_44_6_72_1_58_71_77_49.ps My try so far works but is somewhat unpractical: #!/bin/sh for f in *.ps; do case $f in (0091_000100*.ps|0091_000110*.ps|0091_000120*.ps|0091_000200*.ps) ;; (*) rm -- "$f";; esac done I have to write every start of the filename I want to keep. One problem: The script doesn't match the 0096_* and 0097_* files and all the others omitted for readability. The format of the filename is always the same up to the double underscore. The values in the number groups might change. Is there a way to match for the second group? My experimentation wasn't successful so far. Thank you for your help! A: I like using find for best performance when dealing with a large count of files. This regex should yield the same results: find . -type f -name '*.ps' |egrep "000[12]{1}[012]{1}" |xargs rm -f A: Assuming a directory has only regular files... ls *.ps | egrep -v '^[0-9]{4}_000100_|^[0-9]{4}_000110_|^[0-9]{4}_000120_|^[0-9]{4}_000200_' | xargs rm -f A: Seems like ls *.ps | awk -F_ '$2 < 100 || $2 > 200' might be the list of files you want to delete. After verifying that, rm $(ls *.ps | awk -F_ '$2 < 100 || $2 > 200') As long as no file has whitespace or glob characters in its name. (If they do, use xargs)
doc_23525439
SELECT title, karma, DATE(date_uploaded) as d FROM image ORDER BY d DESC, karma DESC This will give me a list of image records, first sorted by newest day, and then by most karma. There is just one thing missing: I want to only get the x images with the highest karma per day. So for example, per day I only want the 10 most karma images. I could of course run multiple queries, one per day, and then combine the results. I was wondering if there is a smarter way that still performs well. I guess what I am looking for is a way to use LIMIT x,y per group of results? A: You can do it by emulating ROW_NUMBER using variables. SELECT d, title, karma FROM ( SELECT title, karma, DATE(date_uploaded) AS d, @rn := CASE WHEN @prev = UNIX_TIMESTAMP(DATE(date_uploaded)) THEN @rn + 1 ELSE 1 END AS rn, @prev := UNIX_TIMESTAMP(DATE(date_uploaded)) FROM image, (SELECT @prev := 0, @rn := 0) AS vars ORDER BY date_uploaded, karma DESC ) T1 WHERE rn <= 3 ORDER BY d, karma DESC Result: '2010-04-26', 'Title9', 9 '2010-04-27', 'Title5', 8 '2010-04-27', 'Title6', 7 '2010-04-27', 'Title7', 6 '2010-04-28', 'Title4', 4 '2010-04-28', 'Title3', 3 '2010-04-28', 'Title2', 2 Quassnoi has a good article about this which explains the technique in more details: Emulating ROW_NUMBER() in MySQL - Row sampling. Test data: CREATE TABLE image (title NVARCHAR(100) NOT NULL, karma INT NOT NULL, date_uploaded DATE NOT NULL); INSERT INTO image (title, karma, date_uploaded) VALUES ('Title1', 1, '2010-04-28'), ('Title2', 2, '2010-04-28'), ('Title3', 3, '2010-04-28'), ('Title4', 4, '2010-04-28'), ('Title5', 8, '2010-04-27'), ('Title6', 7, '2010-04-27'), ('Title7', 6, '2010-04-27'), ('Title8', 5, '2010-04-27'), ('Title9', 9, '2010-04-26'); A: Maybe this will work: SELECT title, karma, DATE(date_uploaded) as d FROM image img WHERE id IN ( SELECT id FROM image WHERE DATE(date_uploaded)=DATE(img.date_uploaded) ORDER BY karma DESC LIMIT 10 ) ORDER BY d DESC, karma DESC But this is not very efficient, as you don't have an index on DATE(date_uploaded) (I don't know if that would be possible, but I guess it isn't). As the table grows this can get very CPU expensive. It might be simpler to just have a loop in your code :-).
doc_23525440
Also when I tested the db on local host, the incrementation was working correctly. EDIT: I also tried to use the command: 'SET @@auto_increment_increment=1', but it didnt work. Im not sure if I am doing it right. A: http://www.cleardb.com/developers/help/faq#general_16 auto-increment keys are partitioned between instances to prevent collision.
doc_23525441
But every time I am getting this ?(question)mark Image . I am sure that I have added the font Correctly In my Project and also in Plist: Here is my Project Setup: Step 1: Added Font Awesome File in My project Step :2 Installed Font Awesome in my Mac. Step : 3 Add Key In my pList File. Step 4: For Confirmation Checked the Font List in Storyboard: Step 5: Created a UILabel Programmatically and setting font like this: UILabel *lblFontAwesome = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 400)]; lblFontAwesome.center = self.view.center; lblFontAwesome.font = [UIFont fontWithName:@"FontAwesome" size:35]; [lblFontAwesome setText:@"\uf014"]; [self.view addSubview:lblFontAwesome]; Step 6: I have added Some Category files also. Step 7: Here what I am getting: I tried different solutions on net and also from SO.One is this . But None of them seems to work. I am always getting this ?. Note when i try %C then I am getting this Image: And yes with a warning: and Also this is not the correct icon. It's just showing unknown image. A: I am sure that I have added the font Correctly In my Project and also in Plist Well, don't be sure. Clearly you have not added it correctly. The problem is that, although the font file is in your project, it is not being copied into your app. Thus, it is not available in the running app. Here's how to fix that. In the project navigator (your first screen shot), select the FontAwesome.ttf file. Now look at the File inspector on the right. Now look at the Target Membership section. Make sure that the app target is checked.
doc_23525442
<ul> <li class="product product-cat"></li> <li class="product product-cat"></li> <li class="product product-cat"></li> <li class="product"></li> /*I want to add red border for this li item*/ <li class="product"></li> <li class="product"></li> </ul> A: You should be able to do the following: .product { width: 40px; height: 10px; background: yellow; margin: 4px 0; } .product-cat { background: green; } /** * the above code is only for demonstration purposes. * please check the code below */ .product:not(.product-cat) { border: 1px solid red; } .product:not(.product-cat) + .product { border: none; } <ul> <li class="product product-cat"></li> <li class="product product-cat"></li> <li class="product product-cat"></li> <li class="product"></li> <li class="product"></li> <li class="product"></li> </ul> This applies the desired border to all list items that only have the .product class and then skips over the first .product item and removes the border again.
doc_23525443
I have the following problem: If I create a new Delegate of type Action or Func it will be casted to a type of Delegate. var @delegate = Delegate.CreateDelegate(type, @object, methodInfo); But I need for a generic class the right casted object. Consider following example: class Example<T> { Type GenericType() { return typeof(T); } } static Example<T> Create<T>(T @delegate) { return new Example<T>(); } Example.Create(@delegate).GenericType(); This will return Delegate as type, since this was the type of the casted object (@delegate). One solution could be to cast the delegate like so: if(@delegate is Action) Example.Create((Action)@delegate).GenericType(); But since Delegate.CreateDelegate could also create Action or Func delegates, it is impossible to check all variations. I can't change the generic class, so i must cast the delegate. I hope i was able to explain my problem. I am not a native English speaker... Edit: The Problem is that typeof(T) not return the "real" type of the object. But i'm afraid there is no solution. A: What's wrong with @delegate.GetType() to get the actual type of the delegate? Also, a side note: you are misusing the term "boxing". A: If you can use .net 4.0 then your above works if you cast to dynamic Example.Create((dynamic)@delegate).GenericType(); If you cannot, then you just have to do a little reflection and abstraction. abstract class Example{ abstract Type GenericType(); } class Example<T>:Example { override Type GenericType() { return typeof(T); } } static Example Create(Delegate @delegate) { return (Example)Activator.CreateInstance(typeof(Example<>).MakeGenericType(new []{@delegate.GetType()})); } A: To answer my own question: It is not possible. :(
doc_23525444
PUT _ingest/pipeline/attachment { "description" : "Extract attachment information", "processors" : [ { "attachment" : { "field" : "data" } } ] } I ingest the document as follow: PUT myindex/_doc/my_id?pipeline=attachment { "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=" } And this is how it looks in elasticsearch: GET myindex/_search { "took" : 8, "timed_out" : false, "_shards" : { "total" : 1, "successful" : 1, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : { "value" : 1, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "myindex", "_type" : "_doc", "_id" : "my_id", "_score" : 1.0, "_source" : { "data" : "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=", "attachment" : { "content_type" : "application/rtf", "language" : "ro", "content" : "Lorem ipsum dolor sit amet", "content_length" : 28 } } ] } } But I have some doubds about the content , please, advice: * *Is it a best practice the extracted attachment content to be moved outside _source via some post processing in the ingestion_pipeline so it will be searchable? *If I suppress the "_source.data" as follow , will the extracted/indexed content be still searchable and how ? PUT myindex { "mappings": { "_source": { "excludes": [ "data" ] } } } *Is it best practice the entire _source field to be removed from the indexed document so the size to be reduced ? Thanks
doc_23525445
I would like to use random forest and for this reason I would like to convert in a different format like this: hour minute is it possible? thanks in advance A: You should try using strftime: df['timestamp'] = df['timestamp'].apply(lambda x: x.strftime('%H %M')) If you want the result in different columns, could you try adding the following code: df[['hour', 'minute']] = df['timestamp'].str.extract('(\d\d) (\d\d)') Hope this can help you!
doc_23525446
I am trying to retrieve data from a document stored in FireStore. I am following the example provided here: https://github.com/angular/angularfire2/blob/master/docs/firestore/documents.md What I am wondering: After having access to the document: this.itemDoc = afs.doc<Item>('items/1'); this.item = this.itemDoc.valueChanges(); How can I retrieve data from that document? I don't want . to use it in my html, but get the data from some fields and do something with it in TypeScript. Obviously this.item is not an array so item[0].fieldname doesn't work... TIA. A: this.item is an observable, you need to subscribe to get the data. this.itemDoc = afs.doc<Item>('items/1'); this.item = this.itemDoc.valueChanges(); this.item.subscribe(res=>{ console.log(res.fieldname); } A: //I assume you know how to use firebase with angular and ionic import { AngularFirestore } from 'angularfire2/firestore'; constructor(private firestore:AngularFirestore) { } readNote(){ this.readUsingObservable().subscribe(data => { console.log(data[0].textnote); //0 means accessing first object console.log(data[0].day); //textnote and day are fields in collection object }) } readUsingObservable():Observable<any>{ return this.firestore.collection('yourcollectionname').valueChanges(); }
doc_23525447
This works well for the first time when the app is installed. But when the device is restarted and the app is launched, all logic of detecting the location works, but the LocationBasedActivity is not launched. The call to startActivity is being made, but it returns without any error or exception, the following is the code snippet for launching the LocationBasedActivity from the service Intent intent = new Intent(MyBackgroundService.this, LocationBasesActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); I tried debugging this, got to the point where the call to Android's tried debugging the startActivity which in turn is calling This is on Android 4.4 on Tab E. Would really appreciate any help on this issue. Thanks
doc_23525448
it came with win8.1, we installed the 7 x64 Trying to execute jogl, java is crashing http://pastebin.com/gv6117NK it crashes when glLinkProgram is called Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) j jogamp.opengl.gl4.GL4bcImpl.dispatch_glLinkProgram1(IJ)V+0 j jogamp.opengl.gl4.GL4bcImpl.glLinkProgram(I)V+46 j javax.media.opengl.DebugGL4bc.glLinkProgram(I)V+9 j glsl.GLSLProgramObject.initializeProgram(Ljavax/media/opengl/GL3;Z)V+113 I am creating the shader using some code that I wrote in past, it always worked and I never got problems, so I am afraid it has something to do with the nvidia opengl driver.. I am initializing the program in this way public final void initializeProgram(GL3 gl3, boolean cleanUp) { _progId = gl3.glCreateProgram(); for (int i = 0; i < _vertexShaders.size(); i++) { gl3.glAttachShader(_progId, _vertexShaders.get(i)); } for (int i = 0; i < _fragmentShaders.size(); i++) { gl3.glAttachShader(_progId, _fragmentShaders.get(i)); } gl3.glLinkProgram(_progId); int[] params = new int[]{0}; gl3.glGetProgramiv(_progId, GL3.GL_LINK_STATUS, params, 0); if (params[0] != 1) { System.err.println("link status: " + params[0]); gl3.glGetProgramiv(_progId, GL3.GL_INFO_LOG_LENGTH, params, 0); System.err.println("log length: " + params[0]); byte[] abInfoLog = new byte[params[0]]; gl3.glGetProgramInfoLog(_progId, params[0], params, 0, abInfoLog, 0); System.err.println(new String(abInfoLog)); } gl3.glValidateProgram(_progId); if (cleanUp) { for (int i = 0; i < _vertexShaders.size(); i++) { gl3.glDetachShader(_progId, _vertexShaders.get(i)); gl3.glDeleteShader(_vertexShaders.get(i)); } for (int i = 0; i < _fragmentShaders.size(); i++) { gl3.glDetachShader(_progId, _fragmentShaders.get(i)); gl3.glDeleteShader(_fragmentShaders.get(i)); } } } Any tips? Both 337 and 340 drivers fail A: As jmaasing suggested, I had to force the use of the dedicated graphic card I also had to add "C:\Program Files\Internet Explorer" to the path for the IEShims.dll and update the retail win7 to the sp1 and various updates
doc_23525449
private IntPtr hHandle; private IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); public const Int64 FILESIZE = 1024 * 1024; private const string memoryfilename = "myfilename"; //CreateFileMapping [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern IntPtr CreateFileMapping( IntPtr hFile, IntPtr lpFileMappingAttributes, FileMapProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, [MarshalAs(UnmanagedType.LPStr)] string lpName); //OpenFileMapping [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr OpenFileMapping( FileMapAccess dwDesiredAccess, Int32 bInheritHandle, [MarshalAs(UnmanagedType.LPStr)] string lpName); [Flags] public enum FileMapAccess : uint { FileMapCopy = 0x0001, FileMapWrite = 0x0002, FileMapRead = 0x0004, FileMapReadWrite = 0x0006, FileMapAllAccess = 0x001f, FileMapExecute = 0x0020, } [Flags] enum FileMapProtection : uint { PageReadonly = 0x02, PageReadWrite = 0x04, PageWriteCopy = 0x08, PageExecuteRead = 0x20, PageExecuteReadWrite = 0x40, SectionCommit = 0x8000000, SectionImage = 0x1000000, SectionNoCache = 0x10000000, SectionReserve = 0x4000000, } //hHandle becomes non-zero hHandle= CreateFileMapping( INVALID_HANDLE_VALUE, IntPtr.Zero, FileMapProtection.PageReadWrite, (uint)0, (uint)FILESIZE, memoryfilename); //hHandle2 stays zero IntPtr hHandle2 = OpenFileMapping(FileMapAccess.FileMapWrite, 0, memoryfilename); //myerror is 2 ERROR_FILE_NOT_FOUND uint myerror = GetLastError(); //this works and I can read/write the file through UnmanagedMemoryStream pBuffer = MapViewOfFile(hHandle, FileMapAccess.FileMapWrite, 0, 0, (uint)FILESIZE); A: [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern IntPtr CreateFileMapping( IntPtr hFile, IntPtr lpFileMappingAttributes, FileMapProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, [MarshalAs(UnmanagedType.LPStr)] string lpName ); The DllImport attribute uses CharSet.Auto which means that the wide character version of the function will be used. You then pass an ANSI encoded string because you used UnmanagedType.LPStr. Which, as Hans says, means that your name will be mangled when the system interprets the ANSI encoded text you supplied as though it was UTF-16 encoded. [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr OpenFileMapping( FileMapAccess dwDesiredAccess, Int32 bInheritHandle, [MarshalAs(UnmanagedType.LPStr)] string lpName ); This time you omit CharSet.Auto and so the default of ``CharSet.Ansiis used. And so the ANSI version of the function is used, which matchesUnmanagedType.LPStr` this time. Hence the intended name is passed. All this explains why the system reports ERROR_FILE_NOT_FOUND. Fix the p/invoke declarations and all will be well. [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern IntPtr CreateFileMapping( IntPtr hFile, IntPtr lpFileMappingAttributes, FileMapProtection flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName ); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern IntPtr OpenFileMapping( FileMapAccess dwDesiredAccess, bool bInheritHandle, string lpName );
doc_23525450
What I had been doing (trivialized quite a bit): internal class FooBase : IDisposable { Socket baseSocket; private void SendNormalShutdown() { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool _disposed = false; protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { SendNormalShutdown(); } baseSocket.Close(); } } ~FooBase() { Dispose(false); } } internal class Foo : FooBase, IDisposable { Socket extraSocket; private bool _disposed = false; protected override void Dispose(bool disposing) { if (!_disposed) { extraSocket.Close(); } base.Dispose(disposing); } ~Foo() { Dispose(false); } } A: Why complicate things when you don't need to? Since you don't encapsulate any unmanaged resources, you don't need all that mucking about with finalization. And, your classes are internal, which suggests that you control the inheritance hierarchy within your own assembly. So, the straighforward approach would be: internal class FooBase : IDisposable { Socket baseSocket; private void SendNormalShutdown() { // ... } private bool _disposed = false; public virtual void Dispose() { if (!_disposed) { SendNormalShutdown(); baseSocket.Close(); _disposed = true; } } } internal class Foo : FooBase { Socket extraSocket; private bool _disposed = false; public override void Dispose() { if (!_disposed) { extraSocket.Close(); _disposed = true; } base.Dispose(); } } Even when you do have unmanaged resources, I'd say you're much better off encapsulating them in their own disposable class and using them like you'd use any other disposable; as straighforward as the code above. A: The idea of this pattern is that you override the virtual Dispose method, calling base.Dispose if necessary. The base class takes care of the rest, calling the virtual Dispose method (and hence the correct implementation). The subclass should not need to also implement IDisposable (it is IDisposable via inheritance) A: I always turn to Joe Duffy's very in-depth study on this pattern. For me, his version is Gospel. http://joeduffyblog.com/2005/04/08/dg-update-dispose-finalization-and-resource-management/ The first thing to remember is that a finalizer is not needed most of the time. It's for clearing up unmanaged resources where you are directly holding native resources, i.e. only resources that do not have their own finalizer. Here's an example for a base-class subclass pair. // Base class #region IDisposable Members private bool _isDisposed; public void Dispose() { this.Dispose(true); // GC.SuppressFinalize(this); // Call after Dispose; only use if there is a finalizer. } protected virtual void Dispose(bool isDisposing) { if (!_isDisposed) { if (isDisposing) { // Clear down managed resources. if (this.Database != null) this.Database.Dispose(); } _isDisposed = true; } } #endregion // Subclass #region IDisposable Members private bool _isDisposed; protected override void Dispose(bool isDisposing) { if (!_isDisposed) { if (isDisposing) { // Clear down managed resources. if (this.Resource != null) this.Resource.Dispose(); } _isDisposed = true; } base.Dispose(isDisposing); } #endregion Note that the subclass has its own _isDisposed member. Also note null-checking on resources since you don't want any exceptions in these blocks. Luke A: When I just override the Dispose(bool disposing) call, it feels really strange stating that I implement IDisposable without having an explicit Dispose() function (just utilizing the inherited one), but having everything else. This is something you shouldn't be concerned with. When you subclass an IDisposable class, all of the "Dispose pattern" plumbing is already being handled for you by the base class. You really should do nothing but override the protected Dispose(bool) method, and track whether you've been disposed already (to properly raise ObjectDisposedException.) For details, see my blog post on Subclassing from an IDisposable class. Also, often, it's a good idea to consider encapsulating the IDisposable class instead of subclassing it. There are times when subclassing an IDisposable class is appropriate, but they are somewhat rare. Encapsulation is often a better alternative. A: The child class should override the virtual Dispose, do any disposing specific to the subclass, and call the superclass' Dispose, which in turn will do its own work. EDIT: http://davybrion.com/blog/2008/06/disposing-of-the-idisposable-implementation/ is the pattern I follow in such cases. Not the 'Disposable' class specifically, but the inheritance and overrides.
doc_23525451
When the page loads, jquery successfully populates the "currently saved settings" textboxes with the values read in from the server csv file using php. When I enter new values and then click the [submit] button to save these values, the server file gets updated successfully. And it is the next steps where the problem arises, I can use php to read the newly stored values back in from the server file and "alert" them to check that they are correct but the jquery lines to update the "currently saved settings" will not update. I have to refresh the webpage to get these textboxes to update. I should say that the "alerts" display the correct (newly saved) values so everything up to that point works fine it's just the following two jquery lines that work on page load don't seem to get executed at this point. Hopefully there's something dead simple I'm missing here. (The csv file itself is simply two parameters used by a complete separate and unrelated piece of software.) Help much appreciated. php file as follows: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>System Settings</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script> <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" type="text/javascript"></script> <?php $SystemSettings = explode(",",file_get_contents('Data/Settings.csv')); ?> <script type="text/javascript"> $(document).ready(function () { $("#txtStoredParam1").val("<?php echo $SystemSettings[0] ?>"); $("#txtStoredParam2").val("<?php echo $SystemSettings[1] ?>"); $("#btnSaveSettings").button(); }); </script> </head> <body> <?php if(isset($_POST['submit'])) { $File = "Data/Settings.csv"; $Handle = fopen($File, 'w'); $Data = $_POST['Param1'] . "," . $_POST['Param2']; fwrite($Handle, $Data); fclose($Handle); $SystemSettings = explode(",",file_get_contents('Data/Settings.csv')); ?> <script> // alert("<?php echo $SystemSettings[0] ?>"); // alert("<?php echo $SystemSettings[1] ?>"); $("#txtStoredParam1").val("<?php echo $SystemSettings[0] ?>"); $("#txtStoredParam2").val("<?php echo $SystemSettings[1] ?>"); </script> <?php } ?> <form id="Form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="SettingsForm" target="iFormResponse"> <h2>Parameter 1:</h2> <input id="txtParam1" type="text" name="Param1" /> <h2>Parameter 2:</h2> <input id="txtParam2" type="text" name="Param2" /> <p>&nbsp;</p> <p><input id="btnSaveSettings" type="submit" value="Save Settings" name="submit" /></p> <p>&nbsp;</p> <h3> Currently Saved Settings: </h3> <p> <label id="lblParam1">Parameter 1: </label><input id="txtStoredParam1" type="text" name="StoredParam1" /> <label id="lblParam2">Parameter 2: </label><input id="txtStoredParam2" type="text" name="StoredParam2" /></p> </form> <iframe name="iFormResponse" width="300" height="200" Style="display:none;"></iframe> </body> </html> A: Your first script block used $(document).ready() whereas the second does not. Therefore, the second block runs first and is overridden by the second. Delete the second block and move the code for the first block to the end of the page so that you have only one script block that is reused in both cases. But since you are using forms and PHP, why not just set the value of the input? <input id="txtParam2" type="text" name="Param2" value="<?php echo $systemSettings[0];?>" />
doc_23525452
A: The "redundancy" was by design (RFC 826), and can be useful in targeting different layers. In RFC 3927 there's what is known as Gratuitous Address Resolution Protocol (GARP), and in certain circumstances the redundancy, or lack of, plays an important role, especially in troubleshooting and monitoring networking stacks. Actually it's not rendunancy at all, the MAC (physical, layer 2) and IP (logical, layer 3) addresses are not the same thing. They serve different purposes on different network layers. On large scale networks it's quite common to observe changes in the MAC/ARP/Source/Dest information, and at times can seem almost incorrect. For example, you might see a host send an ARP request with its own address as the target address. Depending on the exact situation, it might be telling us it's a link up/down event, maybe it's trying update other devices ARP tables, or possibly detecting an ip conflict and moving the ip to another NIC. I could get into clustering, failovers — the list goes on, although I would end up writing a book trying to explain it all. Hopefully this gives you a bit of insight about the "redundancy" you were questioning. ;-) More Info: RFC 826 / RFC 3927 / Wireshark Gratuitous ARP A: Although often used in conjunction with Ethernet, ARP by itself is an independent protocol. Imagine other link layer protocols that do not expose MAC addresses. ARP would not work in such circumstances if the sender field was not provided. A: There is no rule that the ARP protocol field sender mac address to be same as ethernet source mac address. Eg: Its possible in few applications where multiple interfaces of same host are on network, but one only interface sends arp responses for all interfaces.
doc_23525453
Here is the code: //this compiles fine HtmlInput usernameInput = form.getInputByName("username"); usernameInput.setValueAttribute(userName); //this fails to compile form.getInputByName("password").setValueAttribute(passWord); This is the error message I get when I compile using ANT and Java 1.6: [javac] E:\workspaces\europa\PortalTestSuite\src\com\carefirst\portal\test\controller\EAITest.java:32: com.gargoylesoftware.htmlunit.html.HtmlInput cannot be dereferenced [javac] form.getInputByName("password").setValueAttribute(passWord); [javac] ^ com.gargoylesoftware.htmlunit.html.HtmlInput cannot be dereferenced ? I've seen derefernce issues with Autoboxing, but not with objects. What does it mean in this context? And why does the code work one way and not the other? A: In fact, it's another problem. The API is public final <I extends HtmlInput> I getInputByName(String name) throws ElementNotFoundException. That means the method returns an instance of I (I extends HtmlInput). When you write: HtmlInput usernameInput = form.getInputByName("username"); -> The class I is implicitly an HtmlInput. But when you write: form.getInputByName("password").setValueAttribute(passWord); -> The class I can't be found explicitly. If you want it to work, you have to write: form.<HtmlInput>getInputByName("password").setValueAttribute(passWord); -> this forces I to be an HtmlInput. Cordially, Jérôme. A: The function form.getInputByName is declared final as shown in the javadoc here The object HtmlInput is abstract thus on runtime time it is always implemented by an object that is extending HtmlInput. Due to the nature of final methods (it is never overridden so there is no callstack) the error comes beceause the compiler sees it as just htmlinput and not an implemented htmlinput.(ref)(he thinks there will be no callstack) assigning it to a new htmlinput object correctly invokes the callstack and thus makes the code viable again. thats what i think is going on here though i somehow dont manage to find version 2.5 yet can you link me please where you got it?
doc_23525454
I was thinking on using viewDidDisappear to save the timestamp when the app went to background and viewDidAppear for checking previously saved values and refresh if needed, but this methods are not getting called when switching between apps. How can I solve this in a easy way? A: use UIApplicationDidBecomeActive for resume and UIApplicationWillResignActive for handle goes background SwiftUI Text("check application state!") .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in print("User received on willResignActiveNotification!") } .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in print("User received on didBecomeActiveNotification!") } Swift 5.x > above override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(self.openAndCloseActivity), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.openAndCloseActivity), name: UIApplication.didBecomeActiveNotification, object: nil) } @objc func openAndCloseActivity(_ notification: Notification) { if notification.name == UIApplication.didBecomeActiveNotification{ // become active notifictaion }else{ // willResignActiveNotification } } Swift 5.x < below override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(self.closeActivityController), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.openactivity), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) } and handle the method as func closeActivityController() { } func openactivity() { //view should reload the data. } other notification types are extension NSNotification.Name { @available(iOS 4.0, *) public static let UIApplicationDidEnterBackground: NSNotification.Name @available(iOS 4.0, *) public static let UIApplicationWillEnterForeground: NSNotification.Name public static let UIApplicationDidFinishLaunching: NSNotification.Name public static let UIApplicationDidBecomeActive: NSNotification.Name public static let UIApplicationWillResignActive: NSNotification.Name public static let UIApplicationDidReceiveMemoryWarning: NSNotification.Name public static let UIApplicationWillTerminate: NSNotification.Name } A: Swift 5 let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(appBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) Methods : @objc func appMovedToBackground() { print("App moved to background!") } @objc func appBecomeActive() { print("App become active") } To remove observers override func viewWillDisappear(_ animated: Bool) { let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self, name:UIApplication.willResignActiveNotification, object: nil) notificationCenter.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) } A: UIApplicationDelegate has these two functions: applicationDidEnterBackground(_:) applicationDidBecomeActive(_:) These could well be what you need. A: Objective-C - (void)viewDidLoad { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appMovedToBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; } - (void)appMovedToBackground:(NSNotification *) notification { NSLog(@"App Moved To Background"); } - (void)appBecomeActive:(NSNotification *) notification { NSLog(@"App become active"); } Don't forget to clear notifications when view gets disappear A: If interested here is a RxSwift version NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).subscribe(onNext: { [weak self] _ in }).disposed(by: disposeBag) NotificationCenter.default.rx.notification(UIApplication.willResignActiveNotification).subscribe(onNext: { [weak self] _ in }).disposed(by: disposeBag)
doc_23525455
When I do NOT use -u or --line-buffer options, I can see the output for each thread after the thread has finished. Because my ssh commands take a while I want to see output as it occurs. When I try to use -u tagging does not work. When I try to use --line-buffer, I don't get any of the output, even after threads have finished. I've written this simple test command which behaves in the same way: parallel -q ssh user@{} 'ls && sleep 4 && ls' ::: host1 host2 I have been looking at this very similar question https://unix.stackexchange.com/questions/101360/scp-does-not-display-output-when-used-with-gnu-parallel but the suggested solution of using the script command did not work for me. Might be because my system is not linux. (Am using Solaris). Any help would be appreciated. A: If you want to run the same command on a bunch of machines, use --nonall. https://www.gnu.org/software/parallel/parallel_tutorial.html#Running-the-same-commands-on-all-hosts We need to determine whether it is due to ssh or it is a general problem. So test these: parallel --version parallel --line-buffer 'echo {}; sleep 4; echo {}' ::: a b c parallel --tag --line-buffer 'echo {}; sleep 4; echo {}' ::: a b c parallel -S host1 --line-buffer 'echo {}; sleep 4; echo {}' ::: a b c parallel -S host2 --line-buffer 'echo {}; sleep 4; echo {}' ::: a b c parallel -S host1,host2 --line-buffer 'echo {}; sleep 4; echo {}' ::: a b c parallel -S host1 --tag --line-buffer 'echo {}; sleep 4; echo {}' ::: a b c parallel -S host2 --tag --line-buffer 'echo {}; sleep 4; echo {}' ::: a b c parallel -S host1,host2 --tag --line-buffer 'echo {}; sleep 4; echo {}' ::: a b c Have you somehow enabled --compress (this would explain the behaviour)?
doc_23525456
cv::Mat cur_features; cv::goodFeaturesToTrack(current_image, cur_features, 400, 0.01, 0.01); Now, being the hard-headed individual, I am interested to see what cur_features is holding... I expected a 400x2 cv::Mat but instead I got a 400x1 cv::Mat No biggy, I think maybe its a direct index. However, for the LIFE of me I CANNOT extract a value from cur_features.at(0) and print it out. What am I doing wrong? I have seen the goodFeaturesToTrack_Demo.cpp. Some things to note on that demo that differ for mine. I tried the following calls given that example: std::cout << cur_features.size() << std::endl; // This throws a compile time error even though its in the example std::cout << cur_features.at<Point2f>(0).x << std::endl; //This throws a run time error. Could anyone direct me to some documentation that explains how to achieve my goal? The goodFeaturesToTrack tells you it returns an OutputArray which is a vector of corners, but nowhere does it describe what the type of those corners are. Where in the documentation would I look for this answer in case I get it with other methods? Edit: Also, whats the Point of Mat::type(). I cannot find where the returned value can be explained... I'm looking for an enumeration in the documentation but having trouble finding it. std::cout << current_image.type() << std::endl; //This returns 0 std::cout << cur_features.type() << std::endl; //This returns 13 A: As a suggestion, try to initialize matrices with dimensions and type cv::Mat cur_features(400,1,CV_32_FC1); //400x1 32 bits, 1 channel cv::Mat cur_features2(400,1,CV_32_FC2); //400x1 32 bits, 2 channels To get a value of a Mat int pos = 0; foat value = cur_features.at<float>(pos); cv::Vec2f value2 = cur_features2.at<Vec2f>(pos); // for a two channel, CV_23F image And a handy debug technique for Visual Studio that helped me a lot * *1- Right click cur_features when debugging. *2- QuickWatch *3- Write this: (float*)cur_features.data,400 *4- You will see all the values of the array A: It turns out that even though my goodFeaturesToTrack returns a 400x1, I was doing it on a black image and thus no corners. This caused cur_features.data == NULL Interesting situation where the C code seems to be easier and more user friendly than the C++ code. A: It says here: http://opencv.itseez.com/modules/imgproc/doc/feature_detection.html That you should give it a vector<Point2f> as the output array. It is declared as such in the goodFeaturesToTrack_Demo.cpp in my local copy of OpenCV: vector<Point2f> corners; ... /// Apply corner detection goodFeaturesToTrack( src_gray, corners, maxCorners, qualityLevel, minDistance, Mat(), blockSize, useHarrisDetector, k ); UPDATE: The link I gave above uses a template OutputArray argument for corners. The docs at http://opencv.willowgarage.com/documentation/cpp/imgproc_feature_detection.html for the 2.1 version of the library do state vector<Point2f>
doc_23525457
Now I want to replace content on posts with this status via functions.php. I tried something like this function block_by_status ($post_object) { global $wp_query; if( 'blocked' == $wp_query->post->post_status ) { return 'This post is blocked'; } } add_action('the_post','block_by_status'); But it doesn't work, please somebody help? A: So for the content you can do something as simple as: add_filter('the_content', 'block_by_status'); and to hide the title you can use: add_filter( 'the_title', 'block_by_status', 10, 2 ); If you want to go further than that, I suggest editing the template in the theme folder. For pages you need to edit page.php and for posts you need to edit posts.php or singular.php, depends on the theme you are using. So you can do something like this: In the functions.php file: function block_by_status ($post_object) { global $wp_query; if( 'blocked' == $wp_query->post->post_status ) { return true; } } and then in the files I referenced above (Depends on your theme): <?php if (!block_by_status()) { ?> <?php while (have_posts()) : the_post(); ?> <h1><?php the_title() ?></h1> <?php the_content() ?> <?php get_sidebar() ?> <?php endwhile; ?> <?php } else { echo 'This post is blocked'; } ?> So you use your function as a boolean and just hide what you dont want users to see.
doc_23525458
myConn = dr.connectDB(); myStmt = myConn.prepareCall("{call spViewUsers()}"); myStmt.execute(); myRS = myStmt.getResultSet(); while (myRS.next()){ String name = myRS.getString("userID"); cbUser.addItem(name); This is a simple login window where the username is populated into a JComboBox (cbUser). The code above works, but now I'm wondering if I can re-use the ResultSet to obtain the corresponding password when the cbUser value is changed, or do I have to store the ResultSet fields into an array. It'd be nice if I could get a specific row based on the value of a column (not the column's label). For example, let's say this is my table: userID userPassword ------------------- admin 123456 guest qwerty random abcd I want to get the value qwerty when guest is selected in cbUser. Is it possible? Thanks!
doc_23525459
type Title = String type Singer = [String] type Year = Int type Fan = String type Fans = [Fan] type Song = (Title, Signer, Year, Fans) type Database = [Song] songDatabase :: Database songDatabase = [("Wrapped up", ["Olly Murs"], 2014, ["Garry", "Dave", "Zoe", "Kevin", "Emma"]), ("Someone Like you", ["Adele"], 2011, ["Bill", "Jo", "Garry", "Kevin", "Olga", "Liz"]), ("Drunk in Love", ["Beyonce", "Jay Z"], 2014, ["tom", "Lucy"])] I think this would be done through list comprehension but I am new to Haskell and i am struggling to work out how to do it, if people could point me in the right direction that would be great!! A: You can use dropWhile to drop the elements before the tuple with "Someone like you". Since this returns the target tuple along with the rest of the list, you can then use drop 1 to get rid of that tuple: drop 1 $ dropWhile (\(title, _, _, _) -> title /= "Someone Like you") songDatabase [("Drunk in Love",["Beyonce","Jay Z"],2014,["tom","Lucy"])]
doc_23525460
Example: A * *Apple *Apricot B * *Banana *Blackberry and so on... To implement this I use the following code: // get glossary function glossary($post_id) { $all_posts = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'glossar', 'orderby' => 'title', 'order' => 'ASC', )); echo '<ul>'; if( $all_posts->have_posts()){ foreach( range( 'A', 'Z' ) as $letter ) { echo '<div class="group_letter"><div class="letter">' . $letter. '</div>'; while( $all_posts->have_posts() ){ $all_posts->the_post(); $title = get_the_title(); $name = get_post_field( 'post_name', get_post() ); $initial = strtoupper( substr( $title, 0, 1 ) ); if( $initial == $letter ){ echo '<li><a class="glossary-listing" href="/glossar/'. $name . '">' . $title . '</a></li>'; } } $all_posts->rewind_posts(); } } echo '</ul>'; } add_shortcode( 'glossary', 'glossary' ); So far it works, but now it shows letters for which there are no posts. This is how it looks now I have tried to do it with an if query, but so far, I am stuck. Can someone help me? Best regards and thank you! A: Sort the array using PHP sort() function then loop through the result <?PHP $list=['apples','popsicles','Zinger','donkeys','bananas','joe', 'Locusts','gazelles','Angels','Popsicle','Dongle','jump','cocoa' ]; //convert all elements to same case //sorting will sort by case $list =array_map('strtolower', $list); //sort the array sort($list); $last_letter=null; foreach($list as $item){ $current_letter=substr($item,0,1); if($last_letter!=$current_letter){ ?> <div style="margin:1rem;padding:1rem;background:#f5f5f5;"> <?=$current_letter?> </div> <?php $last_letter=$current_letter; } ?> <div style="margin:1rem;padding:1rem;background:#f5f5f5;"> <?=$item?> </div> <?PHP } ?> A: I am sure there is a better solution besides running 26 times through the while loop. Anyway, here is what you are looking for. // get glossary function glossary($post_id) { $all_posts = new WP_Query( [ 'posts_per_page' => -1, 'post_type' => 'glossar', 'orderby' => 'title', 'order' => 'ASC', ] ); echo '<ul>'; if ($all_posts->have_posts()) { foreach (range('A', 'Z') as $letter) { $foundPostable = false; while ($all_posts->have_posts()) { $all_posts->the_post(); $title = get_the_title(); $name = get_post_field( 'post_name', get_post() ); $initial = strtoupper(substr($title, 0, 1)); if ($initial === $letter) { if ($foundPostable === false) { $foundPostable = true; echo '<div class="group_letter"><div class="letter">' . $letter. '</div>'; } echo '<li><a class="glossary-listing" href="/glossar/'. $name . '">' . $title . '</a></li>'; } } $all_posts->rewind_posts(); } } echo '</ul>'; } add_shortcode( 'glossary', 'glossary' ); As for improvement, something like this might work as well. // get glossary function glossary($post_id) { $all_posts = new WP_Query( [ 'posts_per_page' => -1, 'post_type' => 'glossar', 'orderby' => 'title', 'order' => 'ASC', ] ); echo '<ul>'; $startLetter = ''; while ($all_posts->have_posts()) { $all_posts->the_post(); $title = get_the_title(); $name = get_post_field( 'post_name', get_post() ); $initial = strtoupper(substr($title, 0, 1)); if ($initial !== $startLetter) { $startLetter = $initial echo '<div class="group_letter"><div class="letter">' . $letter . '</div>'; } echo '<li><a class="glossary-listing" href="/glossar/'. $name . '">' . $title . '</a></li>'; } echo '</ul>'; } add_shortcode('glossary', 'glossary');
doc_23525461
When user clicks on any alphabet the the respective data is loaded through ajax call. And profile of associated faculty is displayed. When user clicks on back to list buttion the page goes back to the previous page rather than page of selected alphabet. What i want to do is , When user clicks on back to list button user have to go the aphabet selected ajax call ? How can i do this ?
doc_23525462
First I generate the FluidGridItems and place them in the hashMap: private HashMap<PDIDefinition, List<FluidGridItem>> formItems = new HashMap<>(); private void generateModel() { for (PDIDefinition pdid : pdiDefinitions) { Fragment f = new Fragment(); f.setDefinition(pdid.getFragmentDefinition()); fragments.add(f); List<FluidGridItem> items = new ArrayList<>(); formItems.put(pdid, items); //((DynamicField)((FluidGridItem)formItems.get(pdid).get(0)).getData()).label; for (FragmentValueDefinition fvd : f.getDefinition().getFragmentValues()) { FragmentValue fv = new FragmentValue(); fv.setFragmentValueDefinition(fvd); fv.setFragmentId(f.getInner()); if (f.getValues() == null) { f.setValues(new ArrayList<>()); } f.getValues().add(fv); fragmentValues.add(fv); //not required? DynamicField df = new DynamicField((fv), items.size()); fields.add(df); if ("String".equals(fvd.getType())) { items.add(new FluidGridItem(df, "stringValue")); } if ("Integer".equals(fvd.getType())) { items.add(new FluidGridItem(df, "integerValue")); } if ("Date".equals(fvd.getType())) { items.add(new FluidGridItem(df, "dateValue")); } } } } Then I convert them as stated in Displaying Hashmap keys and values in a primefaces DataTable: public List<Map.Entry<PDIDefinition,List<FluidGridItem>>> getFormItemsForDisplay(){ Set <Map.Entry<PDIDefinition,List<FluidGridItem>>> s = formItems.entrySet(); return new ArrayList<>(s); } Finaly in my view I generate the form using dataList and fluidGrid: <p:dataList var="pdi" value="#{FormGenerator.formItemsForDisplay}" id="all" varStatus="loop" type="none"> <p:panel id="panel" header="#{pdi.key.getFragmentDefinition().getFragmentName()}" style="margin-bottom:1em; width:100%;"> <pe:fluidGrid id="fluidGrid" value="#{pdi.value}" var="data" hGutter="20" vGutter="10" widgetVar="fgwv_#{loop.index}"> <pe:fluidGridItem type="stringValue" id="txt_"> <div class="dynaFormLabel"> <p:outputLabel for="txt" value="#{data.label}"/> </div> <p:inputText id="txt" value="#{data.value}"/> </pe:fluidGridItem> <pe:fluidGridItem type="integerValue" id="int_"> <div class="dynaFormLabel"> <p:outputLabel for="int" value="#{data.label}"/> </div> <p:spinner id="int" value="#{data.value}" /> </pe:fluidGridItem> <pe:fluidGridItem type="dateValue" id="cal_"> <div class="dynaFormLabel"> <p:outputLabel for="cal" value="#{data.label}"/> </div> <p:calendar id="cal" value="#{data.value}" showOn="button"/> </pe:fluidGridItem> </pe:fluidGrid> </p:panel> </p:dataList> This results in the form I wish. My problem is, that only the values from the last iteration of the dataList are updated on the server (PDF in the image). Thanks for your Help. A: Solved it by replacing <p:dataList var="pdi" value="#{FormGenerator.formItemsForDisplay}" id="all" varStatus="loop" type="none"> by <c:forEach var="pdi" items="#{FormGenerator.formItemsForDisplay}" id="all" varStatus="loop"> Got the Idea from https://zenidas.wordpress.com/recipes/jsf-update-single-entry-in-a-datalist-like-component/
doc_23525463
My JS knowledge for popup is still at the .. level. Yet this site is using < a class="addcomment">Add Comments only. How does it trigger the popup? I searched its homepage html source and not seeing the case it pre-load the popup then hide and enable it when someone click the "Add Comments" link. A: Have a look at jQuery Its a javascript library that has feature and plugins that can achieve this very easily and supports most browsers. Have a look at the jquery dialog specifically: http://jqueryui.com/demos/dialog/ A: They are attaching a click event handler via jQuery. If you use your browser's dev tools and use the console, you could execute the following code to view the handlers bound. If you use Firefox and Firebug, you can use Firequery, which adds the .data() data to the dom view. $(".addcomment").data("events").click If you look at the external js file and search for "addcomment", you'll see the handler being bound.
doc_23525464
/usr/include/ /usr/lib/<pkg-arch>/ etc. I just noticed by running sort install_manifest.txt | uniq --count --repeated that some subprojects happened to export header files with different content but the same filename into /usr/include/, essentially overriding all but one. Needless to say that this causes the weirdest errors when trying to use the installed software. Is it possible to have make install fail on overrides?
doc_23525465
system('rm -Rf some_dir/*'); A: There is no need in asterisk in this command. If you want to remove directory together with files, remove the slash as well. Leaving the slash will delete files, but preserve directory. Also check comments on this page: http://php.net/manual/en/function.unlink.php A: It's probably because the user executing the script doesn't have privileges for deleting the directory(ies) or the shell isn't in the right directory. If you're running this via apache, chances are the process is owned by www-data. If the "some_dir" directory doesn't allow for write access by www-data, then it won't work. Since you're using a relative path (very dangerous), you need to ensure that the script is executing in the correct directory. I'd suggest you change the path to an absolute one if you can - "rm -rf /path/to/some_dir".
doc_23525466
What I observed is that when the application grows, the MainViewModel for view MainView keeps growing too. The 1st question: is it ever possible to separate the MainViewModel into multiple VMs? Or rather, multiple VMs control the same MainView that contains ribbons? And the 2nd question is under this scenario: The area under ribbon displays different Views when the user press buttons in the ribbon, that is, the "ActiveItem" is changed into other Views like GlobalDataView or BreakdownDataView etc.: <Grid x:Name="SubView" Background="White"> <ContentControl x:Name="ActiveItem" /> </Grid> Say now GlobalDataView is activated (assigned into the ContentControl), a contextual ribbon tab is shown upon the view's activation, and we assume that the contextual ribbon is with VM "ContextualRibbonGlobalDataViewModel" if there is a good solution for Question1. Also, the GlobalDataView itself also has its own VM called "GlobalDataViewModel". My question is: will it be possible to combine ContextualRibbonGlobalDataViewModel and GlobalDataViewModel? Since they both contain logic very specific to the GlobalDataView. If Q1 is not possible, is there a way to let GlobalDataViewModel controls the contextual ribbon inside MainView? My current approach is MainViewModel (MainView) + GlobalDataViewModel (GlobalDataView), such that the MainViewModel contains all the commands (actions in CM) for the GlobalData's view's contextual ribbon. MainViewModel has to use a mediator (the EventAggregator in CM) to talk to GlobalDataViewModel. Thanks. A: In my application, I have a "ShellView" Mainmodel, which contains multiple sub-containers. So it is entirely possible, especially if the sub-items are logically related and separated from the other parts. Learning how to do it was a little cumbersome, but It boils down to: [ImportingConstructor] public ShellViewModel(IWindowManager windowManager, IEventAggregator events) { this.windowManager = windowManager; this.logger = NLog.LogManager.GetCurrentClassLogger(); this.events = events; events.Subscribe(this); } Load another view: public async void loadview() { this.ActivateItem(new BlaViewModel(this.events, this.windowManager)); //displaying it in a tabcontrol, which is defined in XAML. It would probably work with something else too var thisView = (ShellView)this.GetView(); thisView.BlaViewM.SelectedItem } In the new view: public PowerPointViewModel(, IEventAggregator events, IWindowManager windowManager) { this.logger = NLog.LogManager.GetCurrentClassLogger(); events.Subscribe(this); this.events = events; this.DisplayName = "BLA"; this.windowManager = windowManager; } I am using events to pass messages around, especially if there needs to be interaction between the separate viewmodels. There is an ok tutorial to find from the author: http://devlicio.us/blogs/rob_eisenberg/archive/2010/10/08/caliburn-micro-soup-to-nuts-part-6a-screens-conductors-and-composition.aspx Can you elaborate a bit on your second question? I am not sure if I understand you correctly. But I think you are having too muc logic in your ribbon. My ribbons are simply launching events, which are send to the specific viewmodel, which may talk to the Data access layer. So, my ribbons are specific to a certain Viewmodel, too. But there is no need for them to do much. Som thinks like dropdowns are relying on the Viewmodel-methods to get a the values to display, but they do nothing more.
doc_23525467
python -c "import sys; print(sys.version)" but doing :python -c "import sys; print(sys.version)" in vim throws a SyntaxError. A: Run :ve[rsion] in command-line mode or run vim --version from Bash. * *If vim was compiled with Python 3, you'll find -python and +python3. *If vim was compiled with Python 2, you'll find +python and -python3. *If vim was compiled without Python support, you'll find -python and -python31. I'm not sure if it's possible to find both +python and +python3 in :ve output – currently probably not. 1Currently -python and -python3 seem to be the default for the Debian vim package. If you need vim support for scripting languages, install vim-nox, which is dedicated to them and therefore has (among other things) +python3 enabled. There is also an interesting, heavily refactored vim fork called neovim (or nvim in short). BTW: on Debian you can list all installed vim versions by running update-alternatives --list vim. A: I just discovered here that you can also do it with :python import sys; print(sys.version) A: I think you want this: Type: :python << EOF import sys; print(sys.version); EOF If vim was compiled with python, when you type :python << EOF in the command line, the command line will expand with newlines and wait for the EOF. Before the EOF, type your python code, and terminate with an EOF. Edit: as you've already discovered, the EOF is unnecessary and you can have your script on a single line, sans quotes and -c. The EOF trick is nice for testing out python/VIM scripts in the command line. :python import sys; print(sys.version); A: You could just run a python --version from within Vim directly: * *Open vim. *In normal mode (NOT insert mode), type :!python --version. *Type enter. The version of python is displayed.
doc_23525468
After url.openConnection() I see the value of the the 'connected' field in httpConn object and it says false. But if I remove this comment //int responsecode = httpConn.getResponseCode(); the status code of 200 is returned (success). What does this mean? Has the connection been established or not? When I telnet - o localhost 8080 it says 'Press any key to continue' and when I do so it says 'Connection with the host lost' Also, when the above piece of code is executed the console shows this null null Servlet Reached and I get the exception below (after the entire program has run in debugging mode) java.net.ProtocolException: Cannot write output after reading input. and when I finish executing the next line of code (debugging mode) StringBuffer requestParams = new StringBuffer(); the console no longer shows the output. What exactly is happening? An additional question - Right now I'm sending strings as parameters in the HTTP POST message but how would I send entire objects? Would I have to use serialization? Any help would be hugely appreciated. package tutorial; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.net.*; import java.util.Iterator; class HttpUtility{ private static HttpURLConnection httpConn; public static HttpURLConnection sendPostRequest(String requestURL, ArrayList list) throws IOException { URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); //int responsecode = httpConn.getResponseCode(); //httpConn.setDoInput(true); // true indicates the server returns response StringBuffer requestParams = new StringBuffer(); if (list != null && list.size() > 0) { httpConn.setDoOutput(true); // true indicates POST request // creates the list string, encode them using URLEncoder Iterator iter = list.iterator(); int index=0; while (iter.hasNext()) { String lValue = (String) iter.next(); requestParams.append(URLEncoder.encode("params"+ index++, "UTF-8")); requestParams.append("=").append( URLEncoder.encode(lValue, "UTF-8")); requestParams.append("&"); } System.out.println(requestParams.toString()); String requestParam = requestParams.toString(); DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream()); wr.writeBytes(requestParam); wr.flush(); wr.close(); /* OutputStream ops = httpConn.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(ops); writer.write(requestParams.toString()); writer.flush(); */ /* OutputStream os = httpConn.getOutputStream(); os.write(requestParam.getBytes()); os.flush(); os.close(); */ } return httpConn; } public static void disconnect() { if (httpConn != null) { httpConn.disconnect(); } } } class ConsoleHttpRequest { public static String requestURL; public static void main(String[] args) { ArrayList list = new ArrayList(); requestURL = "http://localhost:8080/ServletTutorial/ConsoleToServlet"; // No Exception but no connection //requestURL = "https://localhost:8080/ServletTutorial/ConsoleToServlet"; //javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake //requestURL = "http://localhost"; // java.net.ConnectException: Connection refused: connect //requestURL="https://10.167.7.178"; // java.net.ConnectException: Connection refused: connect //requestURL="http://www.google.com"; // No Exception but no connection as well list.add("Welcome"); list.add("to"); list.add("the"); list.add("World"); list.add("of"); list.add("Java"); list.add("Programming"); try { HttpUtility.sendPostRequest(requestURL, list); } catch (IOException ex) { ex.printStackTrace(); } HttpUtility.disconnect(); } } This is the servlet that receives the request from the console program and simply prints in the console. package tutorial; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ConsoleToServlet */ public class ConsoleToServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String s=request.getParameter("params1"); System.out.println(s); System.out.println("Servlet Reached"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String s=request.getParameter("params1"); System.out.println(s); doPost(request,response); } } A: why got 'false' value after "url.openConnection(...)" after checking with debugtool and tcpdump**(sudo tcpdump -s 0 -A port 80)**, I found that the http request header is not sent when calling openConnection,just after you start reading the inputstream ,the http request from client will be sent . about ProtocolException if you call "httpConn.getResponseCode()",it means the http response header was sent to client , so you can't send http request (unless you use the "pipeline" feature of http protocol,but it must be supported by server side also) send entire objects try it : HttpURLConnection httpConn =(HttpURLConnection) url.openConnection(); httpConn.setDoOutput(true); ObjectOutputStream objOts=new ObjectOutputStream(httpConn.getOutputStream()); objOts.writeObject(new Object()); objOts.close();
doc_23525469
<reply xmlns="urn::ietf::param" xmlns:element="https://xml.example.net/abc/12.3" message-id='1'> <abc> <xyz> hello </xyz> </abc> </reply> I want the value of xyz node i.e. hello, but findnodes is returning null value. my code is : my $xpath=XML::LibXML::XPathContext->new($dom); $xpath->registerNs('ns1','urn::ietf::param'); $xpath->registerNs('ns2','https://xml.example.net/abc/12.3'); $val=$xpath->findnodes('//ns1:reply/ns2:element/abc/xyz'); print $val; but print statement is returning null value A: It looks like you have some misunderstanding about how namespaces work. xmlns:element="https://xml.example.net/abc/12.3" means that there is a prefix element defined with this specific namespace URI. This namespace is actually never used in your XML. xmlns="urn::ietf::param" defines a default namespaces and also applies to all descendant elements. And actually you have no <element/> element in your XML. Thus, the following XPath should work as expected: //ns1:reply/ns1:abc/ns1:xyz
doc_23525470
(I need the x, y to be ints ant the end) Thank you ! public void updatePlayerFlip() { double angle_stepsize = 0.1; double angleInRadians = angle_stepsize * (Math.PI / 180); double cosTheta = Math.cos(angleInRadians); double sinTheta = Math.sin(angleInRadians); flipPosition.x = (int) (cosTheta * (flipPosition.x - spinPosition.x) - sinTheta * (flipPosition.y - spinPosition.y) + spinPosition.x); flipPosition.y = (int) (sinTheta * (flipPosition.x - spinPosition.x) + cosTheta * (flipPosition.y - spinPosition.y) + spinPosition.y); } A: You should store your positions as floating-point values and only convert to int when you need to use the result as an int. For example, assuming DoublePoint is a double-precision floating point class that represents the x and y position, and IntPoint is an integer point class, you could do something like this: class Player { DoublePoint position; IntPoint getIntPosition() { return IntPoint((int)position.x, (int)position.y); } void RotatePosition(double radians) { DoublePoint newPos; newPos.x = position.x * cos(radians); newPos.y = position.y * sin(radians); position = newPos; } }; Then do all your calculations in floating point (like in the RotatePosition() method). When you need the integer value, call getIntPosition() rather than directly using position.
doc_23525471
The problem is: If I use OR logical operator for joining clauses, the DBMS would stop checking of WHERE section once it encounter predicate that return TRUE. With AND logical operator is similar situation: once DBMS encounter predicate that return FALSE, the the DBMS will stop checking WHERE section. How to make DBMS check all clauses in WHERE section independently of clauses TRUE/FALSE values? A: You can't. SQL is a declarative language, not an imperative one. That means the database engine is absolutely free to use any and all kinds of optimizations (and dirty tricks) to get the correct result according to your specification. Moreover, the strategy the engine may choose today may change in the future without notice, so long it returns the correct result. The optimizer logic is typically very simple (and predictable) in low end databases, while it's very sophisticated in high end ones (more operations, better histograms, smarter logic, etc.). In short the strategy is constantly adapting the specific method to the existing conditions: data present on each table, hardware and software conditions, etc. A: I decided to add "Short-circuit protection mode" to my app and build WHERE section like "WHERE ((cond1 = cond2) = cond3) = cond4)" or "WHERE cond1 = (cond2 = (cond3 = cond4))", the last one would be easier to implement. UPDATE:
doc_23525472
def san(string): if ':' in string: spliter = ':' elif '-' in string: spliter = '-' else: return string (key, value) = string.split(spliter) return (key, value) why twice RETURN ? A: One is for the case where the string is not split, the other is for the case where the string is split. A: The return in the else clause is used to return before using the split function, returning the original string. The return at the bottom of the block is used to return the value after the split function has occurred. Using multiple returns is common in most programming languages and is usually used to break out of a function when you know that you don't need to run the remainder of the function. It is very useful when you reach an exceptional condition, there you can just return a special case which the function caller can pick up and know that an error has occurred. Do note however, that some people consider it to be bad style, especially if it causes inconsistent behaviour (like it does in your example).
doc_23525473
class OrdersTable extends React.Component { constructor() { super(); this.state = { orders: [], ... } componentDidMount() { setTimeout(() => { axios.get("http://localhost:1234/api/orders").then(response => { this.setState({ orders: response.data, }); }); }, 2000); } render () { return ( <div className="content-wrapper"> <div className="content-left"> <BootstrapTable keyField='id' data={this.state.orders} columns={this.state.columns} rowStyle = {this.state.rowStyle} rowEvents={this.rowEvents} caption={<CaptionOrders title="Orders" />} noDataIndication={<NoData />} {...this.props} /> <Legend /> </div> </div> ) } } I'd like to transform it to use Redux instead of inner state. I've started with the following: index.js: const store = createStore(reducer); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); Actions: import { LOAD_DATA } from '../constants/action-types'; export const loadData = orders => ({ type: LOAD_DATA, payload: orders }) Reducer: export default initialState = { orders: [] }; const reducer = (state = initialState, action) => { switch(action.type) { case LOAD_DATA: return { ...state, orders: action.payload }; default: return state; } } Container: const mapStateToProps = (state) => ({ orders: state.orders }) const mapDispatchToProps = (dispatch) => ({ // Should "axios" call be here and if so, how should look like? }); export default connect(mapStateToProps, mapDispatchToProps)(OrdersTable); Presentational component: How can I use the orders state from Redux in OrdersTable component? A: HTTP calls in Redux are considered side effects. They are not a part of Redux itself, which is only a state management library. Therefore you'll have to use another library in addition to Redux, of which the easiest one is redux-thunk. Using redux-thunk you can define a side effect which is essentially a function that can dispatch multiple times. For example: import { LOAD_DATA } from '../constants/action-types'; export const getOrders = () => async (dispatch) => { try { const response = await axios.get("http://localhost:1234/api/orders"); dispatch(loadData(response.data)) } catch (e) { /* ... */ } } export const loadData = orders => ({ type: LOAD_DATA, payload: orders }) A: Jayce444 is correct, you should use redux-thunk. I would consider that the canonical way to do this. check out this answer : https://stackoverflow.com/a/34458710/8896573 if you want to keep this elementary, forget about mapDispatchToProps (still do mapStateToProps) and in your axios response just call this.props.dispatch(loadData (orders)) Then because of the structure of your mapStateToProps, your 'orders' are available in your component as this.props.orders :)
doc_23525474
doc_23525475
string='var1/var2/var3'; IFS='/' read -r -a array <<< $string So the array is ["var1", "var2", "var3"] I want to add an element at a specified index and then shift the rest of the elements that already exist. So the resultant array becomes ["var1", "newVar", "var2", "var3"] I've been trying to do this with and loops but I feel like there's some better more "bash" way of doing this. The array may not be of a fixed length so it needs to be dynamic. A: You can try this: declare -a arr=("var1" "var2" "var3") i=1 arr=("${arr[@]:0:$i}" 'new' "${arr[@]:$i}") echo "${arr[@]}" result will be: var1 new var2 var3 More details: How to slice an array in Bash A: There is a shorter alternative. The += operator allows overwriting consequent array elements starting from an arbitrary index, so you don't have to update the whole array in this case. See: $ foo=({1..3}) $ declare -p foo declare -a foo=([0]="1" [1]="2" [2]="3") $ $ i=1 $ foo+=([i]=bar "${foo[@]:i}") $ declare -p foo declare -a foo=([0]="1" [1]="bar" [2]="2" [3]="3")
doc_23525476
I tried all those below and all returned with syntax errors. take 1: delete table1.* from table1 inner join table2 on table1.id=table2.id where table2.column3=21 and table2.column4=59; Error: near "table1": syntax error take 2: delete table1 from table1 inner join table2 on table1.id=table2.id where table2.column3=21 and table2.column4=59; Error: near "table1": syntax error take 3: delete from table1 inner join table2 on table1.id=table2.id where table2.column3=21 and table2.column4=59; Error: near "inner": syntax error Anyone knows what are the correct syntax? If this is the wrong approach, what is the correct way to achieve my goal? Really appreciate it. A: No Join in SqlLite DELETE, by the look of it, but you could use exists: delete from table1 where exists (select 1 from table2 where table1.id=table2.id and table2.column3=21 and table2.column4=59 ); A: Since SQLite does not support JOIN yet in outer query of DELETE statements, consider using subquery with IN or EXISTS: DELETE FROM table1 WHERE id IN ( SELECT id FROM table2 WHERE table2.column3 = 21 AND table2.column4 = 59 ) DELETE FROM table1 WHERE EXISTS ( SELECT 1 FROM table2 WHERE table1.id = table.id AND table2.column3 = 21 AND table2.column4 = 59 )
doc_23525477
self.aButtons.push({ label: __('Siguiente'), class: 'btn-moduloAvance', show: (self.oContrato.definirPago || self.oContrato.horario_definido) } }); That's the Html: <button ng-if="boton.show" ng-repeat="boton in personaAndContrato.aButtons" type="button" ng-class="boton.class" /> I know that i'm assigning a boolean to the 'show' property, so it's impossible it changes because it's a simple type. By the way I'm trying to assign a function to the 'show' property but i'm getting the following error: self.aButtons.push({ label: __('Siguiente'), class: 'btn-moduloAvance', show: function () { return (self.oContrato.definirPago || self.oContrato.horario_definido); } }); Html (edited): <button ng-if="boton.show()" ng-repeat="boton in personaAndContrato.aButtons" type="button" ng-class="boton.class" /> TypeError: v2.show is not a function at fn (eval at compile (angular.js?version=alpha.1:14539), :4:240) Some ideas? Does i'm missing or missunderstanding something? Thanks in advance! A: You can't have ng-repeat and ng-if in the same tag if ng-if refer to the inner variable of ng-repeat. Just split it : <div ng-repeat="boton in personaAndContrato.aButtons"> <button ng-if="boton.show()" type="button" ng-class="boton.class" /> </div> A: Changing to ng-if="boton.show()" will do.
doc_23525478
the issues are basically targeted towards the constructor and the variables I am using a Macbook pro and the others whose are not working are windows laptops class DateTextField extends StatelessWidget { DateTextField({@required this.dateComposition, @required this.dateCompositionHintText, this.onFieldSubmitted, this.onChanged, this.focusNode}); //dateComposition can only have Day, Month, or Year as strings final String dateComposition; final String dateCompositionHintText; final Function onFieldSubmitted; //onchanged function has to be determined if you want to automatically set the focus to another text field, see application on age_screen with the datetextfields final Function onChanged; //set the widget with its focusnode final FocusNode focusNode; @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( dateComposition, style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), ), SizedBox(height: 7), Container( margin: EdgeInsets.all(4), width: dateComposition == "Year"? 73: 55, child: TextFormField( textAlign: TextAlign.center, //Keyboardtype for numbers keyboardType: TextInputType.number, //only numbers can be typed in inputFormatters: <TextInputFormatter>[ FilteringTextInputFormatter.digitsOnly, LengthLimitingTextInputFormatter(dateComposition=="Year"? 4 : 2), ], style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600), autofocus: true, cursorColor: kPrimaryMagentaColor, onFieldSubmitted: onFieldSubmitted, onChanged: onChanged, focusNode: focusNode, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: kTextIconColorDarkBlue), borderRadius: BorderRadius.circular(15), ), hintText: dateCompositionHintText, hintStyle: TextStyle(fontWeight: FontWeight.w600, fontSize: 18.0), contentPadding: EdgeInsets.only( left: 10, right: 10, top: 10, bottom: 10, ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(15), borderSide: BorderSide( color: kPrimaryMagentaColor, width: 1.5, ), ), ), ), ), ], ); } } A: * *Please check dart and flutter versions in your devices *Check the version of packages used in pubspec.yaml is same or did it changed when your teammate did pub upgrade or pub get. Edit: I got variable can't be null error in this line DateTextField({@required this.dateComposition, @required this.dateCompositionHintText, this.onFieldSubmitted, this.onChanged, this.focusNode}); I made below changes to remove the error DateTextField( {required this.dateComposition, required this.dateCompositionHintText, required this.onFieldSubmitted, required this.onChanged, required this.focusNode}); If your teammate is getting the error on the same line please try this. Edit 2: class DateTextField extends StatelessWidget { DateTextField( {required this.dateComposition, required this.dateCompositionHintText, this.onFieldSubmitted, this.onChanged, this.focusNode}); //dateComposition can only have Day, Month, or Year as strings final String dateComposition; final String dateCompositionHintText; final Function ?onFieldSubmitted; //onchanged function has to be determined if you want to automatically set the focus to another text field, see application on age_screen with the datetextfields final Function ?onChanged; //set the widget with its focusnode final FocusNode focusNode; }
doc_23525479
Here is the passport-strategy configuration: const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth20').Strategy; const mongoose = require('mongoose'); const keys = require('../config/keys'); const User = mongoose.model('users'); passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser((id, done) => { User.findById(id).then(user => { done(null, user); }); }); passport.use( new GoogleStrategy( { clientID: keys.googleClientID, clientSecret: keys.googleClientSecret, callbackURL: '/auth/google/callback', proxy: true, authorizationParams: { access_type: 'offline', approval_prompt: 'force' } }, async (accessToken, refreshToken, profile, done) => { const existingUser = await User.findOne({ googleID: profile.id }) if (existingUser) { // we already have a record with the given profile ID return done(null, existingUser); } // we don't have a user record with this ID, make a new record! const user = await new User({ googleID: profile.id, name: profile.displayName }).save() done(null, user); }) ); A: Add prompt: 'select_account' to the passport.authenticate() middleware in your /auth/google route. app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'], prompt: 'select_account' }); Visit this page: https://developers.google.com/identity/protocols/OpenIDConnect#scope-param
doc_23525480
<batch-execution lookup="defaultKieSession"> <insert out-identifier="message" return-object="true" entry-point="DEFAULT"> <com.arty.drlwb.MyExampleType> <message>Hello Worlddddd</message> </com.arty.drlwb.MyExampleType> </insert> <fire-all-rules/> </batch-execution> I can get what I expected. Everything seems OK. But I found there are two KieSessions in the rule package and don't know which one will be used. If the stateful one is used, and I the post XML command with different facts (messages here) over and over again, all facts will be kept in Drools' working memory as far as I know. Then, would it cause memory leakage since there's no retract command? If yes, what's the correct way to format the XML command? A: The session you want to use for a batch execution in kie-server can be specified by the attribute lookup in the <batch-execution> element. In your case, the KieSession with name defaultKieSession will be used. If no lookup attribute is specified, then the KieSession defined as the default (default="true") in the kmodule.xml will be selected. If multiple default sessions are specified in the kmodule.xml (just like in your previous post), then I'm not sure which one will be selected. I would say that it is always a good practice to provide the lookup attribute in your <batch-execution> element to avoid confusion. Regarding the retraction of facts, given that this operation was renamed as "delete" in Drools 6.x, the command you are looking for is org.drools.core.command.runtime.rule.DeleteObjectCommand. Oddly enough, this command is still being serialized as <retract>. Hope it helps,
doc_23525481
Example: <?php function foo($a, $b=1) { return $a-$b; } ?> If I call $test = func_get_args(foo(10)); var_dump($test); I will have only an array with [0] => 10. How can I have the value(s) of the optional parameter(s) even if I don’t pass it/them? (I know that func_get_args only returns passed parameters.) EDIT: To be more precise, here is what I’m doing: function insertLog($fct_name="-1", $type="-1", $error="-1", ....) { // first thing $params = func_get_args(); var_dump($params); } A: func_get_args Note: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments. Ive created a function called func_get_all_args which takes advantage of Reflection. It returns the same array as func_get_args but includes any missing default values. function func_get_all_args($func, $func_get_args = array()){ if((is_string($func) && function_exists($func)) || $func instanceof Closure){ $ref = new ReflectionFunction($func); } else if(is_string($func) && !call_user_func_array('method_exists', explode('::', $func))){ return $func_get_args; } else { $ref = new ReflectionMethod($func); } foreach ($ref->getParameters() as $key => $param) { if(!isset($func_get_args[ $key ]) && $param->isDefaultValueAvailable()){ $func_get_args[ $key ] = $param->getDefaultValue(); } } return $func_get_args; } Usage function my_function(){ $all_args = func_get_all_args(__FUNCTION__, func_get_args()); call_user_func_array(__FUNCTION__, $all_args); } public function my_method(){ $all_args = func_get_all_args(__METHOD__, func_get_args()); // or $all_args = func_get_all_args(array($this, __FUNCTION__), func_get_args()); call_user_func_array(array($this, __FUNCTION__), $all_args); } This could probably do with a bit of improvement such ac catching and throwing errors. A: You can accomplish this using the ReflectionFunction function class. function foo($a, $b=1) { $arr = array(); $ref = new ReflectionFunction(__FUNCTION__); foreach($ref->getParameters() as $parameter) { $name = $parameter->getName(); $arr[$name] = ${$name}; } print_r($arr); // ... } Calling the function: foo(1); Output: Array ( [a] => 1 [b] => 1 ) Demo
doc_23525482
t1.MIN_of_DATE_PARAM - in date format t1.MAX_of_DATE_PARAM - in date format CASE WHEN t1.MIN_of_DATE_PARAM < 01JAN2019 AND t1.MAX_of_DATE_PARAM < 01JAN2019 THEN 'OLD CLIENT' END how can i compare it to jan12019 which I have declared in the calculation? here's the error i get: (CASE WHEN t1.MIN_of_DATE_PARAM < 01JAN2019 AND t1.MAX_of_DATE_PARAM < 01JAN2019 THEN 'OLD CLIENT' END) _________ 22 76 ERROR 22-322: Syntax error, expecting one of the following: enter image description here A: The error is underlined in the log, you can't specify a date value in SAS simply by putting 01JAN2019, you need to do the following: CASE WHEN t1.MIN_of_DATE_PARAM < '01JAN2019'd AND t1.MAX_of_DATE_PARAM < '01JAN2019'd THEN 'OLD CLIENT' END Wrapping the values in ''d converts the provided date-string into a SAS date value which can be compared with the date variables. For more information, search the SAS documentation for "SAS Date Constants".
doc_23525483
The input that is generated on button click looks like this: <div class="row t-a t-line" id="1"> <div class="col-md-1"> <input class="form-control" type="text" name="cod[]"> </div> <div class="col-md-4"> <input class="form-control" type="text" name="piesa[]"> </div> <div class="col-md-1"> <input class="form-control cantitate" type="number" name="cantitate[]" value="1"> </div> </div> The next one will have id 2 and so on. I use jquery serialize var form = $( this ).serialize(); But when i log in the console the var form, all the values are there except the dinamically generated input fields. Any ideas? Thank in advance! update: Yes, the form is wraped raound all input fields the js code: $( document ).on( "submit","form", function( event ) { event.preventDefault(); var form = $( this ).serialize(); form += '&action=update&id=<?php echo $id; ?>'; form += '&serie-produs='+$('#serie-produs').val(); form += '&Total='+$('#total-cu-TVA').val(); form += '&TotalFT='+totalFT.toFixed(2); form += '&TotalT='+totalT.toFixed(2); console.log(form); var action = "assets/tickete-controller.php"; $.post(action, form, function(data){ console.log(data); //$('.rezultat-filtre').html(data.produsItems); if(data.type == "success"){ $("#message").removeClass('alert-danger'); $("#message").css('display', 'block'); $("#message").addClass('alert-success'); $('#rsponse-message').html(data.message); $("#message").delay(4000).fadeOut("slow"); var link = data.linkPdf; console.log(link); window.open(link, '_blank'); } },'json'); }); A: This is because var form = $( this ).serialize(); Takes all values from elements that were in the DOM initially. In other words, you are getting those elements' values by using "READY" event only on HTML objects that were loaded at the beginning. To get the values from the elements added dynamically you will have to add an event listener for them: E.g. $(document).on(<event_type>, <element_ID_or_other_selector>, function() { ... <your_implementation> }); This way you will be able to get their values on a specified event. Another way to get their values is by using $('#your_element_ID').val(); for each dynamic element
doc_23525484
A: The views.py doesn't contain anything until you write it. If you hadn't written anything yet, then just create a new empty file and call it views.py. In future, you should always use source control. A: Hope this will help you https://github.com/wibiti/uncompyle2 See this answer on uncompyle2 for some other comments. A: There is no way of getting back the files. They are deleted. You could try a program that scans for deleted files, but don't count on it. Source control and frequent backups are the best methods of preventing this problem in the future.
doc_23525485
I performed this with the following code: import pandas as pd import numpy as np import datetime date1 = datetime.datetime(2009,06,01,10,0) date2 = datetime.datetime(2009,06,02,05,00) dates = pd.date_range(start=date1,end=date2,freq="30min") df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power']) date3 = datetime.datetime(2009,06,01,16,0) date4 = datetime.datetime(2009,06,01,23,0) df1 = df[df.index <= date3] df2 = df[df.index >= date4] df_new = pd.concat([df1,df2]) Is there a better way to get the same results? I was expecting something like this would work: df_new2 = df[df.index <= date3 | df.index >= date4] However I get the following error: TypeError: unsupported operand type(s) for |: 'datetime.datetime' and 'DatetimeIndex' A: The issue is that python does not know how to apply the boolean operations. Do this: df_new2 = df[(df.index <= date3) | (df.index >= date4)]
doc_23525486
I began this uninstall process first by the MySQL Installer Comunity remove option, but it returns me an error that I will show below, by the control panel, by command line on the website that I found in my search, even removing all trace of MySQL files in Program Files x86 and normal and ProgramData folders. I tried all of these ways and, after the restart of the system and go to control panel or MySQL Installer Comunity, keeps showing me the MySQL Server still installed. It's my first time facing this problem and I really need help. Attaching the log from MySQL Installer: Beginning removal of MySQL Server 8.0.13. 1: Action 02:40:05: INSTALL. 1: 1: MySQL Server 8.0 2: {5A1AC698-82B9-4962-9FF5-EABADBA5A124} 1: Action 02:40:05: FindRelatedProducts. Searching for related applications 1: Action 02:40:05: AppSearch. Searching for installed applications 1: Action 02:40:05: LaunchConditions. Evaluating launch conditions 1: Action 02:40:05: ValidateProductID. 1: Action 02:40:05: CostInitialize. Computing space requirements 1: Action 02:40:05: FileCost. Computing space requirements 1: Action 02:40:05: CostFinalize. Computing space requirements 1: Action 02:40:07: MigrateFeatureStates. Migrating feature states from related applications 1: Action 02:40:07: InstallValidate. Validating install 1: Action 02:40:09: InstallInitialize. 1: Action 02:40:09: GenerateScript. Generating script operations for action: 1: InstallInitialize 1: Action 02:40:09: QtRemoveService. 1: 1: Action 02:40:09: RemoveExistingProducts. Removing applications 1: Action 02:40:09: ProcessComponents. Updating component registration 1: Action 02:40:10: UnpublishFeatures. Unpublishing Product Features 1: Feature: Unpublishing Product Features 1: Action 02:40:10: SchedSecureObjectsRollback. 1: Action 02:40:11: ExecSecureObjectsRollback. 1: 1: Action 02:40:11: ExecSecureObjectsRollback. 1: 1: Action 02:40:11: ExecSecureObjectsRollback. 1: 1: Action 02:40:12: ExecSecureObjectsRollback. 1: 1: Action 02:40:12: RemoveRegistryValues. Removing system registry values 1: Key: Removing system registry values, Name: 1: Action 02:40:12: RemoveShortcuts. Removing shortcuts 1: Shortcut: Removing shortcuts 1: Action 02:40:12: RemoveFiles. Removing files 1: File: Removing files, Directory: 1: Action 02:40:12: RemoveFolders. Removing folders 1: Folder: Removing folders 1: Action 02:40:12: CreateFolders. Creating folders 1: Action 02:40:12: InstallFiles. Copying new files 1: Action 02:40:12: CreateShortcuts. Creating shortcuts 1: Action 02:40:12: WriteRegistryValues. Writing system registry values 1: Action 02:40:12: InstallServices. Installing new services 1: Action 02:40:12: RegisterUser. Registering user 1: Action 02:40:12: RegisterProduct. Registering product 1: Action 02:40:12: PublishFeatures. Publishing Product Features 1: Action 02:40:12: PublishProduct. Publishing product information 1: Action 02:40:12: InstallFinalize. 1: Action 02:40:15: InstallInitialize. 1: Action 02:40:16: QtRemoveService. 1: Action 02:40:18: Rollback. Rolling back action: 1: QtRemoveService 1: InstallInitialize 1: 1: MySQL Server 8.0 2: {5A1AC698-82B9-4962-9FF5-EABADBA5A124} 3: 3 1: The action 'Remove' for product 'MySQL Server 8.0.13' failed. A: Had the same error when uninstalling 5.6 after installing 8.0.17, no idea how to solve it
doc_23525487
public class Item<T>{ private T item; public doSomething(){...} } ... public void processItems(Item<?>[] items){ for(Item<?> item : items) item.doSomething(); } At the time I was on a hurry, so I solved my problem by defining a interface with the methods I needed to invoke and made the generic class implement it. public interface IItem { void doSomething(); } public class Item<T> : IItem { private T item; public void doSomething(){...} } ... public void processItems(IItem[] items) { foreach(IItem item in items) item.doSomething(); } This workaround works fine, but I'd like to know what is the correct way to achieve the same behavior. EDIT: I forgot to refer that the caller of processItems doesn't know the actual types. Actually the idea was that the array passed as argument to processItems could contain intermixed types. Since its not possible to have such an array in .Net, using a non generic base class or interface seems to be the only way. A: I see that you only want to invoke some method with no parameters... there's already a contract for that: Action. public void processItems(IEnumerable<Action> actions) { foreach(Action t in actions) t(); } Client: List<Animal> zoo = GetZoo(); List<Action> thingsToDo = new List<Action>(); // thingsToDo.AddRange(zoo .OfType<Elephant>() .Select<Elephant, Action>(e => e.Trumpet)); thingsToDo.AddRange(zoo .OfType<Lion>() .Select<Lion, Action>(l => l.Roar)); thingsToDo.AddRange(zoo .OfType<Monkey>() .Select<Monkey, Action>(m => m.ThrowPoo)); // processItems(thingsToDo); A: The normal way to do this would be to make the method generic: public void ProcessItems<T>(Item<T>[] items) { foreach(Item<T> item in items) item.DoSomething(); } Assuming the caller knows the type, type inference should mean that they don't have to explicitly specify it. For example: Item<int> items = new Item<int>(); // And then populate... processor.ProcessItems(items); Having said that, creating a non-generic interface specifying the type-agnostic operations can be useful as well. It will very much depend on your exact use case. A: There's no way you can omit Type Parameters in .NET generic implementation; this is by design. In fact, this can only be achieved in Java because of its type-erasure-based implementation. You can only use a base non-generic interface (think IEnumerable<T> and IEnumerable). A: Further to Jon's post. making the method generic (a template) negates the requirement for this sort of functionality (using <?>). You can always feed a type into a generic class/function and for cases where you don't know what type you will need you can make the offending method/class generic as well... ultimately the user has to provide a type when calling such a function or using a generic class, for the code to be able to compile... otherwise you will get some compiler errors. A: I've been struggling with the same issue when it came to porting stuff from Java where I've had constructs like if (o instanceof Collection<?>) doSoemthing((Collection<?>)o); Fortunately it turns out that a generic ICollection is also a non-generic ICollection and if someone needs to treat the elements in it as pure objects it is still possible: if (o is ICollection) DoSomething((ICollection)o); That way, since we don't care about the actual type of elements in collection all we get here are objects. A note here: if the collection was holding primitive types (int or byte for example) then autoboxing kicks in which might introduce performance penalty.
doc_23525488
js: $(function(){ var list = $('.lists'); list.on({ 'click': function(){ $('.list-display').toggle('slow'); } }); }); html: <ul class ='lists'> <li> Soccer <ul class='list-display'> <li> Kick </li> <li> Dribble </li> <li> Pass </li> </ul> </li> <li> Basketball </li> <ul class='list-display'> <li> Shoot </li> <li> Dribble </li> <li> Pass </li> </ul> <li> Baseball </li> <ul class='list-display'> <li> Catch </li> <li> Throw </li> <li> Hit </li> </ul> </ul> When I click any li in the main ul (Soccer, Basketball, Baseball) all of the uls embedded in their category toggle. I only want the one clicked to toggle. How can I re arrange my function to only toggle the one clicked? I imagine I have to use the 'this' keyword but am unfamiliar with using it. A: Use this (Example): $('.lists').on('click', 'li', function(){ $('ul.list-display', this).toggle('slow'); }); Also, you have wrong HTML, use something like this: <ul class ='lists'> <li> Soccer <ul class='list-display'> <li> Kick </li> </ul> </li> <li> Basketball <ul class='list-display'> <li> Shoot </li> </ul> </li> </ul> You didn't put all uls inside li, you have two uls like this: <li> Basketball</li> <ul class='list-display'> <li>...</li> </ul> <li> Baseball</li> <ul class='list-display'> <li>...</li> </ul> A: Try list.on({ 'click': function(){ $('.list-display', this).toggle('slow'); }}); I looks for .list-display items inside the currently clicked element.
doc_23525489
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (db2018.catalog_category_product, CONSTRAINT FK_CAT_CTGR_PRD_PRD_ID_CAT_PRD_ENTT_ENTT_ID FOREIGN KEY (product_id) REFERENCES catalog_product_entity_oud (entity_id) ON DE), query was: INSERT INTO catalog_category_product (category_id,product_id,position) VALUES (?, ?, ?), (?, ?, ?) Seems like there are no values being submitted? Can anyone point me in the right direction to get this fixed?
doc_23525490
For example the input [3, 4, 2] would return 1 because 3 ^ (4 ^ 2) = 3 ^ 16 = 43046721 the last digit of which is 1. The function needs to be efficient as possible because obviously trying to calculate 767456 ^ 981242 is not very quick. I have tried a few methods but I think the best way to solve this is using sequences. For example any number ending in a 1, when raised to a power, will always end in 1. For 2, the resulting number will end in either 2, 4, 6 or 8. If a number is raised to a power, the last digit of the resulting number will follow a pattern based on the last digit of the exponent: 1: Sequence is 1 2: Sequence is 2, 4, 8, 6 3: Sequence is 3, 9, 7, 1 4: Sequence is 4, 6 5: Sequence is 5 6: Sequence is 6 7: Sequence is 7, 9, 3, 1 8: Sequence is 8, 4, 2, 6 9: Sequence is 9, 1 0: Sequence is 0 I think the easiest way to calculate the overall last digit is to work backwards through the list and calculate the last digit of each calculation one at a time until I get back to the start but I am not sure how to do this? If anyone could help or suggest another method that is equally or more efficient than that would be appreciated. I have this code so far but it does not work for very large numbers def last_digit(lst): if lst == []: return 1 total = lst[len(lst)-2] ** lst[len(lst)-1] for n in reversed(range(len(lst)-2)): total = pow(lst[n], total) return total%10 Edit: 0 ^ 0 should be assumed to be 1 A: x^n = x^(n%4) because the last digit always has a period of 4. x ^2 ^3 ^4 ^5 1 1 1 1 1 2 4 8 6 2 3 9 7 1 3 4 6 4 6 4 5 5 5 5 5 6 6 6 6 6 7 9 3 1 7 8 4 2 6 8 9 1 9 1 9 As you can see, all 9 digits have a period of 4 so we can use %4 to make calculations easier. There's also a pattern if we do this %4. x ^0 ^1 ^2 ^3 ^4 ^5 ^6 ^7 ^8 ^9 1 1 1 1 1 1 1 1 1 1 1 2 1 2 0 0 0 0 0 0 0 0 3 1 3 1 3 1 3 1 3 1 3 4 1 0 0 0 0 0 0 0 0 0 5 1 1 1 1 1 1 1 1 1 1 (all %4) 6 1 2 0 0 0 0 0 0 0 0 7 1 3 1 3 1 3 1 3 1 3 8 1 0 0 0 0 0 0 0 0 0 9 1 1 1 1 1 1 1 1 1 1 As shown, there is a pattern for each x when n>1. Therefore, you can see that (x^n)%4 = (x^(n+4k))%4 when n>1. We can then prevent the issues that arises from n=0 and n=1 by adding 4 to n. This is because, if (x^n)%4 = (x^(n+4k))%4, then (x^n)%4 = (x^(n%4+4))%4 as well. powers = [3, 9, 7, 1] lastDigit = 1 for i in range(len(powers) - 1, -1, -1): if lastDigit == 0: lastDigit = 1 elif lastDigit == 1: lastDigit = powers[i] else: lastDigit = powers[i]**(lastDigit%4+4) print(lastDigit%10) A: This is more math than programming. Notice that all the sequences you listed has length either 1, 2, or 4. More precisely, x^4 always ends with either 0, 1, 5, 6, as does x^(4k). So if you know x^(m mod 4) mod 10, you know x^m mod 10. Now, to compute x2^(x3^(...^xn)) mod 4. The story is very similar, x^2 mod 4 is ether 0 if x=2k or 1 if x=2k+1 (why?). So * *is 0 if x2 == 0 *is 1 if x2 > 0 and x3 == 0 *if x2 is even, then it is either 2 or 0 with 2 occurs only when x2 mod 4 == 2 and (x3==1 or (any x4,...xn == 0) ). *if x2 is odd, then x2^2 mod 4 == 1, so we get 1 if x3 is even else x2 mod 4. Enough math, let's talk coding. There might be corner cases that I haven't cover, but it's should work for most cases. def last_digit(lst): if len(lst) == 0: return 1 x = lst[0] % 10 if len(lst) == 1: return x # these number never change if x in [0,1,5,6]: return x # now we care for x[1] ^ 4: x1 = x[1] % 4 # only x[0] and x[1] if len(lst) == 2 or x1==0: return x[0] ** x1 % 10 # now that x[2] comes to the picture if x1 % 2: # == 1 x1_pow_x2 = x1 if (x[2]%2) else 1 else: x1_pow_x2 = 2 if (x1==2 and x[2]%2 == 1) else 0 # we almost done: ret = x ** x1_pow_x2 % 10 # now, there's a catch here, if x[1]^(x[2]^...^x[n-1]) >= 4, # we need to multiply ret with the last digit of x ** 4 if x[1] >=4 or (x[1] > 1 and x[2] > 1): ret = (ret * x**4) % 10 return ret A: Working off of your sequences idea and fleshing it out, you'd want to create a dictionary that can map all relevant sequences. mapping = {} for i in range(1, 10): mapping[i] = [i] last_digit = i while True: last_digit *= i last_digit = last_digit%10 if last_digit in mapping[i]: break else: mapping[i].append(last_digit) print(mapping) This produces Output: mapping {1: [1], 2: [2, 4, 8, 6], 3: [3, 9, 7, 1], 4: [4, 6], 5: [5], 6: [6], 7: [7, 9, 3, 1], 8: [8, 4, 2, 6], 9: [9, 1]} Now the real logic can start, The key takeaway is that the pattern repeats itself after the sequence is completed. So, it does not matter how big the power is, if you just use a modulo and figure out which position of the sequence it should occupy. def last_digit_func(lst, mapping): if lst == []: #taken from OP return 1 last_digit = lst[0] % 10 if 0 in lst[1:]: #edge case 0 as a power return 1 if last_digit == 0: #edge case 0 at start return last_digit for current_power in lst[1:]: if len(mapping[last_digit]) == 1: return last_digit ind = current_power % len(mapping[last_digit]) ind -= 1 #zero indexing, but powers start from 1. last_digit = mapping[last_digit][ind] return last_digit test1 = [3, 4, 2] print(last_digit_func(test1, mapping)) #prints 1 I verified this by calculating the powers in python. test2 = [767456 , 981242] print(last_digit_func(test2, mapping)) #prints 6 And i tried to verify this by running it in python....i now have instant regrets and my program is still trying to solve it out. Oh well :)
doc_23525491
I'm using React with Material UI to create my webpages, as well as the npm package react-router-dom to go between pages. I also have a bit of a janky set up for Express to serve my pages. The problem was that if you went to the URL /book you'd be given the express static 404 page, instead of the React page for /book. So I redirected all non-extension URLs to index.html using a regex pattern. app.use("/", (req, res, next) => { // URLs that don't include extensions are assumed to be pages // Render them with the /index.html. const extRegex = /\.\w+\/?$/ if (extRegex.test(req.url) === false) { // Request url does not have an extension. req.url = "/index.html" } next() }, express.static(BUILD)) My Prerender.io middleware is placed before this, so that it is passed the unaltered req.url when it is called. Finally, sometimes I see the warning "Layout was forced before the page was fully loaded. If stylesheets are not yet loaded this may cause a flash of unstyled content." in the console on Firefox. I have not been able to figure out why this happens. Any help is appreciated! Thank you. A: I found a solution. The problem was that the library emotion-js, which is used by Material UI, was injecting CSS using Javascript. The CSS would not show up in the DOM however, so when the page was cached it would not include the CSS. The solution to this is to set the "speedy" setting of emotion-js to false when it detects that the page is being server-side rendered. I do this by checking the user agent, and whether it contains the string "prerender". Then, to set speedy to false when working in React you need to use a CacheProvider and create a cache. Here's an outline of the solution: App.js import { CacheProvider } from '@emotion/react'; import createCache from "@emotion/cache"; // Check if the user agent is Prerender. Speedy should be false if so. const speedy = navigator.userAgent.toLowerCase().indexOf("prerender") === -1; // Create an emotion cache const emotionCache = createCache({ key: "emotion-cache", speedy: speedy, }) function App() { return <CacheProvider value={emotionCache}> ... </CacheProvider> } export default App
doc_23525492
ajs@ajs-HP-Compaq-dc5800-Small-Form-Factor:/usr/local$ mkdir pgsql mkdir: cannot create directory `pgsql': Permission denied But I am getting error: Permission denied How can I resolve and create directory pgsql in this location /usr/local$ Kindly suggest me, hope for reply. Thanks A: You have to check your user name to have permission for creating directory in the folder /usr/local$ Check your permission for the folder by the command ls -ltr /usr Link to refer about file permissions. A: You are getting a Permission denied error because you do not have access rights to create a directory in /usr/local. You can determine the access rights for these directories by using the stat command. The output will look something like this. $> stat -c '%n %A %G %U' /usr /usr/local /usr drwxr-xr-x root root /usr/local drwxr-xr-x root root Now double check who you are. You can use the whoami command or the id command invoked below twice to reveal both username and group. $> id -un; id -gn In the stat output, root:root owns both /usr and /usr/local and only the owner may create (write) new directories based on the access rights. In order to create the directories, I'd recommend either becoming root or trying the command with sudo. If this is not possible, I'm afraid you'll have to create the directory elsewhere or contact the administrator of that machine. A: You probably have to be root to do such things in /usr/local.
doc_23525493
Assuming that my new sitemap only includes relevant product/information link information, do I have anything to worry about? A: t-nez, I work for a merchant service provider, www.banckardclub.com, as the lead SEO. The XML sitemap will not cause your site to fail PCI compliance. We have an XML sitemap and we submit to google, and other search engines. We pass our compliance test with out a problem. Have your webmaster look into the problem some more. A: Create an account on Webmaster tools and if you encounter problems search the help, this should not be a problem.
doc_23525494
So what I exactly need is that if entity is used in different classes a single code is used (no duplicate code). What are the best practices? Do EF provide us something or we need to implement it ourself? Example: Database tables: TableA, TableB, TableC, TableD Models: Model1 -> TableA, TableB Model2 -> TableA, TableC, Model3 -> TableC, TableD Edit: I have a database containing 4 tables (TableA, TableB, TableC, TableD). I create a Entity data model of the database which contains TableA and TableB. In entity designer view I modified names of properties of TableA Entity so that they are readable. Now I create another model which contains TableA and TableC. Now here I have to rename all properties of TableA again. Now this is repeat work. Now if I add some custom action to my Entity for Model1 then I have to write (copy) them to new Model2 Entity as well. I need to avoid this. As I really don't know how many models I will create. And if I have to do this stuff again and again then it will take lot of time.
doc_23525495
For example, When I give an argument with quotes, argparse only takes what's inside of the quotes as the argument. I want to capture the quotation marks as well (without having to escape them on the command line.) pbsnodes -x | xmlparse -t "interactive-00" produces interactive-00 I want "interactive-00" A: I think it is the shell that eats them, so python will actually never see them. Escaping them on the command line may be your only option. If it's the \"backslash\" style escaping you don't like for some reason, then this way should work instead: pbsnodes -x | xmlparse -t '"interactive-00"' A: Command line is parsed into argument vector by python process itself. Depending on how python is built, that would be done by some sort of run-time library. For Windows build, that would be most likely MS Visual C++ runtime library. More details about how it parses command line can be found in Visual C++ documentation: Parsing C++ command-Line arguments. In particular: * *A string surrounded by double quotation marks ("string") is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument. *A double quotation mark preceded by a backslash (\") is interpreted as a literal double quotation mark character ("). If you want to see unprocessed command line, on Windows you can do this: import win32api print(win32api.GetCommandLine())
doc_23525496
ldr R0, =str1 @ str1 = "-400" bl putstring @ putstring displays the number ldr R0, =newline @ Load R0 with address of newline (newline: .byte 10) bl putch @ Function call to ext. func. call putch (putch outputs a character) I want the second portion of the code to output a newline. However, R0 isn't pointing to the address of newline, despite the instruction. $r0 : 0x0002064c → "-400" $r1 : 0x0002064c → "-400" @ After 2nd ldr instruction $r0 : 0x0002064f → 0x30340030 ("0"?) $r1 : 0x0002064c → "-400" Am I doing something wrong? Shouldn't R0 be pointing to a newline address, so that it may be outputted using putch? Why is it pointing to a '0' from the "-400"? The value of R0 SHOULD be: $r0 : 0x0002064f → <newline+0> lsrs r0, r0, #8 after the 2nd ldr instruction. Declarations: str1: .asciz "" newline: .byte 10
doc_23525497
My OnClick looks like this: public class Input { public Action<Vector3> OnClick; } Then in a different class I have: // _input is a refence to class Input public void Init() { _input.OnClick -= OnLeftClick; _input.OnClick += OnLeftClick; var list = _input.OnClick.GetInvocationList(); var list = _input.OnClick.GetInvocationList(); Debug.Log("DEBUG: " + list.Length); foreach (var item in list) Debug.Log(item.Method.ToString()); } After calling this function a few times in a row the output gives: DEBUG: 1 Void OnLeftClick(Vector3) DEBUG: 2 Void OnLeftClick(Vector3) Void OnLeftClick(Vector3) DEBUG: 5 Void OnLeftClick(Vector3) Void OnLeftClick(Vector3) Void OnLeftClick(Vector3) Void OnLeftClick(Vector3) Void OnLeftClick(Vector3) So my method OnLeftClick is getting called multiple times, but I don't know why. How do you clear the method from the action so I can then re-assign it to prevent duplicates? A: When public Action<Vector3> OnClick; is not marked event, i.e. it is a pure field, everyone has access to it in its entirety (not just through add and remove accessors). So they can clear it with _input.OnClick = null;. However, are you sure you do not want an event? For delegates, the convention is that a null reference is used (rather than some empty object) when there are no functions. If instead you decide for an auto-event (so-called field-like event), access to the automatic (implicit) backing field is only from inside the class itself. Of course you can create a method in the class that clears the event, and make the method nonprivate, but maybe it is not the best design. A: The problem here is that your OnClick event subscribers are different from one Init call to another. Probably you are invoking the Init method on different objects or reference. I hope this example clarify the situation: class A { public Action<Vector3> OnClick; // using method group public A() : this(_OnClick) { } // using anonymous method/action reference public A(Action<Vector3> a) => OnClick = a; ... public void Init() { _init.OnClick -= OnClick; _init.OnClick += OnClick; } public void _OnClick(Vector3 v) { } } Problem with group method A a1 = new A(); a1.Init(); // I will display the subscriber list like: _init.OnClick -> [] // Here you are applying: // _init.OnClick -= a1.OnClick; -> _init.OnClick [ ] // _init.OnClick += a1.OnClick; -> _init.OnClick [ a1.OnClick ] // the subscriber is a1 A a2 = new A(); // But here you are applying: // _init.OnClick -= a2.OnClick; -> _init.OnClick [ a1.OnClick ] // _init.OnClick += a2.OnClick; -> _init.OnClick [ a1.OnClick, a2.OnClick ] // the subscriber is a2 a2.Init(); Problem with anonymous methods A a = new A(v => Console.WriteLine($"A1: {v}")); a.Init(); // Here you are applying: // _init.OnClick -= a.OnClick; -> _init.OnClick [ ] // _init.OnClick += a.OnClick; -> _init.OnClick [ (v => Console.WriteLine($"A1: {v}")) ] // the subscriber is (v => Console.WriteLine($"A1: {v}")) a.OnClick = v => Console.WriteLine($"A2: {v}"); a.Init(); // But here you are applying: // _init.OnClick -= a.OnClick; -> _init.OnClick [ (v => Console.WriteLine($"A1: {v}")) ] // and a.OnClick is (v => Console.WriteLine($"A2: {v}")) // _init.OnClick += a.OnClick; -> _init.OnClick [ (v => Console.WriteLine($"A1: {v}")), (v => Console.WriteLine($"A2: {v}")) ] // the subscriber is (v => Console.WriteLine($"A2: {v}")) a2.Init(); NOTE: it also occurs with the same "lambda body" but different anonymous method: Action<Vector3> m1 = v => Console.WriteLine($"A: {v}"); Action<Vector3> m2 = v => Console.WriteLine($"A: {v}"); // m1 differs from m2 because are compiled to two different // anonymous methods, even if they have the same code a.OnClick = m1; a.Init(); // Here you are applying: // _init.OnClick -= a.OnClick; -> _init.OnClick [ ] // _init.OnClick += a.OnClick; -> _init.OnClick [ m1 ] // the subscriber is m1 a.OnClick = m2; // But here you are applying: // _init.OnClick -= a.OnClick; -> _init.OnClick [ m1 ] // _init.OnClick += a.OnClick; -> _init.OnClick [ m1, m2 ] // the subscriber is m2 (!= m1) a.Init(); Same applies if the _init changes from one instance of A to another (eg. is not a static member) Take also a look to Unsubscribe - MDN.
doc_23525498
a. If the user moves the slider by clicking I want to do something when the slider is released. b. If the user moves the slider with the scroll, I want to do something when it stops scrolling. c. If the user moves the slider by pressing the arrow key, I want to do something every time the number changes. I haven't found a way to capture all these functionalities. With void on_verticalSlider_slice_sliderReleased() { qDebug() << "on_verticalSlider_slice_sliderReleased"; qDebug() << this->Internals->verticalSlider_slice->value(); } it only captures the first option. Nothing with scrolling or arrow key. With void on_verticalSlider_slice_valueChanged(int value){ qDebug() << "on_verticalSlider_slice_valueChanged"; qDebug() << value; } it captures the arrow keys and scrolling, but it also captures click and release, going trought every number, same with scrolling. How can I do this? A: What you want to achieve can be accomplished by using the Qt's event system: https://doc.qt.io/archives/qt-4.8/eventsandfilters.html Here's a rough pseudocode: bool MySlider::event(QEvent *event) { if (event->type() == QEvent::KeyPress) { // This is key event } else if (event->type() == QEvent::MousePress) { // This is mouse press event } else if (event->type() == QEvent::Scroll) { // This is scroll event } else { } // If you want your slider to change the value based on the event instead of // you manually setting your slider's value based on the above events. return QSlider::event(event); }
doc_23525499
Uncaught Exception: Error: Cannot find module Require stack 'E:\app-folder..release-builds\app-win32-ia32\resources\app....\node_sqlite3.node' click here to see Error 'Here is my package.json' { "name": "app", "version": "1.0.0", "main": "main.js", "devDependencies": { "electron": "^8.2.0", "electron-builder": "^22.8.0", "electron-rebuild": "^1.10.1" }, "scripts": { "start": "electron .", "rebuild": "electron-rebuild -f -w sqlite3", "package-win": "electron-packager . App--overwrite --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"App\"", "postinstall": "electron-builder install-app-deps" }, "dependencies": { "axios": "^0.19.2", "concat-stream": "^2.0.0", "datatables.net": "^1.10.20", "datatables.net-dt": "^1.10.20", "ejs": "^3.1.5", "electron-packager": "^15.0.0", "express-validator": "^6.6.1", "form-data": "^3.0.0", "jquery": "^3.5.0", "nodemailer": "^6.4.11", "sqlite3": "^5.0.0" } } A: npm install --save-dev @electron-forge/cli npm run package try running these commands you will get an out folder and the application is present in that out folder