_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d14401
val
you can try doing it this way: const server = http.createServer((req, res) => { if(/*your auth check*/){ //return the 401 error } //auth check is passed, pass the request to the proxy proxy.web(req, res, { target: 'http://your.target' }); });
unknown
d14402
val
Have you considered using Selenium? It is able to click through websites automatically by locating HTML tags and clicking links. https://selenium-python.readthedocs.io/index.html A: Look into their private API; Inspect Element, and Network tab. Notice when you click the 'Load More' button your browser makes a request to the following URL: https://www.olx.in/api/relevance/v2/search?facet_limit=100&lang=en&latitude=17.46497&location=4058526&location_facet_limit=20&longitude=78.43517&page=1&platform=web-desktop&query=note%209%20pro&spellcheck=true You can modify the query via the URL params. Then, using requests, you can query this information and organize the JSON return: { "version": "100.0", "data": [ { "id": "1636448838", "score": 1679.043212890625, "spell": { "id": 54, "key": "GEAS", "version": "1", "main": true, "facet_disabled": false, "default_sorting": "DEFAULT" }, "status": { "status": "active", "allow_edit": true, "ban_reason_id": null, "display": "active", "translated_display": "Active", "link": null, "flags": { "new": false, "hot": false }, "message": null }, "category_id": "1453", "favorites": { "count": 0, "count_label_next": "1" }, "images": [ { "id": "1003855963", "external_id": "tj7vu6vj98qp-IN", "width": 524, "height": 1080, "url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image", "full": { "width": 1080, "height": 2225, "url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image;s=1080x2225" }, "big": { "width": 505, "height": 1040, "url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image;s=505x1040" }, "medium": { "width": 120, "height": 247, "url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image;s=120x247" }, "small": { "width": 120, "height": 247, "url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image;s=120x247" } }, { "id": "1003855964", "external_id": "s6z25cvcbz052-IN", "width": 524, "height": 1080, "url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image", "full": { "width": 1080, "height": 2225, "url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image;s=1080x2225" }, "big": { "width": 505, "height": 1040, "url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image;s=505x1040" }, "medium": { "width": 120, "height": 247, "url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image;s=120x247" }, "small": { "width": 120, "height": 247, "url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image;s=120x247" } }, { "id": "1003855965", "external_id": "mq6ouyke1k3h3-IN", "width": 524, "height": 1080, "url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image", "full": { "width": 1080, "height": 2225, "url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image;s=1080x2225" }, "big": { "width": 505, "height": 1040, "url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image;s=505x1040" }, "medium": { "width": 120, "height": 247, "url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image;s=120x247" }, "small": { "width": 120, "height": 247, "url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image;s=120x247" } }, { "id": "1003855966", "external_id": "7vfcbj5fb8fh2-IN", "width": 524, "height": 1080, "url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image", "full": { "width": 1080, "height": 2225, "url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image;s=1080x2225" }, "big": { "width": 505, "height": 1040, "url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image;s=505x1040" }, "medium": { "width": 120, "height": 247, "url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image;s=120x247" }, "small": { "width": 120, "height": 247, "url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image;s=120x247" } } ], "certified_car": false, "is_kyc_verified_user": false, "has_phone_param": false, "locations_resolved": { "COUNTRY_id": "1000001", "COUNTRY_name": "India", "ADMIN_LEVEL_1_id": "2007599", "ADMIN_LEVEL_1_name": "Telangana", "ADMIN_LEVEL_3_id": "4058526", "ADMIN_LEVEL_3_name": "Hyderabad", "SUBLOCALITY_LEVEL_1_id": "5348837", "SUBLOCALITY_LEVEL_1_name": "Murad Nagar" }, "description": "Full condition with box + bill charger", "created_at": "2021-05-18T10:53:54+05:30", "inspection_info": null, "package_id": null, "title": "Note 9 pro", "main_info": null, "user_type": "Regular", "display_date": "2021-05-18T05:23:54+0000", "user_id": "508731436", "price": { "value": { "raw": 14500, "currency": { "iso_4217": "INR", "pre": "₹" }, "display": "₹ 14,500" }, "key_name": "Price", "key": "price" }, "created_at_first": "2021-05-18T10:53:54+05:30", "locations": [ { "lat": 17.39, "lon": 78.448, "region_id": "2007599", "district_id": "5348837", "city_id": "4058526" } ], "parameters": [ { "type": "single", "key": "make", "value": "mi-phone", "key_name": "Brand", "formatted_value": "Mi", "value_name": "Mi" } ], "monetizationInfo": null } ], "metadata": { "sections": [ { "id": 10, "offset": 0, "criterion": "less_than", "distance": 10, "relaxation_type": "bucket" }, { "id": 20, "offset": 39, "criterion": "less_than", "distance": 20, "relaxation_type": "bucket" } ], "feed_version": "100.0", "total_ads": 190, "total_suggested_ads": 0, "ads_on_page": 20, "total_pages": 4, "suggested_sections": [], "original_term": "note 9 pro", "modified_term": "note 9 pro", "original_label": "Showing results for ${original_term}", "show_hint": false, "show_original_items": true, "show_suggested_items": false, "filters": [ { "id": "price", "values": [], "display_order": 200, "description": "Budget", "range": [ { "id": "min", "description": "min", "min_value": 0, "max_value": 10000000000 }, { "id": "max", "description": "max", "min_value": 0, "max_value": 10000000000 } ], "type": "range-input", "render_as": "range-input" } ], "applied_sorting": { "key": "desc-creation" }, "next_page_url": "http://api.olx.in/relevance/v2/search?facet_limit=100&clientId=pwa&location_facet_limit=20&spellcheck=true&latitude=17.46497&query=note%209%20pro&location=4058526&page=2&lang=en&clientVersion=7.10.1&platform=web-desktop&longitude=78.43517", "applied_filters": [], "search_query": "note 9 pro", "modified_filters": {} }, "empty": false, "not_empty": true, "suggested_data": [] } I deleted all item entries except one above.
unknown
d14403
val
I'm not sure that omniauth allows you to provide translations for the messages that come out of it. There don't seem to be any en.yml files in omniauth, omniauth-facebook or omniauth-twitter anyway. I've only used omniauth with devise and devise provides a couple of omniauth-related messages which can be overridden, but they contain the untranslated error messages which come out of omniauth: en: devise: omniauth_callbacks: failure: "Could not authenticate you from %{kind} because \"%{reason}\"." success: "Successfully authenticated from %{kind} account." These can be overridden in an app using devise by providing an en translations file containing these in config/locales in your app. You can of course also provide a ru translations file and set config.default_locale = :ru in application.rb or use some other way to decide which locale to use. You can see how devise builds an error message from an omniauth failure here: https://github.com/plataformatec/devise/blob/master/app/controllers/devise/omniauth_callbacks_controller.rb You could use the same approach in your app without using devise, but as I say, the problem is that %{reason} would be the untranslated error (often an exception.message I think) from omniauth. For general internationalisation, if you haven't read it already: Rails i18n EDIT: It sounded like you were asking about omniauth itself, but in case, as Ashitaka wondered in their comment, you were (also) asking about telling the services you call which locale to use, you've probably seen in the docs, but just for the sake of completeness it does indeed vary by service. For example, omniauth-facebook lets you add a locale parameter to the facebook call (e.g. locale=ru_RU) and omniauth-twitter lets you add a lang parameter to the twitter call (e.g. lang=ru). A: If you browse under app/config/locales dir, there is a file en.yml. It is for english locale. If you would like to add other languages, just create (in your case) ru.yml file and place translations there. This Rails guide is a nice staring point. Recently I have tried another interesting approach : phrasing gem.
unknown
d14404
val
You can put your azuredeployparameters.json in your central/main repo. And if you use release pipelines for instance, you should create build for your central repo and publish azuredeployparameters.json as artifact. You can later use this artifacts in any release pipeline you want. So you can get it Release1 and Release2. If you use build pipelines also to deploy, you can use multiple repos and get source code (in release 1) from your central repo and repo dedicated to this release. In the same way you have this file available. If you want to customize file a bit in Relese pipeline you can tokenize you azuredeployparameters.json file and replace those tokens in release. Here you have extension for this.
unknown
d14405
val
Run it in a background thread and put Thread.Sleep(1000) in the loop. This way it will be time based and not freeze your app. A: We need to see more of your code, but it's pretty simple: using System.Windows.Forms; SomeMethod(...) { Timer t = new Timer(); t.Interval = 1000; t.Tick += t_Tick; t.Enabled = true; t.Start(); } void t_Tick(...) { foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2 { makeSelfMoves = replay[item.Key]; codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]); PrintPieces(codeFile.PieceState()); // MessageBox.Show("rowStart: " + makeSelfMoves[0] + ". rowEnd: " + makeSelfMoves[2] + ". columnStart: " + makeSelfMoves[1] + ". columnEnd: " + makeSelfMoves[3] + "____a is: " + a); } } A: Personally, I would put this into a seperate thread and use Thread.sleep(). In combination with accessing GUI-elements, I would suggest a BackgroundWorker instead (see MSDN, easy to implement). If you insist in using a timer, I would suggest you use the suggestion of 'Ed S.'. The timer could also be placed on your form, instead of creating it in code of course. Just what you prefer.
unknown
d14406
val
You're making 2 mistakes here: 1) You're writing past the end of the array here, since it can only hold 1 character, not 2 like you're attempting to access: char *x=new char[1]; x[0]='R'; x[1]='\0'; You're only using one char anyway, so why make it an array? Replace it by: char x = 'R'; 2) You're not comparing the chars, but the memory addresses they're located at. Of course this won't work. You have to dereference the pointers (i.e. access the stored values) for it to work. Rewrite it like so: if (*data->c == *x) A: Since you create the object to look for this way char *x=new char[1]; it will never match anything in the list, because you have allocated a new piece of memory. You need to compare what the pointers point to. A: First of all, you are making an illegal write when you are initializing char x, by trying to access it's index 1. If you create an array of length N, you can access only the indices [0, N). In this case, as you created an array of length 1, you can not access its index 1, as it is out of bounds. You should instead create an array of length 2, if you intend to put the '\0' character. Secondly, when comparing, you should match the contents to which the char* points to, not the pointer itself, which is only an address. As you are trying to compare a character to another, using their pointers, you should change the innermost if checks (i.e. if (data->c == x) with the following: if (*data->c == *x) Thirdly, your code has another bug, related to how deletion of linked list elements is implemented. Basically, you should consider the case where temp2 variable may be nullptr. Finally, I recommend you look into std::string, which may be a better way to represent strings. Alternatively, if your linked list only has single characters, you may simply use character variables, as opposed to allocating a character array for each node in your list. Here is a working version of your code with the updates I mentioned above. A: you try to compare string like we compare character reason why it don't work. you can use strcmp instead or use character and not string. A: Why don't use std::string? The struct: struct ll { std::string c; ll *prev; ll *next; }; The string initialization: ll obj; obj.c = "R"; Your del function: void del(ll *data, char *val) { ll *temp, *temp2; bool sm = false; std::string x = val; while (data != nullptr) { if (data->prev == nullptr) { if (data->c == x) { temp = data; data = data->next; data->prev = nullptr; delete temp; } } else { if (data->c == x) { temp = data; data = data->prev; data->next = temp->next; temp2 = data->next; temp2->prev = data; delete temp; } } data = data->next; } }
unknown
d14407
val
Welcome to Stackoverflow! In the future, please make sure if you are asking a question, the code you post has no errors or if it does have errors, then your question can be about fixing the error. Your JSON is not valid JSON. Step 1 Fix your JSON. Here is the corrected version of your JSON: { "Enumerations" : { "IndianCities" : [ { "key" : "Delhi", "val" : 001}, { "key" : "Mumbai", "val" : 002} ] }, "Users":[ { "AccessType" : "Admin", "Male" : [ { "Name" : "Xyz", "ID" : 459 }, { "Name" : "Abc", "ID" : 542 } ], "Female" : [ { "Name" : "Abc", "ID" : 543 } ] }, { "Location" : "NewYork", "Male" : [ { "Name" : "Xyz", "ID" : 460 }, { "Name" : "Abc", "ID" : 642 } ], "Female" : [ { "Name" : "Abc", "ID" : 643 } ] } ] } Step 2 As I mentioned in my comment, refer the answer here to create C# classes to represent your JSON. I did it, and it generated this: public class Rootobject { public Enumerations Enumerations { get; set; } public User[] Users { get; set; } } public class Enumerations { public Indiancity[] IndianCities { get; set; } } public class Indiancity { public string key { get; set; } public int val { get; set; } } public class User { public string AccessType { get; set; } public Male[] Male { get; set; } public Female[] Female { get; set; } public string Location { get; set; } } public class Male { public string Name { get; set; } public int ID { get; set; } } public class Female { public string Name { get; set; } public int ID { get; set; } } Step 3 Is there any generic solution available for reading male info all classes and put in a list. Yes! But what you really mean is: Is there any generic solution available for reading all males into a list? Use Newtonsoft.Json library to deserialize the JSON content. Please note each User instance has a Male array so you need to use SelectMany to flatten the data as shown below: Rootobject ro = JsonConvert.DeserializeObject<Rootobject>("YourJSON"); List<Male> males = ro.Users.SelectMany(x => x.Male).ToList(); You may do other filtration if you require.
unknown
d14408
val
<?php $host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-password'; $conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ?> <?php $sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5"; $query = $conn->prepare($sql); $query->execute(); $row = $query->fetch(PDO::FETCH_ASSOC); $totalRows = $query->rowCount(); ?> <?php do { // print your results here ex: next line echo 'Title: '.$row['title'].' Date: '.$row['date'].' Author: '.$row['author'].'<br>'; } while ($row = $query->fetch(PDO::FETCH_ASSOC)); ?> Don't forget to close and release resources <?php $query->closeCursor(); ?> EDIT I recommend not echoing error messages once you have confirmed your code functions as expected; however if you want to simply use plain text you can do this... You can add this to your connection block... if ($conn->connect_error) { die("Database Connection Failed"); exit; } You can also change your query block... try { $sql = "SELECT id,title,date,author FROM table ORDER BY date DESC LIMIT 5"; $query = $conn->prepare($sql); $query->execute(); $row = $query->fetch(PDO::FETCH_ASSOC); $totalRows = $query->rowCount(); } catch (PDOException $e) { die("Could not get the data you requested"); exit; } Again, it is recommended that errors not be echoed. Use error checking only for debugging. A: <?php $db = PDO('mysql:dbhost=$dbhost;dbname=$dbname', $user, $pass); $sth = $db->prepare("SELECT id,title,date,author FROM table ORDER BY date LIMIT 5"); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); print_r($result); ?> in a loop: while($row = $sth->fetch()) { echo $row['column']; } From the documentation: http://php.net/manual/en/pdostatement.fetch.php
unknown
d14409
val
SELECT `City`.* FROM `city` WHERE (City LIKE '%a%') You weren't using your single quotes correctly. It is: City LIKE '%a%' Not: City 'LIKE %a%'
unknown
d14410
val
Unless you deliberately left out export when you wrote, changing function prepadSigned(hexStr) { ... } to export function prepadSigned(hexStr) { ... } may fix the problem.
unknown
d14411
val
There are some mistakes in your code (the first function argument is not the user, but the url redirection to be filtered). Try the following instead: add_filter('woocommerce_login_redirect', 'ffaces_register_customer', 10, 2 ); add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer', 10, 2 ); function ffaces_register_customer( $redirect, $user = '' ) { if( isset($user) && is_a( $user, 'WP_User' ) && $user->ID > 0 ) { return home_url("my-account/my-projects"); } else { return get_permalink( wc_get_page_id( 'myaccount' ) ); } } Code goes in functions.php file of your active child theme (or active theme). It should work. A: I don't think its set yet when this fires. The hook passes the user object of the user that logged in try to change $customerid = get_current_user_id(); to $customerid = $user->ID;
unknown
d14412
val
The problem you're having is that you're using a two dimensional array there. A two dimensional array looks like a table. That's not what you want though. You want a list of pairs of points. So, create a structure with two integers in it, x and y, and make an array of those structures: 'Right underneath your Class Form1 declaration: Structure Point Dim x As Integer Dim y As Integer End Structure Dim length As Integer = 10 Dim Points(length) As Point 'When you want to start using your points put this in the method: Points(0).x = 10 Points(0).y = 10 Points(1).x = 20 Points(1).y = 40 A: Dynamic variables in VB6 First you declare the variable without giving size: Dim InputX() As String Then you give for the first time size to your array using ReDim: ReDim InputX(5) If you want to preserve whatever data is already in your array you use ReDim Preserve: ReDim Preserve InputX(10) I hope this is what you need. A: it appears that the first method Text1.Text=InputX(2,0) is working. I just need to declare x and y As Single
unknown
d14413
val
You could use getName() with File which is available Reference : https://docs.oracle.com/javase/6/docs/api/java/io/File.html#getName%28%29 File f = new File("C:\\Dummy\\Folder\\MyFile.PDF"); System.out.println(f.getName()); Which returns you MyFile.PDF. (or) // Path object Path path = Paths.get("D:\\eclipse\\configuration" + "\\myconfiguration.conf"); // call getName(int i) to get // the element at index i Path indexpath = path.getName(path.getNameCount()-2); // prints the name System.out.println("Name of the file : " + indexpath); Which prints myconfiguration.conf. Hope it helps ! A: Path#getParent returns a path’s parent. You can then use Path#getFileName: path.getParent().getFileName();
unknown
d14414
val
Did you import the same database of your local Installation on the live Server? Maybe some worng paths in options table could be wrong causing your problems, if you migrated your local database to the live server. Maybe you also need to check wp-config.php and set your base url here or sth.
unknown
d14415
val
There are some issues with your data. First, I think that your a parameter is constant for the last 5 entries, so the line would only plot the first one. Further, the method animate() would not do anything to the line (unless you have somehow implemented it and not shown in your example). Also you need to update the axis domain, otherwise your line wouldn't be shown correctly. I have created a JSFiddle here so please have a look. Essentially, I cleaned your data and created a setInterval method as shown here: setInterval( function (){ // Append your new data, here I just add an increment to your a data.push( {"a":Number(parseFloat(d3.max(data, function(d){return d.a}))+1), "b":Math.random()*10 }); //Redraw the line svg.select(".line").transition().duration(50).attr("d",line) //Recompute the axes domains x.domain(d3.extent(data, function(d) { return parseFloat(d.a); })); y.domain(d3.extent(data, function(d) { return parseFloat(d.b); })); // Redraw the axes svg.select('.x-axis').call(xAxis); svg.select('.y-axis').call(yAxis) },1000) Hope this helps.
unknown
d14416
val
We do this with redux-form quite easily. Because everything's maintained in the fields prop, you could do something like this: const Form = ({ fields, handleSubmit, saveForm }) => ( <form onSubmit={handleSubmit(saveForm)}> <fieldset> <input type="text" {...fields.hasAlternativeDelivery} /> </fieldset> {fields.hasAlternativeDelivery.value === true && <fieldset> {/* more fields go here */} </fieldset> } </form> ); We then conditionally validate certain fieldsets like this. So, to answer your question: you shouldn't rely on change events to hide / show certain fields, this goes against the very nature of React (React is declarative, what you're describing is an imperative way of doing things). Instead, figure out what state (/props) should lead to which UI.
unknown
d14417
val
Java solves both issues presented in that article: * *Shallowly immutable data holders ➙ Records *Read-only maps ➙ Map.copyOf Leaking references is an important issue. But that article’s solution seems overwrought to me in its approach. * *Certainly creating the CustomerRecords to hold a map seems redundant and useless. Instead, use a non-modifiable map (discussed below). *As for a "read-only" interface as view onto a mutable object, this might make sense in some limited situations. But you might also wreak havoc when the supposedly immutable "CustomerReadOnly" returns a different email address on the second call to "getEmail" after an update. Trying to be simultaneously both mutable and immutable is unwise. To handle immutability, instead make an immutable copy of the mutable state. Records The Records feature being previewed in Java 14 and previewed again in Java 15, and discussed by Brian Goetz, provide for shallowly immutable data holders. This special kind of class handles automatically the constructor, “getter” accessors, equals, hashCode, and toString methods behind the scenes. So your example class Customer turns into this utterly simple code: record Customer( String name , String email ) {} You retain the option of implementing those various methods if need be. For this example here, you might want a constructor to do data validation, ensuring non-null arguments, and specifically a non-empty name, and valid-looking email address. Read-only Map Java 10 gained the Map::copyOf method to instantiate a non-modifiable Map using the entries of another Map. Map< String , Customer > customersByNameReadOnly = Map.copyOf( otherMap ) ; So no need for defining a CustomerRecords class. To change immutable data, make a copy You asked: What if the data does need to be updated? For example, I copied the code from the blog post down below and also added an additional class member of "email". Say the customer changed his email address. If your goal is thread-safety through immutable data, then you must deal with copies of your data. If the customer represented by a Customer record object changes their email address, then you must create a new fresh Customer record object, swap any references to the old object, and let the old object go out-of-scope to become a candidate for garbage-collection. Some folks believe in an everything-should-be-immutable approach, with programming languages designed to cater to such an approach. Personally, I believe that to be practical some classes should be mutable while other kinds of classes should be immutable. In my view, complex business objects such as an invoice or purchase order should often be mutable. Simpler kinds of data, such as a date, should be immutable. When doing an accounting app, I expect changes to an invoice, but if the date of that invoice suddenly changes because some other invoice happens to be pointing to the same mutable date object via an “escaped reference”, then I would be mightily annoyed. To my mind, the invoice should be mutable while the date object member on that invoice should be immutable. So I appreciate that Java gives us a “middle way”. Rather than be slavishly devoted to the everything-is-immutable approach, or frustrated by mutability in objects I expect to be stable, with Java we can pick and choose an appropriate route. * *When immutability is desired, use Java Records for immutable objects, and use Map.of, Set.of, and List.of (or .copyOf) for unmodifiable collections. *When mutability is appropriate, use regular Java classes and collections. As for that “read-only” interface on a mutable object, that seems generally to be confusing at best, and dangerous at worst. I think an object should be clearly and truly immutable or mutable, but not try to be both. Immutable example: java.time For examples of this, see the java.time classes that years ago supplanted the terrible date-time classes bundled with the earliest versions of Java. In java.time the classes are immutable by design, and therefore thread-safe. LocalDate today = LocalDate.now() ; LocalDate tomorrow = today.plusDays( 1 ) ; In the code above, we capture the current date as seen in JVM’s current default time zone. Then we add a day to move to "tomorrow". But adding a day does not affect the original object referenced by today variable. Rather than alter (“mutate”) the original, we instantiate a new, second LocalDate object. The new object has values based on values from the original, along with our desired change (adding a day). The java.time framework even worked out some handy naming conventions. The names to…, from…, parse, format, get…, with, and so on makes dealing with the immutability more intuitive. You may want to follow these conventions in your own coding.
unknown
d14418
val
In the following line: species[s-1] = [] you're assigning an empty list to a list of numbers, which results in something like: 20 [20, 2] 2 Then when you try to compare a number and a list: if species[s-1] > species[s]: you'll get that error: TypeError: unorderable types: int() > list()
unknown
d14419
val
Read about node.js and expressjs. Node.js is server and Expressjs - web framework under Node.js. Apache is also web server and you don't need to use them together. You can place Node.js app behind Nginx or HAproxy if you want. A: You can use a Node.js app (built with Express or whatever you like) standalone, you don't need to use something in front of it. If you want to use something in front of it though, I suggest you use something like Nginx better than Apache, since Nginx is also asynchronous (like Node) and it's performs really well at serving static files. A: All you have to do is set node.js as proxy pass inside your site config here is text on it http://httpd.apache.org/docs/2.0/mod/mod_proxy.html Just decided which port to use and which framework :) eg. http://www.expressjs.com
unknown
d14420
val
Here's a method that does not use eval but does wrap the params in a fake function call and uses parse to extract them #sample function myfun<-function(...) { print(list(...)) } strparam <- "na.rm=TRUE, plot=F, age=15" params <- as.list(parse(text=paste0("f(", strparam , ")"))[[1]])[-1] do.call(myfun,params) A: If the input format follows some specification, you can always do string processing: fun <- "mean" args <- "trim=0.1, na.rm=FALSE" args <- strsplit(args, ",", fixed=TRUE) args <- strsplit(args[[1]], "=", fixed=TRUE) names(args) <- gsub(" ", "", sapply(args, "[", 1), fixed=TRUE) args <- lapply(args, "[", -1) args <- lapply(args, type.convert) do.call(get(fun), c(list(1:10), args)) #[1] 5.5 mean(1:10, trim=0.1, na.rm=FALSE) #[1] 5.5 But it's always dangerous to allow arbitrary input.
unknown
d14421
val
There is an example in the LibGDX tests that does drawing. All of the source code for LibGDX including the tests can be found here: http://github.com/libgdx/libgdx As for the shapes, there is a shape renderer, I have never used it, but you could maybe use it for a drawing game. Best of luck.
unknown
d14422
val
Just add this style #cssmenu > ul > li > ul{display: block!important;} Here is the FIDDLE A: if you need the first menu to open on page load and you still want it to work as an accordion, trigger click event, on first menu item in top accordion, onload. $('#cssmenu li.has-sub>a').on('click', function(){ ... }); $('#cssmenu>ul>li.has-sub>a').click(); check the fiddle
unknown
d14423
val
I saw index, id also is props. You just update UpdatePngf: function UpdatePngf({index, id, ...props}) { ... } And pass props to UpdatePng wwhen using it: <UpdatePng id="...." index="..." ...yourProps>
unknown
d14424
val
I think you are confusing two frameworks, jQuery and Phaser. For loading and displaying sprites you don't need jQuery, just Phaser will do. The load.spritesheet expects a spritesheet where all sprites have a fixed width and height, so with all sprites in a grid layout. What you have sounds like a spriteatlas, the difference being that in a spriteatlas each sprite can have a different width and height, and all these widths and heights per sprite are described in the accompanying .JSON file. So I think you are looking for the load.atlasJSONHash function, something like this: function preload(){ //.. game.load.atlasJSONHash('robot', 'assets2/VillainSpriteSheet.png', 'assets2/VillainSpriteSheet_json.json'); // and then load a sprite like so // Note: 'myframename1' should be some framename from the .json file var villain = game.add.sprite(50, 50, 'robot', 'myframename1'); And btw just to clarify, the load.json in Phaser can be used to just load a .json file, for example with for your own customised data like level layouts, dialog/multilanguage texts, highscore data, enemy patterns etc. A: You don't want jQuery's getJSON(). You want the Phaser one. It would be something like p = new Phaser.Game(...); p.cache.getJSON('foo'); p.load.image(...);
unknown
d14425
val
This will be fixed in node v8.2.1 which should be landing today.
unknown
d14426
val
You can use fillna to merge the two columns with same name then append the last column. First load the files: df1 = pd.read_excel("new_excel_file.xlsx", sheet_name = "Sheet1") df2 = pd.read_excel("new_excel_file.xlsx", sheet_name = "Sheet2") Fill empty columns in df1 with df2: fill = df1.fillna(df2[['Name', 'Class', 'Date']]) Then join the last column: result = teste.join(df2[['City']]) Edit Since you edited your post, just use fill = df1.fillna(df2) and it will do The output: Name Class City Date Misc Misc2 Blank Col 0 Tom Q,W AA 2020-11-01 00:00:00 xxx 12 -- 1 Jerry W AA 2019-03-05 00:00:00 xx 32 -- 2 Don E,R BB 2020-05-06 00:00:00 yyyyy 54 -- 3 Rob T,Y BB 2020-01-02 00:00:00 zz 23 -- 4 Mike W CC 2018-03-05 00:00:00 yy 54 -- 5 Ann O,p CC 2020-09-04 00:00:00 ww 32 --
unknown
d14427
val
try setting outline and/or border properties of select. select{outline:1px solid green;border:1px solid black;} A: Currently there is no way I know of that this can be accomplished using only CSS. However, using jQuery I was able to achieve a similar effect. Live Demo Your dropdown changes because i have to set the size of the select element which makes it look like a list-box. Maybe somebody can improvise on this. Here is the jQuery i used $(document).ready(function (event) { $('select').on('mouseenter', 'option', function (e) { this.style.background = "limegreen"; }); $('select').on('mouseleave', 'option', function (e) { this.style.background = "none"; }); }); A: Try to change like this, hope it may help you select option{ background: red; color: #fff; outline:1px solid green; }
unknown
d14428
val
Due to runtime type erasure, you need to provide what's called a type token to the class: public class ItemSelector<T> { private final Class<T> clazz; public ItemSelector(Class<T> clazz) { this.clazz = clazz; } public void test(GameObject ob) { if (clazz.isInstance(ob)) {// use token to check type // do work } } } This requires a class object to be passed to the constructor, usually by passing a class literal, eg MyClass.class A: There is a way to check the type with class.getTypeName(). I assume the SpecificItemWorker is a game object as shown in the code. package stackoverflow.question39718130; public class SpecificItemWorker extends GameObject { } package stackoverflow.question39718130; public class ItemSelector<T> { private T t; public ItemSelector(final T t) { this.t = t; } public T getT() { return t; } public void test(final GameObject ob) { /*if (ob instanceof T) {// compile error // do work }*/ if (t.getClass().getTypeName() == ob.getClass().getTypeName()) { System.out.println("Grab item."); } else { System.err.println("No item found."); } } } There is a test example to pass the GameObject. package stackoverflow.question39718130; public class GameObjectTest { public static void main(final String[] args) { specificItemWorkerTest(); } public static void specificItemWorkerTest() { final GameObject specificItemWorker = new SpecificItemWorker(); final ItemSelector<GameObject> selector = new ItemSelector<>(specificItemWorker); selector.test(specificItemWorker); } } I hope I understood you right with the SpecificItemWorker. Please let me know if this fits to your solution.
unknown
d14429
val
you have encrypt the password twice, on your model and controller. just remove one of them e.g: don't use bcrypt on your controller, because you have already use bcrypt on your model.
unknown
d14430
val
You can use the stack view and then hide the required objects i.e label or image. Remember to give the proper constraints to the stack view and select the required properties. A: I fixed this by dynamically adding the constraint cell.match.translatesAutoresizingMaskIntoConstraints = false cell.match.constraints.forEach { (constraint) in if constraint.firstAttribute == .height { constraint.constant = release.post.height(withConstrainedWidth: cell.match.frame.width, font: UIFont.preferredFont(forTextStyle: UIFont.TextStyle.subheadline)) + 15 } }
unknown
d14431
val
Your some_sorter_by_mtime should be for example: xargs stat -f "%m %N" | sort -n | cut -f2- the idea behind is: * *print out file modification time and the filename *sort the output numerically (so by modification time) *cut out the time field so, find / -type f -print | xargs stat -f "%m %N" | sort -n | cut -f2- A: Like this? find / -type f -print | xargs ls -l --time-style=full-iso | sort -k6 -k7 | sed 's/^.* \//\//' A: Yes, without perl: find / -type f -exec ls -lrt '{}' \+ Guru.
unknown
d14432
val
Found the problem, leaving it here for reference. I was not handling the pause()/onPause() life-cycle step and therefore never calling: @Override protected void onPause() { super.onPause(); Log.v(this, ".onPause()"); mBus.unregister(this); // unregisters. } Changing the above code as following solved: @After public void tearDown() throws Exception { mController = mController.pause().stop().destroy(); }
unknown
d14433
val
4 objects will be created. Two notes: * *new String("something") always creates a new object. The string literal "something" creates only one object for all occurrences. The best practice is to never use new String("something") - the instantiation is redundant. *the concatenation of two strings is transformed to StringBuilder.append(first).append(second).toString(), so another object is created here. A: each of the str1, str2, str3, str4 are String objects . str1 : "String1" is a string literal and Java creates a String object whenever it encounters a string literal. str2 : as you are using the new keyword and constructor of the class String a String object is created str3 : similar to str1 str4 : concatenated string literal, similar to str1 edit : http://download.oracle.com/javase/tutorial/java/data/strings.html
unknown
d14434
val
Use a function to check when you have an element as array then convert back to json: <?php $json = "{ \"foo\": \"bar\", \"nested\": { \"nested_key\": \"nested_value\" }, \"multinested\": { \"multinested_key\": { \"multinested_key\": \"nested_value\" } }, \"another_top_level_key\": \"some_useful_value\" }"; $array = json_decode($json, true); foreach($array as &$item) { if (is_array($item)) { $item = json_encode($item); } } print_r($array); Output: Array ( [foo] => bar [nested] => {"nested_key":"nested_value"} [multinested] => {"multinested_key":{"multinested_key":"nested_value"}} [another_top_level_key] => some_useful_value ) A: The trick is to use the decode twice: $array = json_decode(json_decode($json, true), true); print_r($array);
unknown
d14435
val
I solved my problem. Instead of using the glob function I used the os.listdir to read all my excel sheets, loop through each excel file, reformat, then append the final data to the end of the table. #first create empty appended_data table to store the info. appended_data = [] for WorkingFile in os.listdir('C:\ExcelFiles'): if os.path.isfile(WorkingFile): # Import the excel file and call it xlsx_file xlsx_file = pd.ExcelFile(WorkingFile) # View the excel files sheet names xlsx_file.sheet_names # Load the xlsx files Data sheet as a dataframe df = xlsx_file.parse('sheet1',header= None) #.... do so reformating, call finished sheet reformatedDataSheet reformatedDataSheet appended_data.append(reformatedDataSheet) appended_data = pd.concat(appended_data) And thats it, it does everything I wanted. A: you need to change os.chdir('C:\ExcelWorkbooksFolder') for FileList in glob.glob('*.xlsx'): print(FileList) to just os.chdir('C:\ExcelWorkbooksFolder') FileList = glob.glob('*.xlsx') print(FileList) Why does this fix it? glob returns a single list. Since you put for FileList in glob.glob(...), you're going to walk that list one by one and put the result into FileList. At the end of your loop, FileList is a single filename - a single string. When you do this code: for File in FileList: for x in File: the first line will assign File to the first character of the last filename (as a string). The second line will assign x to the first (and only) character of File. This is not likely to be a valid filename, so it throws an error.
unknown
d14436
val
Well there's not a special many to two relationship but what you'd probably do is something like this: public class NodeMap : ClassMap<Node> { public NodeMap() { //Id and any other fields mapped in node HasMany(x => x.Links); } } public class LinkMap : ClassMap<Link> { public LinkMap() { //Id and any other fields mapped in node References(x => x.StartNode); References(x => x.EndNode); } } Again this is just a brief overview above. You will probably need additional mapping attributes if you want to for example cascade any create/update/delete actions.
unknown
d14437
val
I think it might be something like this: <Series:StackedLineSeries.IndependentAxis> <Series:LinearAxis xmlns:datavis="using:WinRTXamlToolkit.Controls.DataVisualization"> <Series:LinearAxis.TitleStyle> <Style TargetType="datavis:Title"> <Setter Property="Visibility" Value="Collapsed"/> </Style> </Series:LinearAxis.TitleStyle> </Series:LinearAxis> </Series:LineSeries.IndependentAxis>
unknown
d14438
val
At the last step of i loop you are setting temp to null instead of setting it to a new array using new ArrayList<String>();. This will cause temp.add(newHeaders[j]); to through the null pointer exception. change temp = null; to temp = new ArrayList<String>(); A: The error is with the line temp = null; You are not reinitializing temp again. if you move the line ArrayList<String> temp = new ArrayList<String>(); between the two for loops all should be fine.
unknown
d14439
val
Just use the java.lang.BigInteger class. It has a pow() method that does exactly what you want in a rather efficient way. A: Since the exponent is in int, you already have the binary representation of the number (well the computer does). So you should have three integers, the base, the exponent and a temporary integer that you will use for computation and one more for solution. You start with this: unsigned int base;//you manage input for this and exponent like you wish, probably passed in as parameters unsigned int exponent; unsigned int temp = base; unsigned int answer = 1; while (exponent!=0){ if (exponent%2 == 1){ answer *= temp; } exponent>>1; temp<<1; } Please try this algorithm and let me know how it works. The while look runs at max the bit length of the exponent (i.e. 32 times). This code doesn't handle large numbers or negative numbers, but I'm not sure if you require this or not.
unknown
d14440
val
Try with bfill df['new'] = df.bfill(axis=1)['VAR1'].str[0]
unknown
d14441
val
<html> <head> <script type="text/javascript" src="js/jquery_1.7.1_min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#unos').click(function() { $("#tre").attr('src', '/012/11/image2.jpg'); }); }); </script> </head> <body> <img id="tre" class="aligncenter" title="images" src="/012/11/image1.jpg" alt="" width="940" height="207" /> <input id="unos" type="submit" name="change_src" value="change image" /> </body> </html>
unknown
d14442
val
Assuming, from the code that you have provided, that your cell has been formatted using Conditional Formatting, you need to access is the Range.DisplayFormat property. Note that I showed only some of the formatting options for a cell. There is documentation online for other formatting options (eg other borders, numberformat, etc) but this should get you started. For example: Option Explicit Sub foo() Dim R As Range, C As Range Dim fc As FormatCondition Set R = Range(Cells(1, 1), Cells(5, 1)) For Each C In R With C.DisplayFormat Debug.Print .Interior.Color Debug.Print .Font.Name Debug.Print .Font.Color Debug.Print .Borders(xlEdgeLeft).LineStyle ' etc Debug.Print .Font.Size End With Stop Next C End Sub If the cell has been formatted manually, or directly using code, then just access the various properties directly, not using the DisplayFormat property eg: For Each C In R With C Debug.Print .Interior.Color Debug.Print .Font.Name Debug.Print .Font.Color Debug.Print .Borders(xlEdgeLeft).LineStyle ' etc Debug.Print .Font.Size End With Stop Next C A: What you are looking for are the Range.Interior and Range.Font properties etc. You can see some examples in the links below: https://learn.microsoft.com/en-us/office/vba/api/excel.font(object) https://learn.microsoft.com/en-us/office/vba/api/excel.interior(object) https://learn.microsoft.com/en-us/office/vba/api/excel.border(object)
unknown
d14443
val
Suppose you have a Record class for each entry public class Record { public String name; public Integer date; public String status; public Record(String name, Integer date, String status) { this.name = name; this.date = date; this.status = status; } } You can use Stream API to achieve your goals public static Map<String, Integer> useStream(List<Record> records) { return records.stream() .collect(Collectors.groupingBy(r -> r.name)) .entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> { Integer[] lastFail = new Integer[]{null}; return e.getValue().stream() .sorted(Comparator.comparing(r -> r.date)) .mapToInt(t -> { if (t.status.equals("fail") && lastFail[0] == null) { lastFail[0] = t.date; } else if (t.status.equals("success") && lastFail[0] != null) { int last = lastFail[0]; lastFail[0] = null; return t.date - last; } return 0; }) .sum(); })); } Or you can use better Seq API with smoother code public static Map<String, Integer> useSeq(List<Record> records) { return Seq.of(records) .groupBy(r -> r.name) .toList() .toMap(Map.Entry::getKey, e -> { Integer[] lastFail = new Integer[]{null}; return Seq.of(e.getValue()) .sortBy(r -> r.date) .sumInt(t -> { if (t.status.equals("fail") && lastFail[0] == null) { lastFail[0] = t.date; } else if (t.status.equals("success") && lastFail[0] != null) { int last = lastFail[0]; lastFail[0] = null; return t.date - last; } return 0; }); }); } Both of these methods result as {chris=6, john=7}
unknown
d14444
val
In the documentation of the API, it is mentioned that the "body" of the request is the raw binary data for the *.wav file that you have recorded. This means you just need to send the file as is without any decoding.
unknown
d14445
val
You can use (?:\G(?!^)',\s*'|\bIN\s*\(')\K\d+ (?<=\bIN\s*\([^()]*)\d+ See regex demo #1 and regex demo #2. Regex #1 (compliant with Boost, PCRE, Onigmo regex libraries): * *(?:\G(?!^)',\s*'|\bIN\s*\(') - end of the previous match and then ', ,, zero or more whitespace and then a ', or a whole word IN followed with (' substring *\K - match reset operator that discards the currently matched text *\d+ - one or more digits Regex #2 (compliant with JavaScript ECMAScript 2018+, .NET, PyPi regex): * *(?<=\bIN\s*\([^()]*) - a location that is immediately preceded with * *\bIN - whole word IN *\s* - zero or more whitespaces *\( - a ( char *[^()]* - zero or more chars other than ( and ) *\d+ - one or more digits.
unknown
d14446
val
You have to check for optional in numberOfRows Method and do it like this func myFunc() { let queue1 = DispatchQueue(label: "com.appname.queue") queue1.async { let realm = try! Realm() // get file JSON from local device and write data from it to RealmDB if realm.isEmpty { //local file JSON let file = Bundle.main.path(forResource: "file", ofType: "json")! let url = URL(fileURLWithPath: file) let jsonData = NSData(contentsOf: url)! //Serialization JSON let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: []) realm.beginWrite() //Create data from JSON to our objects realm.create(DataRoot.self, value: json, update: true) try! realm.commitWrite() DispatchQueue.main.async { self.tableview.reloadData() } } } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let routes = transport.filter("id == 1").first?.routes { return routes.count } return 0 } A: To generally answer your question: the high level Realm feature you want to be using here is notifications. You should be architecting your app in such a way that the data you want to use to back a view controller can be represented in a Realm query or notification, so that when the underlying data for a view or controller changes, you can perform the relevant view update actions. There are some other problems with your code, such as potentially accessing a Realm instance from a different thread than the one on which it was created. I suggest you read more about this in Realm's Threading documentation.
unknown
d14447
val
You can use a property having an array of Strings as value: MERGE (a:Person{number:'123'}) MERGE (b:Person{number:'456'}) MERGE (a)-[r:CALLED]->(b) ON CREATE SET r.duration = ["100-200->500"] ON MATCH SET r.duration = ["100-200->500"] Later on when adding the second duration value, use MERGE (a:Person{number:'123'}) MERGE (b:Person{number:'456'}) MERGE (a)-[r:CALLED]->(b) ON MATCH SET r.duration = n.duration + "200-100->600" N.B. the "+" operator on an array amends a new element to the array.
unknown
d14448
val
You may delete the whole queue with AMQP::Queue#delete Just take the AMQP::Queue instance and call queue.delete or queue.delete do |_| puts "Deleted #{queue.name}" end
unknown
d14449
val
Ok, this wasn't easy - Due to a bug in PDFClown the my main stream of information in the PDF page has been corrupted. After it's end it had a copy of a past instance of it. This caused a partial text section without the starting command "BT" - which left a single "ET" without a "BT" in the end of the stream. once I corrected this, it ran great. Thank you all for your help. I would have much more difficult time debugging it without the tool RUPS which @Bruno suggested. edit: The bug was in the Buffer.java:clone() (line 217) instead of line: clone.append(data); needs to be: clone.append(data, 0, this.length); Without this correction it clones the whole data buffer, and set the cloned Buffer's length to the data[].length. This is very problematic if the Buffer.length is smaller than the data[].length. The result in my case was that in the end of the stream there was garbage. A: The error shows while reading (with Adobe) the attached file only when scrolling down to the 8'th page, then scrolling back up to 3'td page. Alternatively, Zooming out to 33.3% will also produce the message. Well, I get it easier, I merely open the PDF and scroll down using the cursor keys. As soon as the top 2 cm of page 3 appear, the message appears. What's wrong with my file?? The content of pages 1 and 2 look ok, so let's look at the content of page 3. My initial attributing the issue to the use of text specific operations (especially Tf and Tw) outside of a text object was wrong as Stefano Chizzolini pointed out: Some text related operations indeed are allowed outside text objects, namely the text state operations, cf. figure 9 from the PDF specification: So while being less common, text state operations at page description level are completely ok. After my incorrect attempt to explain the issue, the OP's own answer indicated that the main stream of information in the PDF page has been corrupted. After it's end it had a copy of a past instance of it. This caused a partial text section without the starting command "BT" - which left a single "ET" without a "BT" in the end of the stream. An ET without a prior BT indeed would be an error, and quite likely it would be accompanied by operations at the wrong level... Inspecting the stream content of that third page (the focused page of this issue), though, I could not find any unmatched ET. In the course of that inspection, though, I discovered that the content stream contains more than 2000 trailing 0 bytes! Adobe Reader seems not to be able to cope with these 0 bytes. The bug the OP found, can explain the issue: in the Buffer.java:clone() (line 217) instead of line: clone.append(data); needs to be: clone.append(data, 0, this.length); Without this correction it clones the whole data buffer, and set the cloned Buffer's length to the data[].length. This is very problematic if the Buffer.length`` is smaller than the data[].length. Trailing 0 bytes can be an effect of such a buffer copying bug. Furthermore symptoms as found by the OP (After it's end it had a copy of a past instance of it) can also be the effect of such a bug. So I assume the OP found those symptoms on a different page, not page 3, but fixing the bug healed all symptoms. How can I find what's wrong with it? is there a tool which tells you where does the error lie? There are PDF syntax checkers, e.g. the Preflight tool included in Adobe Acrobat. but even that fails on your file. So essentially you have to extract the page content (using a PDF browser, e.g. RUPS) and check manually with the PDF specification on the other screen. A: the general post about debugging pdf might have been also helpful as rups / pdfstreamdump etc is mentioned there How do you debug PDF files?
unknown
d14450
val
this query is working : update accbalance set econ = econ + @winnings where id=@id and econ > @bet ; Next time please create a sqlfiddle , it can help . the query was tested in : http://sqlfiddle.com/#!9/960009/1 . A: You should be able to integrate the comparison into your UPDATE query: UPDATE users SET econ = econ + ? WHERE econ > ? AND id = ? Here I've used placeholders on the assumption you would prepare the query, in order they are for winnings, bet and id
unknown
d14451
val
there is natural Id which automaticly creates a unique constraint on schema creation and can be used to query for it more efficiently. in xml <natural-id> <property name="name"/> <property name="org"/> </natural-id> naturalids use the second level cache more efficient and from H4.1 on loading by naturalid uses the first level cache and can save roundtrips. Other than that natural ids are just like normal properties. you could however write a generic natural id checker * *create a new object with the properties set *access through the sessionfactory the classmetadata of the object *iterate the natural id properties and use them to get the values from your object and set them on the using(propertyname, propertyvalue) *if something is found copy the data, else just save the object you just created
unknown
d14452
val
You have a problem with the total_entries variable. First of all you need a "var" in front, to define that it's a new variable. Second, you forgot a "." (dot) to search for the class in your HTML code.. your first line should be: var total_entries = $(".image-entry").length; Hope it works ;-)
unknown
d14453
val
Try x.set_tick_position('bottom') instead of ax1.x.set_tick_position('bottom'). x is already an attribute off of the ax1 object, so you don't need to access ax1 again. Furthermore, no need for getattr if you know the name of the attribute statically. You can just do x = ax1.xaxis. A: I would suggest to work on the objects directly. nax=[ax1,ax2,ax3,ax4] for ax in nax: for axis in ['bottom','left']: ax.spines[axis].set_linewidth(0.5) for axis in ['right','top']: ax.spines[axis].set_visible(False) ax.xaxis.set_tick_position('bottom')
unknown
d14454
val
This hasn't been possible in the past, however you're far from the first person to ask for it. Custom control exceptions would provide a way for framework-style things to do internal control flow without CATCH/default in user code accidentally swallowing the exceptions. Bleeding edge Rakudo now contains an initial implementation of taking X::Control as an indication of a control exception, meaning that the code as you wrote it now does as you expect. This will, objections aside, appear in the 2019.01 Rakudo release, however should be taken as a draft feature until it also appears in a language specification release. Further, a proposed specification test has been added, so unless there are objections then this feature will be specified in a future Perl 6 language release.
unknown
d14455
val
At the time of writing there is no accepted solution that handles everything you want. CMake gives you cross-platform builds and git (with submodules) gives you a way to manage source-level dependencies if all other projects are using CMake. But, in practice, many common dependencies you project wil need don't use CMake, or even Git. Ryppl is meant to solve this, but progress is slow because the challenge is such a hard one. Arguably, the most successful solution so far is to write header-only libraries. This is common practice and means your users just include your files, and their build system of choice takes care of everthing. There are no binary dependencies to manage. A: TheHouse's answer is still essentially true. Also there don't seem to have been any updates to ryppl itself for a while (3 years) and the ryppl.org domain has expired. There are some new projects aiming to solve the packaging issue. Both build2 and wrap from mesonbuild have that goal in mind. A proposal was made recently to add packages to the c++ standard which may open up the debate (reddit discussion here). Wrap looks promising as meson's author has learned from cmake. There is a good video when its author discussing this here. build2 seems more oblivious (and therefore condemned to reinvent). However both suffer from trying to solve the external project dependencies issue simultaneously with providing a complete build system. conan.io is another recent attempt which doesn't try to provide the build system as well. Time will tell if any of these gain any traction. The accepted standard for packaging C and C++ projects on Unix was always a source tarball + a configure script (autotools) + make. cmake is now beginning to replace autotools as your first choice. It is able create RPMs and tarballs for distribution purposes. Its also worth considering the package managers built into the various flavours of Linux. The easiest to build and install projects are those where most of the dependencies can be pulled in via yum or apt. This won't help you on windows of course. While there is a high barrier to entry getting your own projects added to the main Linux repositories (e.g. RedHat, Debian) there is nothing to stop you adding your maintaining your own satellite repo. The difference between that and just hosting your project on github or similar is you can provide pre-built binaries for a number of popular systems. You might also consider that configure times checks (e.g. from cmake findLibrary()) and your own documentation will tell people what needs to be installed as a prerequisite and providing you don't make it too onerous that might be enough.
unknown
d14456
val
If your result is null you set the status of the response but don't return anything. Usual way to do this is the call next() to end the route: router.get('/:id', function (req, res, next) { models.Utilisateur.find({ where: { id: req.params.id }, include: [{model: models.Profil, include: [{model: models.Fonctionnalite}], through: {attributes: []}}] }).then(function (result) { if (result === null) { res.status(204); next(); } else { res.status(200); res.json(result); } }); }); or you could just return a json object instead. res.json({error: "not found"});
unknown
d14457
val
Like @CBroe pointed out in the comment there was a version mismatch, the code was for Bootstrap 4.0 and the Bootstrap version I was using was 5.0.
unknown
d14458
val
I can't answer regarding Windows, but on Ubuntu 18.04 I can confirm that a git checkout or git merge will delete and recreate a changed file, rather than editing it in place. This can be seen in strace output, for example: unlink("test.sh") = 0 followed later by openat(AT_FDCWD, "test.sh", O_WRONLY|O_CREAT|O_EXCL, 0666) = 4 It can also be seen if you create a hard link to the file before the git command and then look again afterwards, you will see that you have two different inodes, with different contents. This is to be expected following deletion and recreation, whereas an in-place edit would have preserved the hard linking. $ ls -l test.sh -rw-r--r-- 1 myuser mygroup 59 Jun 5 17:04 test.sh $ ln test.sh test.sh.bak $ ls -li test.sh* 262203 -rw-r--r-- 2 myuser mygroup 59 Jun 5 17:04 test.sh 262203 -rw-r--r-- 2 myuser mygroup 59 Jun 5 17:04 test.sh.bak $ git merge mybranch Updating 009b964..d57f33a Fast-forward test.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) $ ls -li test.sh* 262219 -rw-r--r-- 1 myuser mygroup 70 Jun 5 17:05 test.sh 262203 -rw-r--r-- 1 myuser mygroup 59 Jun 5 17:04 test.sh.bak You mentioned in a comment attached to the question that it is related to Overwrite executing bash script files. Although it would seem not to be the best idea to run a git command affecting a script which is currently still being executed, in fact the delete and recreate behaviour should mean that the existing execution will be unaffected. Even if the bash interpreter has not yet read the whole file into memory, it will have an open filehandle on the existing inode and can continue to access its contents even though that inode is no longer accessible via the filename that it had. See for example What happens to an open file handle on Linux if the pointed file gets moved or deleted A: On Windows with git-for-windows I see the same behavior: $ mklink /H test.sh.bak $ fsutil hardlink list test.sh.bak test.sh.bak test.sh $ git merge test $ fsutil hardlink list test.sh.bak test.sh.bak Meaning the hard link did not get preserved, meanin a new file has been created.
unknown
d14459
val
Your sprite file is wonky. You should not have multiple nested <symbol> elements. <symbol viewBox="0 0 0 0" id="delete"> <symbol viewBox="0 0 0 0" id="delete"> Each icon should only have one. The reason your "delete" icon is not showing is because, when the browser tries to find the "delete" symbol, it has two that have id="delete". That is illegal for a start, because id attributes must be unique. It will choose one of them. In this case it doesn't matter which one it chooses. That's because all that either "delete" symbol contains is a <symbol> element. Which is effectively nothing, because <symbol> elements by themselves are not rendered. They are only rendered when referenced by a <use>. You got lucky with the "edit" symbol, because you have three of those. But luckily your browser is probably picking the first id match it finds. And for id="edit" the first one is three levels down inside the nested <symbol id="delete"> ones. In other words, your sprite file looks like this to the browser <svg width="0" height="0" class="hidden"> <symbol viewBox="0 0 0 0" id="delete"> </symbol> <symbol fill="#000000" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" id="edit"> <path d="M 18.414062 2 C 18.158062 2 17.902031 2.0979687 17.707031 2.2929688 L 15.707031 4.2929688 L 14.292969 5.7070312 L 3 17 L 3 21 L 7 21 L 21.707031 6.2929688 C 22.098031 5.9019687 22.098031 5.2689063 21.707031 4.8789062 L 19.121094 2.2929688 C 18.926094 2.0979687 18.670063 2 18.414062 2 z M 18.414062 4.4140625 L 19.585938 5.5859375 L 18.292969 6.8789062 L 17.121094 5.7070312 L 18.414062 4.4140625 z M 15.707031 7.1210938 L 16.878906 8.2929688 L 6.171875 19 L 5 19 L 5 17.828125 L 15.707031 7.1210938 z"></path> </symbol> </svg> Fix the nested symbol problem. It looks like you are passing, to that utility, SVG files that already contain only symbols. So it is simply wrapping symbols in other symbols. I expect you should be passing renderable SVGs to that utility. If your SVG files don't render anything when opened with a browser, they are probably already a "sprite sheet". Only use SVGs that display something when opened in a browser. For your immediate problem, try this manually fixed file instead. <svg width="0" height="0" class="hidden"> <symbol fill="#000000" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" id="delete"> <path d="M 18.414062 2 C 18.158062 2 17.902031 2.0979687 17.707031 2.2929688 L 15.707031 4.2929688 L 14.292969 5.7070312 L 3 17 L 3 21 L 7 21 L 21.707031 6.2929688 C 22.098031 5.9019687 22.098031 5.2689063 21.707031 4.8789062 L 19.121094 2.2929688 C 18.926094 2.0979687 18.670063 2 18.414062 2 z M 18.414062 4.4140625 L 19.585938 5.5859375 L 18.292969 6.8789062 L 17.121094 5.7070312 L 18.414062 4.4140625 z M 15.707031 7.1210938 L 16.878906 8.2929688 L 6.171875 19 L 5 19 L 5 17.828125 L 15.707031 7.1210938 z"></path> </symbol> <symbol fill="#000000" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" id="edit"> <path d="M 18.414062 2 C 18.158062 2 17.902031 2.0979687 17.707031 2.2929688 L 15.707031 4.2929688 L 14.292969 5.7070312 L 3 17 L 3 21 L 7 21 L 21.707031 6.2929688 C 22.098031 5.9019687 22.098031 5.2689063 21.707031 4.8789062 L 19.121094 2.2929688 C 18.926094 2.0979687 18.670063 2 18.414062 2 z M 18.414062 4.4140625 L 19.585938 5.5859375 L 18.292969 6.8789062 L 17.121094 5.7070312 L 18.414062 4.4140625 z M 15.707031 7.1210938 L 16.878906 8.2929688 L 6.171875 19 L 5 19 L 5 17.828125 L 15.707031 7.1210938 z"></path> </symbol> </svg>
unknown
d14460
val
It looks you have blank user_id column when comments doesn't have user. So the correct query should be @post = Post.find(1) @comments = @post.comments.where("user_id != ''") A: I'd do this: #app/models/post.rb class Post < ActiveRecord::Base has_many :comments do def no_user where.not(user_id: "") #-> http://robots.thoughtbot.com/activerecords-wherenot end end end #app/models/comment.rb class Comment < ActiveRecord::Base belongs_to :post end This will allow me to call: #app/controllers/comments_controller.rb class CommentsController < ApplicationController def show @post = Post.find params[:post_id] @comments = @post.comments.no_user end end -- Notes on Null Having null is a specific data-type in your database We use it when wanting to "default" populate a table's columns - allowing you to submit no data, having the database be as efficient as possible in providing the right allocations of data. I would certainly look up about the NULL data type with the likes of MYSQL & PGSQL. This will give you the ability to define any unpopulated data columns as NULL - allowing you to call the NOT NULL command. Currently, your "non defined" data is just blank - not null A: My code might not represent a standard way but it would work in both cases(Null and blank). @post = Post.find(1) @comments = @post.comments.where("user_id > 0")
unknown
d14461
val
There is no option to just skip a few characters in each row using a read.table option. Instead, you can call read.table twice, once for all the data after the first row, and the second time for the header. Where your data are in a file called "test.txt", you would do: library(magrittr) tmp <- read.table(file="test.txt", sep="", stringsAsFactors = FALSE, skip=1)[, -c(1:3)] %>% setNames(read.table(file="test.txt", sep="", stringsAsFactors = FALSE, nrows=1)) > tmp xyz ghj asd qwe 1 1 2 3 4 2 5 6 7 8 3 9 10 11 12 > Package magrittr is what gives you the pipe operator %>% that allows you to read the data and the header separately, but put them together in a single line. If you have a sufficiently-new R version you can use the |> operator instead, without the magrittr package.
unknown
d14462
val
Turns out what I need to send to the server is not APNS token, but Firebase token, found in here: https://firebase.google.com/docs/cloud-messaging/ios/client#monitor-token-generation
unknown
d14463
val
You can use indices of sorted elements [S,I]=sort(x(1,:)); result = [S;x(2,I)] The first row is sorted and indices of the sorted elements is used to order the second row. result 2 3 4 9 1 2 8 3 A: There are a couple of ways to achieve this: [y1,I] = sort(x(1,:)) y2 = x(2,I) y = [ y1 ; y2 ] This basically sort the first row of your data, and save the sorting index in I, and then use those index to get the 'sorted' second row, and then just join them or y = sortrows(x')' The ' operator transposes the matrix, which allows you to use sortrows and then use it again to reshape your output matrix. A: You can get the indices directly from sorting the first row. These can be used as an argument in x itself: x=[9 2 4 3 ;3 1 8 2 ]; %get the indices of the first row: [~,indices] = sort(x(1,:)) %return x in the order "indices" for each row: y = [x(1,indices);x(2,indices)]
unknown
d14464
val
You're solving a problem that doesn't exist. You seem to think that select a.Id, a.UserName, getFullName(a.UserName), a.CreateTime from DataTable; Has some relatively expensive process behind it to get UserName that is happening twice. In reality, once the record is located, getting the UserName value is an virtually instant process since it will probably be stored in a "variable" by the SQL engine behind the scenes. You should have little to no performance difference between that query and select a.Id, getFullName(a.UserName), a.CreateTime from DataTable; The scalar function itself may have a performance issue, but it's not because you are "pulling" the UserName value "twice". A better method would be to join to the other table: select a.Id, a.UserName, b.FullName, a.CreateTime from DataTable a LEFT JOIN dbo.NamesTable b ON a.UserName = b.UserName A: As D Stanley says, you're trying to solve some problem that doesn't exist. I would further add that you shouldn't be using the function at all. SQL is meant to perform set-based operations. When you use a function like that you're now making it perform the same function over and over again for every row - a horrible practice. Instead, just JOIN in the other table (a set-based operation) and let SQL do what it does best: SELECT DT.Id, DT.UserName, NT.fullname, DT.CreateTime FROM DataTable DT INNER JOIN NamesTable NT ON NT.username = DT.username; Also, DataTable and NamesTable are terrible names for tables. Of course they're tables, so there's no need to put "table" on the end of the name. Further, of course the first one holds "data", it's a database. Your table names should be descriptive. What exactly does DataTable hold? If you're going to be doing SQL development in the future then I strongly suggest that you read several introductory books on the subject and watch as many tutorial videos as you can find. A: Scalar UDF will execute for every row,but not defintely the way you think.below is sample demo and execution plan which proves the same.. create table testid ( id int, name varchar(20) ) insert into testid select n,'abc' from numbers where n<=1000000 create index nci_get on dbo.testid(id,name) select id,name,dbo.getusername(id) from dbo.testid where id>4 below is the execution plan for above query Decoding above plan: Index seek outputs id,name Then compute scalar tries to calculate new rows from existing row values.in this case expr1003 which is our function Index seek cost is 97%,compute scalar cost is 3% and as you might be aware index seek is not an operator which goes to table to get data.so hopefully this clears your question
unknown
d14465
val
lets say you have an array like this: a= [array([ 1, 24, 4, 5]), array([ 22, 4, 123]), array([11, 1, 1])] #convert all subarrays to list a= [ list(item) for item in a ] no you can check for a sublist like this: In [80]: [1,22,4] in a Out[80]: False In [81]: [1,24,4,5] in a Out[81]: True A: Using the verb is when talking about python is a bit ambiguous. This example covers all the cases I could think of: from __future__ import print_function from numpy import array, array_equal, allclose myarr0 = array([1, 0]) myarr1 = array([3.4499999, 3.2]) mylistarr = [array([1, 2, 3]), array([1, 0]), array([3.45, 3.2])] #test for identity: def is_arr_in_list(myarr, list_arrays): return next((True for elem in list_arrays if elem is myarr), False) print(is_arr_in_list(mylistarr[2], mylistarr)) #->True print(is_arr_in_list(myarr0, mylistarr)) #->False #myarr0 is equal to mylistarr[1], but it is not the same object! #test for exact equality def arreq_in_list(myarr, list_arrays): return next((True for elem in list_arrays if array_equal(elem, myarr)), False) print(arreq_in_list(myarr0, mylistarr)) # -> True print(arreq_in_list(myarr1, mylistarr)) # -> False #test for approximate equality (for floating point types) def arreqclose_in_list(myarr, list_arrays): return next((True for elem in list_arrays if elem.size == myarr.size and allclose(elem, myarr)), False) print(arreqclose_in_list(myarr1, mylistarr)) #-> True PS:do NOT use list for a variable name, as it is a reserved keyword, and often leads to subtle errors. Similarly, do not use array. A: There is a much simpler way without the need to loop using np.all(). It only works when all the arrays within the list of arrays have the same shape: list_np_arrays = np.array([[1., 1.], [1., 2.]]) array_to_check = np.array([1., 2.]) is_in_list = np.any(np.all(array_to_check == list_np_arrays, axis=1)) The variable is_in_list indicates if there is any array within he list of numpy arrays which is equal to the array to check.
unknown
d14466
val
If i understand your question, you want to allocate data. Look alloca malloc fucntions. A: The splitter() function here does the job you ask for. It takes quite a lot of arguments, unfortunately. There's the value to be split (value), the size of the chunk at the least significant end of the value (p1), the size of the middle chunk (p2), and then pointers to the high, medium and low values (hi_val, md_val, lo_val). #include <assert.h> #include <inttypes.h> #include <stdio.h> static void splitter(uint32_t value, unsigned p1, unsigned p2, uint32_t *hi_val, uint32_t *md_val, uint32_t *lo_val) { assert(p1 + p2 < 32); *lo_val = value & ((1U << p1) - 1); value >>= p1; *md_val = value & ((1U << p2) - 1); value >>= p2; *hi_val = value; } static void test_splitter(uint32_t value, int p1, int p2) { uint32_t hi_val; uint32_t md_val; uint32_t lo_val; splitter(value, p1, p2, &hi_val, &md_val, &lo_val); printf("0x%.8" PRIX32 " (%2u,%2u,%2u) = 0x%.4" PRIX32 " : 0x%.4" PRIX32 " : 0x%.4" PRIX32 "\n", value, (32 - p1 - p2), p2, p1, hi_val, md_val, lo_val); } int main(void) { uint32_t value; value = 0xFFFFFFFF; test_splitter(value, 9, 11); value = 0xFFF001FF; test_splitter(value, 9, 11); value = 0x000FFE00; test_splitter(value, 9, 11); value = 0xABCDEF01; test_splitter(value, 10, 6); test_splitter(value, 8, 8); test_splitter(value, 13, 9); test_splitter(value, 10, 8); return 0; } The test_splitter() function allows for simple testing of a single value plus the sections it is to be split in, and main() calls the test function a number of times. The output is: 0xFFFFFFFF (12,11, 9) = 0x0FFF : 0x07FF : 0x01FF 0xFFF001FF (12,11, 9) = 0x0FFF : 0x0000 : 0x01FF 0x000FFE00 (12,11, 9) = 0x0000 : 0x07FF : 0x0000 0xABCDEF01 (16, 6,10) = 0xABCD : 0x003B : 0x0301 0xABCDEF01 (16, 8, 8) = 0xABCD : 0x00EF : 0x0001 0xABCDEF01 (10, 9,13) = 0x02AF : 0x006F : 0x0F01 0xABCDEF01 (14, 8,10) = 0x2AF3 : 0x007B : 0x0301 If any of the sections is larger than 16, the display gets spoiled — but the code still works. In theory, the 1U values could be a 16-bit quantity, but I'm assuming that the CPU is working with 32-bit int. There are ways (UINT32_C(1)) to ensure that it is a 32-bit value, but that's probably OTT. The code explicitly forces 32-bit unsigned integer values, and prints them as such.
unknown
d14467
val
I generally use loadDataFrom on the action that called the form (rather than inside the form function). So for example: ... public function index() { $form =$this->Form(); $form->loadDataFrom($this); $this->customise(array("Form" => $form)); return $this->renderWith("Page"); } ... That way the function only returns the base form and you alter it as and when required. A: Your form will be called once when adding it in the template, and once via request. Since all actions on a controller get the request as parameter, you can modify your form function like so: public function FormUpdate($request = null) { Then inside your function, only populate the form if it's not called via a request, eg. if (!$request) { $form->loadDataFrom($Page); }
unknown
d14468
val
Here is the full solution to the problem statement. apiVersion: batch/v1 kind: Job metadata: name: api-test-trigger annotations: argocd.argoproj.io/hook: PostSync argocd.argoproj.io/hook-delete-policy: HookSucceeded spec: template: metadata: labels: name: api-test spec: containers: - name: api-test args: - /bin/sh - -ec - "curl -X POST -H \"Accept: application/vnd.github.v3+json\" -H \"Authorization: token ${GITHUB_TOKEN}\" ${GITHUB_URL} -d '{\"ref\":\"main\"}'" env: - name: GITHUB_URL value: "https://api.github.com/repos/<your org>/<your repo>/actions/workflows/<workflow id>/dispatches" - name: GITHUB_TOKEN value: <your PAT> image: curlimages/curl You can create the PAT from github settings and provide the PAT as a secret. A: ArgoCD provides a feature called resource hooks. Hooks are ways to run scripts before, during, and after a sync operation. A use case for hooks from the official documentation: Using a PostSync hook to run integration and health checks after a deployment. Hooks can be any type of Kubernetes resource kind, but tend to be Pod, Job, or Argo Workflows. Per the GitHub actions documentation, you can send a POST request to the Github API in PostSync hooks template to run the workflow run.
unknown
d14469
val
One problem is that it appears you're calling chmod with the intent of adding a single permission bit. In fact, you are setting all of the permission bits, so the call is trying to clear all of them except the one you want set. Assuming you're on a Unix system, you will presumably want to set the user and group bits as well, including the read and execute bits. You can do the following: st = os.stat(path) old_mode = st.st_mode new_mode = old_mode | stat.S_IWOTH os.chmod(path, new_mode) Hopefully that will help you.
unknown
d14470
val
Figured it out - IPyWidgets notebook extension provides nice examples of how to do this: https://github.com/ipython/ipywidgets On the JS side: var comm_manager=Jupyter.notebook.kernel.comm_manager var handle_msg=function(msg){ console.log('got msg'); console.log(msg) } comm_manager.register_target('myTarget', function(comm,msg){ console.log('opened comm'); console.log(msg); // register callback comm.on_msg(handle_msg) }) Then in Python, from ipykernel.comm import Comm c=Comm(target_name='myTarget',data={}) c.send('hello') The response in the browser console: opened comm VM4511:3 Object {parent_header: Object, msg_type: "comm_open", msg_id: "331ba915-0b45-4421-b869-7d9794d72113", content: Object, header: Object…} VM4464:2 got msg VM4464:2 Object {parent_header: Object, msg_type: "comm_msg", msg_id: "9fdc83c8-49c5-4629-aa43-7ddf92cb4f5e", content: Object, header: Object…}
unknown
d14471
val
Since your subqueries share same FROM and JOIN clauses, simplify to a compact WHERE clause: SELECT i.ip, i.character_name, u.hwid, u.daysToUse, i.locale FROM users u INNER JOIN ips i ON i.hwid = u.hwid WHERE (i.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND u.daysToUse = 3) OR (i.ip = '219.100.37.236' AND u.daysToUse = 3) ORDER BY i.last_time A: Solved it myself.. turns out it is very simple to do this, I just had the query done in backwards order I flipped the order and bam it works as expected. The locale problem was hard.. I couldn't detect which locale is currently used, so I relayed on using ips.lasttime which shows which IP or HWID was used last, and being used last its obviously the locale I want to check Final result SELECT ips.ip, ips.character_name, users.hwid, users.daysToUse, ips.locale FROM users INNER JOIN ips ON ips.hwid = users.hwid WHERE ips.ip IN ( SELECT ips.ip FROM users INNER JOIN ips ON ips.hwid = users.hwid WHERE (ips.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND users.daysToUse = 3) OR (ips.ip = '219.100.37.236' AND users.daysToUse = 3) ) AND ips.locale = ( SELECT ips.locale FROM users INNER JOIN ips ON ips.hwid = users.hwid WHERE (ips.hwid = '1502e3c3-b49c-4907-92fd-2ffac2d50ace' AND users.daysToUse = 3) OR (ips.ip = '219.100.37.236' AND users.daysToUse = 3) ORDER BY ips.last_time ASC );
unknown
d14472
val
The way that templates work is that the components aren't instantiated until they are needed. In this case you are asking for the state of a form before the form is added to the component tree. In terms of what you could do I suggest following Gunter's answer in the comments: I'd use a shared service that you provide in the component that contains above markup and add a component or directive to the that injects that service and communicates from the template with the parent using that service. The parent that provides the service needs also to inject it so that both communication ends have a reference to the same service instance. The service can use a stream to allow one (or both) party to emit events and the other to subscribe to them.
unknown
d14473
val
You're inserting the div under elements that are floating. You need to add clear: both to your #status CSS rules: #status { margin: auto; width: 50%; border: 2px solid red; background: white; height: 40%; /* or 40px, which will look slightly different. Your choice. */ clear: both; } Updated Fiddle
unknown
d14474
val
Yes, this is possible by using the --force-with-lease option. For example: $ git push --force-with-lease=refs/heads/foo origin :refs/heads/foo This is designed for force pushes, but works for deletes as well. The option has many variants and can take explicit values if you like.
unknown
d14475
val
Change if statement to: if($result && mysql_affected_rows() > 0){ Problem with your code is that you are checking if the $result is true, while $result is just an identifier of mysql_query() results. You should check also how much rows where affected by the query. A: Can you show the rest of the code? I guess you want to make a check if there are any entries older than 90 days, the button is enabled. Do you have some kind of list where all entries are shown, and on each entry there is a delete button? To answer your actual question, you'll need to supply us with more code. A: As michal said you can use the affected rows to actually check if a row got deleted with: if($result && mysql_affected_rows() > 0){ If you still want to disable the button tho you can use SELECT IF( DATEDIFF( CURRENT_DATE( ), date ) > 90, 1, 0 ) FROM client_post WHERE id = $id This will return true or false depending on the entry age. Depending on that you can show the button or not. Also, take a look at PDO much better. MySQL api is deprecated.
unknown
d14476
val
This workaround may work for your case. "Although the OAuth 2.0 client credentials grant flow is not currently directly supported by the Azure AD B2C authentication service, you can set up client credential flow using Azure AD and the Microsoft identity platform /token endpoint for an application in your Azure AD B2C tenant. An Azure AD B2C tenant shares some functionality with Azure AD enterprise tenants. To set up client credential flow, see Azure Active Directory v2.0 and the OAuth 2.0 client credentials flow. A successful authentication results in the receipt of a token formatted so that it can be used by Azure AD as described in Azure AD token reference".
unknown
d14477
val
I found problem cases that MIMS site auto submit form with page onload callback for checking authentication. It is not working with machanize gem. Solution Manually submitting the form two times solves this issue. Example url = 'http://www.mims.com/India/Browse/Alphabet/A?cat=drug' page = agent.get url # here checking authentication if success then redirecting to destination p page page.form.submit agent.page.form.submit
unknown
d14478
val
Ok, I found the answer myself. Surprisingly, all the guides I found around explain how to do this configuration via web admin interface or via jboss-cli, but no one in the Jboss community seem to bother explaining how to manually edit the standalone.xml to do the job. This is a working example (basically I just deleted the entire Oracle driver definition section and replaced the driver name in the datasource definition with the name of the runtime name of the deployed jar file): <datasource jta="false" jndi-name="java:/jdbc/fooDS" pool-name="foo-ds" use-ccm="false"> <connection-url>jdbc:oracle:thin:@1.2.3.4:1527/SOMEDB.foo</connection-url> <driver-class>oracle.jdbc.OracleDriver</driver-class> <driver>ojdbc6.jar</driver> [...] other datasource stuff here </datasource> # DELETE FROM HERE... <driver name="oracle" module="oracle.jdbc"> <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class> <datasource-class>oracle.jdbc.OracleDriver</datasource-class> </driver> # ...TO HERE That's all. A: Probably you have to mention in this way... <subsystem xmlns="urn:jboss:domain:datasources:1.1"> <datasources> <datasource jndi-name="java:jboss/XXX" pool-name="XXX" enabled="true" use-java-context="true"> <connection-url>jdbc:oracle:thin:@SID:PORT:DBNAME</connection-url> <driver>oracle</driver> <security> <user-name>user</user-name> <password>password</password> </security> </datasource> <drivers> <driver name="oracle" module="com.oracle"> <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class> <datasource-class>oracle.jdbc.OracleDriver</datasource-class> </driver> </drivers> </datasources> </subsystem> A: * *Create directories like x1/x2/main *Create module.xml file under main directory *Keep ojdbc6-11.1.1.3.0.jar in main directory level In Module.xml <module xmlns="urn:jboss:module:1.1" name="x1.x2"> <properties> <property name="jboss.api" value="unsupported"/> </properties> <resources> <resource-root path="ojdbc6-11.1.1.3.0.jar"/> </resources> <dependencies> <module name="javax.api"/> <module name="javax.transaction.api"/> <module name="javax.servlet.api" optional="true"/> </dependencies> In domain.xml <datasource jndi-name="java:/TestName" pool-name="TestName" enabled="true" use-java-context="true"> <connection-url>jdbc:oracle:thin:@ldap://xxxxx:3000/UKXXX,cn=OracleContext,dc=dcm,dc=XXXX</connection-url> <driver>dps</driver> <security> <user-name>XXXXX</user-name> <password>*****</password> </security> </datasource> <drivers> <driver name="dps" module="x1.x2"> <xa-datasource-class>oracle.jdbc.driver.OracleDriver</xa-datasource-class> </driver> </driver> </drivers> Try to keep the correct ojdbc jar, some versions won't work :)
unknown
d14479
val
Per Ashok: Add RUN chmod -R 775 above the CMD command in your dockerfile This resolved it when applied the folders and the uwsgi.
unknown
d14480
val
This should work: Process process = new ProcessBuilder("rm","-rf","/home/tester/folder").start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String out; while ((out = br.readLine()) != null) { System.out.println(out); }
unknown
d14481
val
So, weirdly enough, the reason I was seeing this was totally unrelated to anything else I thought I was seeing. I had added this line to config/initializers/assets.rb Rails.application.config.assets.prefix = '' because on my production app I am using a cdn and its mapped to http://assets.mydomain.com and I didn't want it to resolve to http://assets.mydomain.com/assets/myasset.js Unfortunately on production it looks like it was causing this issue, weirdly enough.
unknown
d14482
val
You can do this with a flat map const arr = [{"name":"audio","options":[{"name":"true","value":"T"},{"name":"false","value":"F"},{"name":"yes","value":"Y"}]},{"name":"video","options":[{"name":"true","value":"T"},{"name":"false","value":"F"},{"name":"yes","value":"Y"}]},{"name":"call","options":[{"name":"true","value":"T"},{"name":"false","value":"F"},{"name":"yes","value":"Y"}]}] const res = arr.flatMap(({ options, ...props }) => options.map(options => ({ ...props, options }))) console.log(res) .as-console-wrapper { max-height: 100% !important; } This creates an array of arrays for each options in the collection and then flattens it to produce a one-dimensional array. The spread syntax lets you merge any top-level properties (like name) into each option result A: You need a nested loop over the options array to split them into separate array elements. var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}] const res = []; arr.forEach(({ name, options }) => options.forEach(option => res.push({ name, options: option }))); console.log(res) A: Use Array.map to create the converted elements, then use Array.flat to flatten the 2D array. var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}] let output = arr.map(it => { return it.options.map(option => { return {name:it.name,options:option} }) }).flat() console.log(output); Edit: As @mplungjan mentioned this is identical to using Array.flatMap. var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}] let output = arr.flatMap(it => { return it.options.map(option => { return {name:it.name,options:option} }) }); console.log(output); A: var arr = [{name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}] const newArr = arr.reduce((acc, cur) => { acc = [...acc, ...cur.options.map(option => { return { ...cur, options: option, } })]; return acc; }, []); A: You can use map function to resolve your query. var arr = [ {name: "audio", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "video", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}, {name: "call", options:[{name:'true', value: 'T'},{name:'false', value: 'F'},{name:'yes', value: 'Y'}]}] let result = []; arr.map(a => { a.options.map(o => { result.push({ name: a.name, options: { ...o } }); }); }); console.log(result)
unknown
d14483
val
You can add a beforeValidation callback to send the value without spaces, take a look here: Jquery Validator before Validation callback, it seems to be what you're looking for A: a very smiple solution is : replace the type of the phone input as the following : <input id="phone" type="number" maxlength="10" size="2" max="99" style="width:36px;" required /> and you would never have issues with spaces and stuff, just used that in my code ! enjoy
unknown
d14484
val
This is a wonderful use case of the intnx() function. intnx() will be your best friend when it comes to aligning dates. In the traditional calendar, the year starts on 01JAN. In your calendar, the year starts in 01JUN. The difference between these two dates is exactly 6 months. We want to shift our date so that the year starts on 01JUN. This will allow you to take the year part of the date and determine what year you are on in the new calendar. data want; format current_cal_year current_new_year year4. ; current_cal_year = intnx('year', '01JUN2018'd, 0, 'B'); current_new_year = intnx('year.6', '01JUN2018'd, 1, 'B'); run; Note that we shifted current_new_year by one year. To illustrate why, let's see what happens if we don't shift it by one year. data want; format current_cal_year current_new_year year4. ; current_cal_year = intnx('year', '01JUN2018'd, 0, 'B'); current_new_year = intnx('year.6', '01JUN2018'd, 0, 'B'); run; current_new_year shows 2018, but we really are in 2019. For 5 months out of the year, this value will be correct. From June-December, the year value will be incorrect. By shifting it one year, we will always have the correct year associated with this date value. Look at it with different months of the year and you will see that the year part remains correct throughout time. data want; format cal_month date9. cal_year new_year year4. ; do i = 0 to 24; cal_month = intnx('month', '01JAN2016'd, i, 'B'); cal_year = intnx('year', cal_month, i, 'B'); new_year = intnx('year.6', cal_month, i+1, 'B'); year_not_same = (year(cal_year) NE year(new_year) ); output; end; drop i; run; A: Regarding input Payment2018-Payment2021; there is no automatic assumption of yearness or calendaring. The numbers 2018 and 2021 are the bounds for a numbered range list In a numbered range list, you can begin with any number and end with any number as long as you do not violate the rules for user-supplied names and the numbers are consecutive. The meaning of the numbers 2018 to 2021 is up to the programmer. You state the variables correspond to the June payment in the numbered year. You would have to iterate a date using 9-month steps and increment a counter based on the year in which the date falls. Sample code Dynamically adapts to the variable names that are arrayed. data _null_; array payments payment2018-payment2021; array Pay_Incs pay_inc2018-pay_inc2021; * must be same range numbers as payments; * obtain variable names of first and last element in the payments array; lower_varname = vname(payments(1)); upper_varname = vname(payments(dim(payments))); * determine position of the range name numbers in those variable names; lower_year_position = prxmatch('/\d+\s*$/', lower_varname); upper_year_position = prxmatch('/\d+\s*$/', upper_varname); * extract range name numbers from the variable names; lower_year = input(substr(lower_varname,lower_year_position),12.); upper_year = input(substr(upper_varname,upper_year_position),12.); * prepare iteration of a date over the years that should be the name range numbers; date = mdy(06,01,lower_year); * june 1 of year corresponding to first variable in array; format date yymmdd10.; do _n_ = 1 by 1; * repurpose _n_ for an infinite do loop with interior leave; * increment by 9-months; date = intnx('month', date, 9); year = year(date); if year > upper_year then leave; * increment counter for year in which iterating date falls within; Pay_Incs( year - lower_year + 1 ) + 1; end; put Pay_Incs(*)=; run; Increment counter notes There is a lot to unpack in this statement Pay_Incs( year - lower_year + 1 ) + 1; * *+ 1 at the end of the statement increments the addressed array element by 1, and is the syntax for the SUM Statement variable + expression The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here: retain variable 0; variable=sum(variable,expression); *year - lower_year + 1 computes the array base-1 index, 1..N, that addresses the corresponding variable in the named range list pay_inc<lower_year>-pay_inc<upper_year> *Pay_Incs( <computed index> ) selects the variable of the SUM statement
unknown
d14485
val
The variables that declares widgets are needs to be declared separately, otherwise the last variable will overwrite the current widget and when it will called, it will show only last widget value. This can be fixed using enumerating the list. The enumeration technique indexes objects as well as selects every object from a list at a same time. Also it is required to declare every text variable for Entry widget is declared separately.For that every variable will be appended to list and then that list will enumerated when the variables are called. Here's a Solution, import tkinter from tkinter import * root = Tk() entries_list = [] path_list = [] button_list = [] label_list = [] var_list = [] x = 5 #int variable that define how many times will loop run for var in range(0,x): #always define a variable type before adding it to Entry Box se = StringVar() var_list.append(se) def inputt(): # use enumerate for indexing the list for p,q in enumerate(var_list): l = Label(root,text="Device "+str(p+1)+":") l.grid(row=p,column=0) label_list.append(l) e = Entry(root, textvariable = var_list[p], width=25) e.grid(row=p, column=1) b1 = Button(root,text="Next",command=lambda:load()) b1.grid(row=p+2,column=0) def load(): # Entered values will loaded to entries_list when next button is pressed for u,v in enumerate(var_list): entries_list.append(var_list[u].get()) for j,k in enumerate(entries_list): b3=Button(root, text=k) b3.grid(row= j + x + 2,column=0,columnspan = 2,sticky = EW) button_list.append(b3) inputt() root.mainloop()
unknown
d14486
val
You've got one of the more helpful error messages there - APICategoryController does not have a default constructor, ie: a parameterless constructor. You either need to use some kind of Dependency Injector for your code to know how to instantiate a concrete class for ICatRepository, or provide a default constructor. eg: //a default constructor instantiating a concrete type. Simple, but no good for testing etc. public APICategoryController() { ICatRepository repository = new ConcreteRepository; this.repository = repository; } A: you need to add default constructor. you should add this to APICategoryController (this is default constructor) public APICategoryController() { }
unknown
d14487
val
It seems that some yum commands are case sensitive (atleast install and groupinstall), so the correct command is $ yum groupinstall "X Window System" "KDE Desktop"
unknown
d14488
val
I ran into the same problem. I normally just use one xaml each for the basic darks, the basic lights, and then one for each colour accent (blue, red etc). The accent is slightly lookthrough which makes it darker when then darker theme is selected with a darker background. When creating a theme with a secondary accent colour to have more contrast in the app (for example gray when light theme is selected, accent colour when dark theme), I needed to construct a brush out of two colours as otherwise I would have to create a dark and light theme for each colour. Here is what I use: <DrawingBrush x:Key="SecondaryAccentColorBrush" Viewport="0,0,1,1" TileMode="Tile"> <DrawingBrush.Drawing> <DrawingGroup> <GeometryDrawing> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,0,1,1" /> </GeometryDrawing.Geometry> <GeometryDrawing.Brush> <SolidColorBrush Color="{DynamicResource AccentColor}"/> </GeometryDrawing.Brush> </GeometryDrawing> <GeometryDrawing> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,0,1,1" /> </GeometryDrawing.Geometry> <GeometryDrawing.Brush> <SolidColorBrush Color="{DynamicResource Gray10}"/> </GeometryDrawing.Brush> </GeometryDrawing> </DrawingGroup> </DrawingBrush.Drawing> </DrawingBrush> When the theme is switched, the alpha of "Gray10" switches between 00 and FF, thus the brush shows either gray or the accent colour. A: Unfortunately, custom brushes are not supported in WPF (the brush types are marked 'internal' and cannot be inherited from), so creating a brush that is a mixture of two brushes that can be used from XAML like a normal SolidColorBrush is not possible. As a workaround, you could use a MarkupExtension to simulate the behaviour of a custom brush, which allows you to use XAML syntax and provide a custom value, which allows us to use the built-in SolidColorBrush (no custom brush necessary) set to the value you get when mixing two colors: /// <summary> /// Markup extension to mix two SolidColorBrushes together to produce a new SolidColorBrush. /// </summary> [MarkupExtensionReturnType(typeof(SolidColorBrush))] public class MixedColorBrush : MarkupExtension, INotifyPropertyChanged { /// <summary> /// The foreground mix color; defaults to white. /// If not changed, the result will always be white. /// </summary> private SolidColorBrush foreground = Brushes.White; /// <summary> /// The background mix color; defaults to black. /// If not set, the result will be the foreground color. /// </summary> private SolidColorBrush background = Brushes.Black; /// <summary> /// PropertyChanged event for WPF binding. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Gets or sets the foreground mix color. /// </summary> public SolidColorBrush Foreground { get { return this.foreground; } set { this.foreground = value; this.NotifyPropertyChanged("Foreground"); } } /// <summary> /// Gets or sets the background mix color. /// </summary> public SolidColorBrush Background { get { return this.background; } set { this.background = value; this.NotifyPropertyChanged("Background"); } } /// <summary> /// Returns a SolidColorBrush that is set as the value of the /// target property for this markup extension. /// </summary> /// <param name="serviceProvider">Object that can provide services for the markup extension.</param> /// <returns>The object value to set on the property where the extension is applied.</returns> public override object ProvideValue(IServiceProvider serviceProvider) { if (this.foreground != null && this.background != null) { // Create a new brush as a composite of the old ones // This does simple non-perceptual additive color, e.g // blue + red = magenta, but you can swap in a different // algorithm to do subtractive color (red + yellow = orange) return new SolidColorBrush(this.foreground.Color + this.background.Color); } // If either of the brushes was set to null, return an empty (white) brush. return new SolidColorBrush(); } /// <summary> /// Raise the property changed event. /// </summary> /// <param name="propertyName">Name of the property which has changed.</param> protected void NotifyPropertyChanged(string propertyName) { if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } Which can then be used from XAML as you would a normal brush: <Grid> <Grid.Background> <local:MixedColorBrush Foreground="Blue" Background="Red"/> </Grid.Background> </Grid> Or by using the markup extension syntax: <Grid Background="{local:MixedColorBrush Foreground=Blue, Background=Red}"> The downside to this approach is that you cannot use DynamicResource or StaticResource references to bind the values to other resources in your application. MarkupExtension is not a DependencyObject, and resource binding only works on DependencyObjects; the built-in Brushes are DependencyObjects, which is why binding works with traditional brushes. A: Get the colors from the foreground and background brushes, mix them, and create a new brush from the resulting color. Example in C#: Color foreground = foregroundBrush.Color; Color background = backgroundBrush.Color; int opacity = 25; int r = (opacity * (foreground.R - background.R) / 100) + background.R; int g = (opacity * (foreground.G - background.G) / 100) + background.G; int b = (opacity * (foreground.B - background.B) / 100) + background.B; SolidColorBrush mixedBrush = new SolidColorBrush(Color.FromArgb(r, g, b)); A: One easy way to do it (but probably not optimized), create a LinearGradientBrush of the two colors in repeat mode with Endpoint equals to start point: <LinearGradientBrush SpreadMethod="Repeat" EndPoint="0,0"> <GradientStop Color="Red" Offset="0" /> <GradientStop Color="Yellow" Offset="1" /> </LinearGradientBrush> This one gives you an Orange brush.
unknown
d14489
val
You will have to get the remote data via service and assign the data to a variable, in your example it will be assigned to allSectors. Then it's usual business, running the filter on allSectors, if allSectors is an array of objects, than you have to specify on which property you want to run the filter. In my demo, I am doing it for sector.name. You can use displayWith to control what value to show in input field. HTML: <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn"> <md-option *ngFor="let sector of filteredSectors | async" [value]="sector"> {{ sector.name }} </md-option> </md-autocomplete> TS: export class AutocompleteOverviewExample implements OnInit{ stateCtrl: FormControl; filteredSectors: any; allSectors; constructor(private dataService: DataService) { this.stateCtrl = new FormControl(); } ngOnInit(){ this.dataService.fetchData() .subscribe( (data) => { this.allSectors = data.customers; this.filteredSectors = this.stateCtrl.valueChanges .startWith(null) .map(val => val ? this.filter(val) : this.allSectors.slice()); } ); } filter(name) { return this.allSectors.filter(sector => new RegExp(`^${name}`, 'gi').test(sector.name)); } displayFn(sector) { return sector ? sector.name : sector; } } Here's the Plunker.
unknown
d14490
val
Try like this $(document).ready(function(){ $("#points").each(function(){ if((this).val()>0.5) (this).css("background-color","red"); }); }) Considered that your all points must have the id "points" and their values must be their respective heights(0.1,0.2,....like that) A: "This feature is planned for Highcharts 3.0. We wrote up a temporary hack, which is limited to SVG browsers. That means that it won’t work in IE6, 7 and 8. See http://jsfiddle.net/highcharts/PMyHQ/" - @orstein Hønsi (Admin, Highcharts JS) - Nov 14, 2011 Source: http://highcharts.uservoice.com/forums/55896-general/suggestions/787281-threshold-option-for-colors A: You can very well create a utility method that converts your series.data from [[x,y],...] into [{ x:xVal,y:yVal,color:color,...}...] This function could look something like this function groupDataByValue(data, threshold, aboveColor, belowColor) { var newData = []; $.each(data, function() { var dataPoint = { x: this[0], y: this[1], marker: {} }; var color; if (dataPoint.y > threshold) { color = aboveColor; } else { color = belowColor; } dataPoint.color = color; dataPoint.marker.fillColor = color; newData.push(dataPoint); }); return newData; } Before setting the series.data property pass it to this method and set the result value as the series.data Coloring points based on values @ jsFiddle
unknown
d14491
val
* *validate *I see no difference in F 3.6.10 on Mac *fix at least this: Warning: Expected end of value but found ','. Error in parsing value for 'padding'. Declaration dropped. Source File: /guggs/css.css Line: 39 td { font: 9pt verdana; color:#665544; padding: 0px, 0px, 0px, 5px; } A: Issue resolved. Nothing do with the Javascript ! FireFox and Opera were tripping due to earlier PHP code intended to prevent users coming in through anything other than the index page. Works OK when the site isn't cloaked so I'm not sure exactly what the problem is, but for the moment I've removed the code, which isn't anything like vital. Thanks for your time, people !
unknown
d14492
val
It's not clear how you setup your PATH variable. Or how the scripts are not "working". Did you chmod +x them to make them executable? Any logs output that comes from them at all? The start-all script is available in the sbin directory of where you downloaded Hadoop, so just /path/to/sbin/start-all.sh is all you really need. Yes, the namenode needs formatted on a fresh cluster. Using the official Apache Guide is the most up-to-date source and works fine for most. Otherwise, I would suggest you learn about Apache Amabri, which can automate your installation. Or just use a Sandbox provided by Cloudera, or use many of the Docker containers that already exist for Hadoop if you don't care about fully "installing" it.
unknown
d14493
val
Use the following code as a global listener on ur page to check if the sign-in is successful: firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. var isAnonymous = user.isAnonymous; var unique_id = user.uid; } else { // User is signed out. // ... } }); This snippet has been taken from the Firebase Anonymous Auth link: Click Here to open link. A: For some reason I was trying to set up a binding to sync my app with Firebase, which I just realized I don't need at all! (I just need to push the data at the end of the poll). Of course as soon as removed that requirement it was as simple as: firebase.database().ref().push().set(myData); When using the push() method, Firebase automatically generates a unique key which is all I need...
unknown
d14494
val
One way you could do this is by subclassing AVPlayerViewController. AVPlayerViewController has an AVPlayer property named player. A subclass of AVPlayerViewController might look something like this: import UIKit import AVKit class MyPlayerViewController: AVPlayerViewController { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let path = NSBundle.mainBundle().pathForResource("myVideo", ofType:"mov")! let videoURL = NSURL(fileURLWithPath: path) player = AVPlayer(URL: videoURL) } } This implementation would show the default playback controls and would work out of the box with the Siri remote. Here is the code to do this via a button press using prepareForSegue: import UIKit import AVFoundation import AVKit let playerViewControllerSegue = "play"; class MyViewController: UIViewController { @IBAction func playMovie(sender: UIButton) { self.performSegueWithIdentifier(playerViewControllerSegue, sender: self); } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == playerViewControllerSegue){ let path = NSBundle.mainBundle().pathForResource("7second", ofType:"mp4")! let videoURL = NSURL(fileURLWithPath: path) let player = AVPlayer(URL: videoURL) let playerViewController = segue.destinationViewController as! AVPlayerViewController playerViewController.player = player playerViewController.player?.play() } } }
unknown
d14495
val
If I have understood correct then your main concern is: your stored procedure empties the table and then fills it up and since it takes time, your application have no data show. In that case, you can have a secondary/auxiliary clone table; say tblOpenTicketsPerDay_clone and have your stored procedure fill that table instead like insert into tblOpenTicketsPerDay_clone select convert(varchar(20),datename(dw,@day)) day_name, count(*) Open_Tickets from That way your application will always have data to display since main table has the data. Once, the clone table is done filling up then transfer the same data to main table saying delete from tblOpenTicketsPerDay; insert into tblOpenTicketsPerDay select * from tblOpenTicketsPerDay_clone; A: No, but the problem is not caching, it isa totally bad approach to generate the data. Generate new data into a temporary table, then MERGE The results (using the merge keyword) into the original table. No sense in deleting the data first. That is a terrible design approach.
unknown
d14496
val
For a splittable file/data the partitions will be mostly created automatically depending on cores, operation being narrow or wide, file size etc. Partitions can also be controlled programmatically using coalesce and repartition. But for a gzip/un-splittable file there will be just 1 task for a file and it can be as many parallel as many cores available (like you said). For dynamic cluster one option you have is to point your job to a folder/bucket containing large number of gzip files. Say you have 1000 files to process and you have 10 cores then 10 will in parallel. When dynamically your cluster increases to 20 then 20 will run in parallel. This happens automatically and you needn't code for this. The only catch is that you can't scale fewer files than the available cores. This is a known deficiency of un-splittable files. The other option would be to define the cluster size for the job based the number and size of files available. You can find an emparical formula based on the historical run time. Say you have 5 large files and 10 small files (half size of large) then you may assign 20 cores (10 + 2*5) to efficiently use the cluster resources. A: A standard gzip file is not splittable, so Spark will handle the gzip file with just a single core, a single task, no matter what your settings are [As of Spark 2.4.5/3.0]. Hopefully the world will move to bzip2 or other splittable compression techniques when creating large files. If you directly write the data out to Parquet, you will end up with a single, splittable parquet file. This will be written out by a single core. If stuck with the default gzip codec, would be better to re-partition after the read, and write out multiple parquet files. from pyspark.sql.types import StructType, StructField, StringType, DoubleType, IntegerType schema = StructType([ StructField("a",IntegerType(),True), StructField("b",DoubleType(),True), StructField("c",DoubleType(),True)]) input_path = "s3a://mybucket/2G_large_csv_gzipped/onebillionrows.csv.gz" spark.conf.set('spark.sql.files.maxPartitionBytes', 1000 * (1024 ** 2)) df_two = spark.read.format("csv").schema(schema).load(input_path) df_two.repartition(32).write.format("parquet").mode("overwrite").save("dbfs:/tmp/spark_gunzip_default_remove_me") I very recently found, and initial tests are very promising, a splittable gzip codec. This codec actually reads the file multiple times, and each task scans ahead by some number of bytes (w/o decompressing) then starts the decompression. The benefits of this pay off when it comes time to write the dataframe out as a parquet file. You will end up with multiple files, all written in parallel, for greater throughput and shorter wall clock time (your CPU hours will be higher). Reference: https://github.com/nielsbasjes/splittablegzip/blob/master/README-Spark.md My test case: from pyspark.sql.types import StructType, StructField, StringType, DoubleType, IntegerType schema = StructType([ StructField("a",IntegerType(),True), StructField("b",DoubleType(),True), StructField("c",DoubleType(),True)]) input_path = "s3a://mybucket/2G_large_csv_gzipped/onebillionrows.csv.gz" spark.conf.set('spark.sql.files.maxPartitionBytes', 1000 * (1024 ** 2)) df_gz_codec = (spark.read .option('io.compression.codecs', 'nl.basjes.hadoop.io.compress.SplittableGzipCodec') .schema(schema) .csv(input_path) ) df_gz_codec.write.format("parquet").save("dbfs:/tmp/gunzip_to_parquet_remove_me")
unknown
d14497
val
I'd try: SELECT ID, CASE WHEN B = 0 THEN 0 ELSE A/B END AS Ratio FROM ( SELECT ID, SUM(CASE WHEN Name LIKE 'A%' THEN 1 ELSE 0 END) AS A, SUM(CASE WHEN Name LIKE 'B%' THEN 1 ELSE 0 END) AS B FROM my_table GROUP BY ID ) AS grouped; The inner SELECT gets the group IDs, and for every ID, the number of items beginning with A and those beginning with B. The outer SELECT (you can omit it if you're sure that there'll always be at least one B-row) checks that the ratio makes sense before attempting to calculate it. Or else: SELECT ID, COALESCE(SUM(CASE WHEN Name LIKE 'A%' THEN 1 ELSE 0 END) / SUM(CASE WHEN Name LIKE 'B%' THEN 1 ELSE 0 END), 0) FROM my_table GROUP BY ID; This takes advantage of the fact that, if the number of B-rows is zero, the division will yield NULL. The COALESCE transforms that NULL in a 0. A: This will do it: SELECT id, SUM(IF(name LIKE 'A%',1,0))/SUM(IF(name like 'B%',1,0)) FROM `table` GROUP BY ID
unknown
d14498
val
You have to wrap your background image container in another div. Check the HTML, CSS snippets along with screenshot. <body> <div class="header"> <div class="parallax-2"> <div class="logo fade-in-3"> <img src="logo.png" alt="BeldrProductions" width="500" /> </div> </div> <!-- The nav-items go here. but i left them out to save space--> </div> </body> <style> .header { height: 300px; width: inherit; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px; } .parallax-2 { height: inherit; width: inherit; background-image: url("nav-bg.png"); background-repeat: no-repeat; background-size: 100% 100%; } </style> A: Thanks to everyone that has helped me. But i just used it without a image Thanks, Bye! if there still is anyone who has a solution. Please leave it below. I would love to see it.
unknown
d14499
val
z").Find(What:="*", _ After:=.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row Else MsgBox "Insufficient rows" End If If Range("A1").Value = "April" Then .Unprotect Password:="MyPassword" .Cells.Locked = False .Range("A2:Z" & lastrow).Locked = True A: I'm not so sure what you were trying to accomplish with the existing code, but based purely on what you explained, I think this should do the trick : Dim DestSh As Worksheet Dim lastrow As Long Dim i As Integer Set DestSh = Sheets("Consultant & Teacher") With DestSh 'finds the last row with data on A column lastrow = Range("A65536").End(xlUp).Row 'parse all rows For i = 2 To lastrow 'if your conditions are met If Month(.Cells(i, 16)) > Month(.Cells(1, 1)) Then .Range("A" & i).EntireRow.Cells.Locked = True 'lock the row End If Next i End With
unknown
d14500
val
Theory Well, I found a lot of info after digging on the Internet and one and a half of consultations. There is an architectural pattern named API Gateway, which describes an entry point in a cluster, and this is just what Kubernetes Ingress does, and what I imagined in my question. In a general case, it is proxy server, which is the only entry point to the cluster microservices, and it may perform caching, DDoS protection, it may support different API protocols, manipulate URIs, manage API throttling, monetisation, and perform the authentication I need. Therefore, there is no authentication during microservices communication inside the cluster, because all the required arguments, identifiers will be presented in the requests. Implementation In Kubernetes, NginX Ingress is quite popular, it also supports Basic Auth and OAuth2, which is not a perfect solution, but at least something. There are alternative Ingress solutions for Kubernetes: Kong, Ambassador, Traefik, which provide much more features (though Kong is based on NginX too). In the world of Java and Spring the Spring Cloud Gateway exists to solve such problems, which, just like K8s Ingress, allows to describe path tables with YAML, yet it is extendable, allows to easily embed your custom code for any authentication method. Besides, most of cloud platforms provide their own API gateway services with more or less features, including Google Cloud, Red Hat, AWS, Yandex Cloud. However, it seems they lack authentication methods just like opportunity to be extended, though they aren't much relevant in this question. To read You can find more about API Gateway pattern and it's implementations here: * *microservices.io: API Gateway pattern *RedHat: What does an API gateway do? *kubernetes.github.io: NginX Ingress External OAUTH Authentication *learnK8S.io: Kubernetes API Gateway *cloud.spring.io: Spring Cloud Gateway A: With microservices, JWT are preferred way of authentication & authorization. You can use cloud resources like GCP IAM or OKTA. OR you can run Keycloak in your cluster as a microservice. * *User is created in one of these resources. *Once the user has authenticated, a JWT token is returned (to frontend). *Token contains authentication & authorization related info for that user. *This token is again sent from frontend to backend services in each request. *Backend service will check authentication and authorization and respond accordingly. Also token is normally valid for fixed amount of time. So frontend app should refresh the token periodically.
unknown