date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/21 | 655 | 2,219 | <issue_start>username_0: As the title states, I'm having difficulties connecting my Mosquitto MQTT client (written in C) to my Azure IoT-hub. I've managed to connect to many different platforms before (e.g. Amazon EC2, ThingsBoard, TheThings.io, SierraWireless, ...), so I know my client is pretty solid.
The difficulty here is the fact that I need some sort of certificate to be allowed to connect, and I'm not sure what I need to do this.
I have added the following configuration in order to get this working:
```
mosquitto_opts_set(client, MOSQ_OPT_PROTOCOL_VERSION, "MQTT_PROTOCOL_V311");
mosquitto_tls_set(client, "/home/ca-certificates.crt", NULL, NULL, NULL, NULL);
mosquitto_tls_insecure_set(client, 1);
mosquitto_tls_opts_set(client, 0, "tlsv1", NULL);
mosquitto_username_pw_set(client, "hubname.azure-devices.net/deviceName", "SharedAccessSignature=SharedAccessSignature sr=hubname.azure-devices.net%2Fdevices%2FdeviceName&sig=sigValue&se=1553087157");
```
In the code above, "hubname", "deviceName" and "sigValue" are of course replaced with real values in my code.
Can any of you point me to what I'm doing wrong, or what other configuration steps I need to take?<issue_comment>username_1: ```
DECLARE @Value AS NVARCHAR(MAX) = 'customers.name = ''Schmidt'''
,@Replacement AS NVARCHAR(MAX) = 'last_name'
,@SearchString AS NVARCHAR(MAX) = 'name'
SET @Value = REPLACE(@value, @SearchString, @Replacement)
PRINT @Value;
```
Upvotes: 2 <issue_comment>username_2: You should replace `customers.name` for `customers.last_name`.
```
DECLARE @text VARCHAR(200) = 'customers.name = ''Schmidt'''
SELECT
OriginalText = @text,
ReplacedText = REPLACE(@text, 'customers.name', 'customers.last_name')
/*
Result:
OriginalText: customers.name = 'Schmidt'
ReplacedText: customers.last_name = 'Schmidt'
*/
```
In general basis, when replacing strings, the bigger they are the lower the chance of replacing by mistake. If you are sure that the value will always start with `customers.name =` then you should replace that with `customers.last_name =`. If you try to replace simply `name` you might end up replacing it on another occurence of the string.
Upvotes: 2 [selected_answer] |
2018/03/21 | 516 | 1,661 | <issue_start>username_0: I am useing Font Awesome 5. Some icons are not showing in Chrome. For example "fa-facebook-f". When I change the icon class to fa-facebook it works. Is there a way to fix it?
Here is what i see in chrome.
[](https://i.stack.imgur.com/TaBCz.jpg)
```
```<issue_comment>username_1: Have you imported the css, js but also the etf files which describes the font ?
If yes, then try this class name instead of "fab" which is not referenced in the doc
```
```
Upvotes: 1 <issue_comment>username_2: Its working fine...Its maybe you are not linking the correct font-awesome file
```html
```
Upvotes: 2 <issue_comment>username_3: Import this css it will work for all the font awesome icons and also for all the versions of icons it will work.
Upvotes: 4 <issue_comment>username_4: Add this code in your HTML file before body and style tag
```
```
And remember one thing that use class of that type
```
fab fa-linkedin
```
in some site it is given as
```
fa fa-linkedin
```
which is not working so use 'fab' in place of 'fa'
And you can use this icon in your website
for testing purpose you can use this code
```

##### <NAME>
CEO - Founder
*
*
*
*
```
Upvotes: 3 <issue_comment>username_5: You can use "fab" in class instead of "fa"
```
```
This will surely work. Replace "fa" with "fab" or "fas".
Upvotes: 2 <issue_comment>username_6: This class name works fine for linkedin:
```
```
used the below link in index.html under head tag :
```
```
Upvotes: 0 |
2018/03/21 | 414 | 1,633 | <issue_start>username_0: I have a project with angular 5 and bootstrap 4. I'm trying to use the BS4 framework but that requires jquery.
1. Is it ok to use jquery in angular project ?
2. Can we use bootstrap from <https://getbootstrap.com/> with latest jquery.
3. What is the difference with <https://valor-software.com/ngx-bootstrap/#/> and <https://ng-bootstrap.github.io/#/home>
What is the best practice to use bootstrap 4 with angular 5 with no hassle.<issue_comment>username_1: Below are my answers for your 3 questions:
1. Yes, there is no problem if you are using jQuery in your Angular Project.
2. Yes you can use it.
3. I think you should use <https://valor-software.com/ngx-bootstrap/#/> where you don't bother about jQuery and the benefit of using it is only the required module can be imported in any component which will be faster for your application.
Upvotes: 0 <issue_comment>username_2: 1.-In general is a "bad idea" use jquery and Angular
2.-You can use only bootstrap.css
3.-"Google is our friend". Personally I prefer ng-bootstrap (if use bootstrap 3 you must use ngx-bootstrap). In my opinion is more "closely" to Angular, but it's only a opinion
Upvotes: 1 <issue_comment>username_3: 1. I suggest you research that topic as it's not recommended but the real answer is that 'it depends'.
2. Yes.
3. One (ngx-bootstrap) is from commercial company (Valor software) and one is not. They do the same thing but offer different libraries. Compare them yourself and you will see the differences. Neither need jQuery, they 'rebuild' the core bootstrap controls in Angular, styled with the bootstrap CSS.
Upvotes: 0 |
2018/03/21 | 1,716 | 5,728 | <issue_start>username_0: For a WooCommerce webshop we send out a lot of payment links through email. Before getting to the payment page customers are obligated to login first. We would like the customer to be able to complete payment without logging in as often they don't know their password because of different company departments.
I found this code but this only lets the administrator pay without logging in:
```
function your_custom_function_name($allcaps, $caps, $args)
{
if (isset($caps[0])) {
switch ($caps[0]) {
case 'pay_for_order':
$user_id = $args[1];
$order_id = isset($args[2]) ? $args[2] : null;
// When no order ID, we assume it's a new order
// and thus, customer can pay for it
if (!$order_id) {
$allcaps['pay_for_order'] = true;
break;
}
$user = get_userdata($user_id);
if (in_array('administrator', (array)$user->roles)) {
$allcaps['pay_for_order'] = true;
}
$order = wc_get_order($order_id);
if ($order && ($user_id == $order->get_user_id() || !$order - > get_user_id())) {
$allcaps['pay_for_order'] = true;
}
break;
}
}
return $allcaps;
}
add_filter('user_has_cap', 'your_custom_function_name', 10, 3);
```<issue_comment>username_1: here is working function with all users just test it :
```
function your_custom_function_name( $allcaps, $caps, $args ) {
if ( isset( $caps[0] ) ) {
switch ( $caps[0] ) {
case 'pay_for_order' :
$order_id = isset( $args[2] ) ? $args[2] : null;
$order = wc_get_order( $order_id );
$user = $order->get_user();
$user_id = $user->ID;
// When no order ID, we assume it's a new order
// and thus, customer can pay for it
if ( ! $order_id ) {
$allcaps['pay_for_order'] = true;
break;
}
$order = wc_get_order( $order_id );
if ( $order && ( $user_id == $order->get_user_id() || ! $order->get_user_id() ) ) {
$allcaps['pay_for_order'] = true;
}
break;
}
}
return $allcaps;
}
add_filter( 'user_has_cap', 'your_custom_function_name', 10, 3 );
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I have created a different solution for this problem, allowing anyone who has the WooCommerce-generated Payment URL (which includes the Order Key) to complete the payment for that order. (So we retain some of the security/protection, rather than just allowing anyone to pay for anything and see any order.)
```
function allow_payment_without_login( $allcaps, $caps, $args ) {
// Check we are looking at the WooCommerce Pay For Order Page
if ( !isset( $caps[0] ) || $caps[0] != 'pay_for_order' )
return $allcaps;
// Check that a Key is provided
if ( !isset( $_GET['key'] ) )
return $allcaps;
// Find the Related Order
$order = wc_get_order( $args[2] );
if( !$order )
return $allcaps; # Invalid Order
// Get the Order Key from the WooCommerce Order
$order_key = $order->get_order_key();
// Get the Order Key from the URL Query String
$order_key_check = $_GET['key'];
// Set the Permission to TRUE if the Order Keys Match
$allcaps['pay_for_order'] = ( $order_key == $order_key_check );
return $allcaps;
}
add_filter( 'user_has_cap', 'allow_payment_without_login', 10, 3 );
```
Using this function, a user visiting a URL which has an Order Number, and the associated Order Key, will be able to complete the payment, but if the Order Key is not valid, or not present, then it will fail.
Examples:
* *your.domain/checkout/order-pay/987/?pay\_for\_order=true&key=wc\_order\_5c4155dd4462c*
**PASS** if "wc\_order\_5c4155dd4462c" is Order Key for Order #987
* *your.domain/checkout/order-pay/987/?pay\_for\_order=true*
**FAIL** as No Key Parameter Present
* *your.domain/checkout/order-pay/987/*
**FAIL** as No Key Parameter Present
Upvotes: 2 <issue_comment>username_3: **Here's my solution that also works with WooCommerce Subscriptions.** Subscription renewals also require the user to be logged in. My function gets the user from the order id passed in the payment link, then checks if the id and order key match and limits the login to subscribers and customers for security reasons. The user is logged in via wp\_set\_auth\_cookie() before WooCommerce checks the login status.
Paste this code in your plugin or your theme's functions.php file.
```
/**
* Pay for Order or Subscription if Logged Out - WooCommerce Checkout
*/
function glunz_log_in_user_from_payment_link(){
global $wp;
if ( isset( $_GET['pay_for_order'] ) && isset( $_GET['key'] ) && isset( $wp->query_vars['order-pay'] ) && ! is_user_logged_in() ) {
$order_key = $_GET['key'];
$order_id = isset( $wp->query_vars['order-pay'] ) ? $wp->query_vars['order-pay'] : absint( $_GET['order_id'] );
$order = wc_get_order( $order_id );
$user_id = $order->get_user_id();
$user = get_user_by('id', $user_id);
// Check if order key corresponds with order and the status of the payment is pending or failed
if ( wcs_get_objects_property( $order, 'order_key' ) === $order_key && $order->has_status( array( 'pending', 'failed' ) ) ) {
// For security reasons we want to limit this function to customers and subscribers
if ( in_array( 'customer', $user->roles ) || in_array( 'subscriber', $user->roles ) ) {
// Log the user in
wp_set_auth_cookie($user_id);
wp_set_current_user($user_id);
}
}
}
}
add_action( 'send_headers', 'glunz_log_in_user_from_payment_link', 0 );
```
Upvotes: 0 |
2018/03/21 | 905 | 3,010 | <issue_start>username_0: I need to exclude NULL values from an array with a foreach but it doesn't work actually:
```
foreach ($node->field_fichier_joint as $key => $fichier) {
//Ne pas afficher les champs vides du tableau
if ($fichier !== NULL):
print 'debug de $fichier'.$fichier;
print '- '.$node->field\_fichier\_joint[$key]['view'].'
';
endif;
}
```
This produce empty LI's:
```
* 
[Fichier test pdf](sites/all/media/contenu_international/cal_2sec_20112012.pdf "cal_2sec_20112012.pdf")
* 
[Fichier test pdf 2](/sites/all/media/contenu_international/bac_tehno_stg.pdf "bac_tehno_stg.pdf")
*
*
*
* [Un site internet](https://info.erasmusplus.fr/)
```
What is missing ?
Thanks
EDIt:
`var_dump($fichier);` give for one : `array(1) { ["view"]=> string(0) "" }`
so I need to filter on empty value, not NULL values. Apologize.
EDIT2: Final working code
```
foreach ($node->field_fichier_joint as $key => $fichier) {
//Ne pas afficher les champs vides du tableau
if (!empty($fichier['view'])):
// print 'debug de $fichier'.$fichier;
print '- '.$node->field\_fichier\_joint[$key]['view'].'
';
endif;
}
```<issue_comment>username_1: Just [filter](http://php.net/array_filter) `NULL` values:
```
$values = array_filter($node->field_fichier_joint, 'is_null');
foreach ($values as $key => $fichier) {
...
}
```
Upvotes: -1 <issue_comment>username_2: You could check the content of `$node->field_fichier_joint[$key]['view']`
```
foreach ($node->field_fichier_joint as $key => $fichier) {
//Ne pas afficher les champs vides du tableau
if ($fichier !== NULL):
print 'debug de $fichier'.$fichier;
print (isset($node->field_fichier_joint[$key]['view']))
? '- '.$node->field\_fichier\_joint[$key]['view'].'
'
: '';
endif;
}
```
or as suggeted by B.Desai use empty() for check also for empty string
```
foreach ($node->field_fichier_joint as $key => $fichier) {
//Ne pas afficher les champs vides du tableau
if ($fichier !== NULL):
print 'debug de $fichier'.$fichier;
print (!empty($node->field_fichier_joint[$key]['view']))
? '- '.$node->field\_fichier\_joint[$key]['view'].'
'
: '';
endif;
}
```
Upvotes: 0 <issue_comment>username_3: So, just check if value is not empty with `empty` function:
```
foreach ($node->field_fichier_joint as $key => $fichier) {
//Ne pas afficher les champs vides du tableau
if (!empty($fichier['view'])):
print '- ' . $fichier['view'] . '
';
endif;
}
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 551 | 2,137 | <issue_start>username_0: I was working on injecting of groovy scripts dynamically in Java. So before executing those scripts, I want to get sure of that they do not have potential bugs using [SpotBugs](https://github.com/spotbugs/spotbugs) (static code analyzer).
Here is the Psuedo-Code:
>
> Here it should return the infinite loop bug.
>
>
>
```
String script = "class Hello { static void main(String []args) { def i = 0; while ( i <= 0) { i = i - 1; } } } ";
List bugs = SpotBugs.getBugs(script);
if (bugs == null) {
execute(script);
}
```
So how to do the `SpotBugs.getBugs(script)` using java, the input script will not be hard-coded as in above example, but will be dynamically fetched.<issue_comment>username_1: seems like SpotBugs should run using maven, which means it will package and include only the groovy scripts that are valid.
hence, you will not need to check before execution.
Upvotes: 0 <issue_comment>username_2: Easiest API
===========
The easiest way is to write the compiled code to class files (in a temp directory if needed). By having compiled class as file, you will be able to use the [`FindBugs`](https://static.javadoc.io/com.github.spotbugs/spotbugs/3.1.0/edu/umd/cs/findbugs/FindBugs.html) class which provide an API to configure the scope and rules without playing with internal classes that are subject to changes.
Groovy dynamic (default) vs static compiling
============================================
However, the main obstacle you'll face is that groovy **bytecode** is too obfuscated for SpotBugs. For the call to function `abc()`, you will not see an invoke to method `abc` in the bytecode. It will be a reference to a global functions map that is created at runtime. Groovy has a mode to compile to a less dynamic format. This mode does not allow functions to be created at runtime. You can check the configuration to instruct the compiler for the static mode in this test repo: <https://github.com/find-sec-bugs/find-sec-bugs-demos/tree/master/groovy-simple>. This is, however, a Gradle compilation not a programmatic API that received a String as code.
Upvotes: 2 [selected_answer] |
2018/03/21 | 500 | 1,783 | <issue_start>username_0: I have a rails project whose API's are used by two different but related apps.
One app (Parent) is made using Unity, while other one (Child) is with native (iOS & Android).
In case of error response.
Unity app requires 2xx series status code,in case of any other status code they read it as success case.
While native (iOS & Android) apps need 4xx series status code, in case of any other status code they read it as success case.
Is there any way that from request I can know that which app sent request?
or any other solution to handle this?<issue_comment>username_1: request method has parameter as
```
request.user_agent
```
Upvotes: 0 <issue_comment>username_2: >
> Is there any way that from request I can know that which app sent
> request?
>
>
>
Yes. Several ways.
**1**.Use form to send which device is making the request then access this fro your rail server.
```
WWWForm form = new WWWForm();
//From Unity
form.AddField("App", "Unity");
```
Or
```
//From Native
form.AddField("App", "Native");
```
Then send:
```
UnityWebRequest uwr = UnityWebRequest.Post(url, form);
yield return uwr.SendWebRequest();
```
**2**.Use a custom header to send which device is making the request then access this from your rail server.
```
//From Unity
UnityWebRequest.SetRequestHeader("App", "Unity");
```
Or
```
//From Native
UnityWebRequest.SetRequestHeader("App", "Native");
```
All you need to do is access "App" on rail for both of these.
**3**.Use json or xml to store which device the request is coming from the access this from the server.
The API used here is for Unity but you can do similar thing on iOS and Android too for the native app with Object-C and Java API. It's still the-same thing.
Upvotes: 3 [selected_answer] |
2018/03/21 | 2,253 | 9,065 | <issue_start>username_0: I am executing below code snippet
```
System.out.println(List.of(1, 2).getClass());
System.out.println(List.of(1, 2, 3).getClass());
```
output of this code is;
```
class java.util.ImmutableCollections$List2
class java.util.ImmutableCollections$ListN
```
I am expecting `java.util.ImmutableCollections$List3` as output for the second statement because there is `of()` method which takes three parameter, Why java creating `ImmutableCollections$ListN` but not `ImmutableCollections$List3`?
Edited: It is Java-9 question. There are total 11 overloaded of() methods in List interface each of them takes variable number of parameters from zero to 10 and eleventh one takes varargs to handle N list. So I am expecting List0 to List10 implementation for first 10 overloaded methods, but it is returning ListN with three parameters. Yes, it is implementation detail but just curious to know more information of this.<issue_comment>username_1: Those are both *classes* that are being returned. i.e. there is a separate class for `ImmutableCollections$List2` and `ImmutableCollections$ListN` (the $ indicates an inner class)
This is an implementation detail, and (presumably) List2 exists for (possibly) some optimisation reason. I suspect if you look at the source (via your IDE or similar) you'll see two distinct inner classes.
Upvotes: 1 <issue_comment>username_2: Neither `ImmutableCollections$List2` nor `ImmutableCollections$ListN` is generated at runtime. There are four classes already written:
```
static final class List0 extends AbstractImmutableList { ... }
static final class List1 extends AbstractImmutableList { ... }
static final class List2 extends AbstractImmutableList { ... }
static final class ListN extends AbstractImmutableList { ... }
```
Starting with `of(E e1, E e2, E e3)` and up to `of(E e1, ..., E e10)` an instance of `ImmutableCollections.ListN<>` is going to be created.
>
> Why java creating `ImmutableCollections$ListN` but not `ImmutableCollections$List3`?
>
>
>
The designers have probably decided that `3` and `N` cases are similar and it's not worth writing a separate class for `3`. Apparently, they won't get enough benefits from `$List3`, `$List7`, `$List10` as they have got from the `$List0`, `$List1`, and `$List2` versions. They are specifically-optimised.
Currently, 4 classes cover 10 methods. If they decided to add some more methods (e.g. [with 22 arguments](https://stackoverflow.com/questions/6241441/why-does-the-scala-library-only-defines-tuples-up-to-tuple22)), there would still be these 4 classes.
Imagine you are writing 22 classes for 22 methods. How much unnecessary code duplication would it involve?
Upvotes: 2 <issue_comment>username_3: `ListN` is the all-purpose version. `List2` is an optimised implementation. There is no such optimised implementation for a list with three elements.
There currently exist\* optimised versions for lists and sets with zero, one and two elements. `List0`, `List1`, `List2`, `Set0` etc...
There's also an optimised implementation for an empty map, `Map0`, and for a map containing a single key-value pair, `Map1`.
Discussion relating to how these implementations are able to provide performance improvements can been seen in [JDK-8166365](https://bugs.openjdk.java.net/browse/JDK-8166365).
---
\*bear in mind this is an implementation detail which may be subject to change, and actually [is due to change fairly soon](http://mail.openjdk.java.net/pipermail/core-libs-dev/2018-March/052183.html)
Upvotes: 3 <issue_comment>username_4: As <NAME> rightly mentioned, it is an implementation detail. The specification of `List.of` says that it returns an immutable List, and that's all that matters.
The developers probably decided that they could provide efficient implementations of one-element (`List1`) and two-element lists (`List2`), and that all other sizes could be handled by a single type (`ListN`). This could change at some point in the future - maybe they will introduce a `List3` at some point, maybe not.
As per the rules of polymorphism and encapsulation, none of this matters. As long as the returned object is a List, you should not concern yourself with its actual implementation.
Upvotes: 1 <issue_comment>username_5: The main reason to have several different private implementations of `List` is to save space.
Consider an implementation that stores its elements in an array. (This is essentially what `ListN` does.) In Hotspot (64-bit with compressed object pointers, each 4 bytes) each object requires a 12-byte header. The `ListN` object has a single field containing the array, for a total of 16 bytes. An array is a separate object, so that has another 12-byte header plus a 4-byte length. That's another 16 bytes, not counting any actual elements stored. If we're storing two elements, they take 8 bytes. That brings the total to 40 bytes for storing a two-element list. That's quite a bit of overhead!
If we were to store the elements of a small list in fields instead of an array, that object would have a header (12 bytes) plus two fields (8 bytes) for a total of 20 bytes -- half the size. For small lists, there's a considerable savings with storing elements in fields of the `List` object itself instead of in an array, which is a separate object. This is what the old `List2` implementation did. It's recently been superseded by the `List12` implementation, which can store lists of one or two elements in fields.
Now, in the API there are 12 overloaded `List.of()` methods: zero to ten fixed args plus varargs. Shouldn't there be corresponding `List0` through `List10` and `ListN` implementations?
There could be, but there doesn't necessarily have to be. An early prototype of these implementations had the optimized small list implementations tied to the APIs. So the zero, one, and two fixed arg `of()` methods created instances of `List0`, `List1`, and `List2`, and the varargs `List.of()` method created an instance of `ListN`. This was fairly straightforward, but it was quite restrictive. We wanted to be able to add, remove, or rearrange implementations at will. It's considerably more difficult to change APIs, since we have to remain compatible. Thus, we decided to decouple things so that the number of arguments in the APIs was largely independent of the implementation instantiated underneath.
In JDK 9 we ended up with the 12 overloads in the API, but only four implementations: field-based implementations holding 0, 1, and 2 elements, and an array-based implementation holding an arbitrary number. Why not add more field-based implementations? Diminishing returns and code bloat. Most lists have few elements, and there's an exponential dropoff in the occurrences of lists as the number of elements gets larger. The space savings get relatively smaller compared to an array-based implementation. Then there's the matter of maintaining all those extra implementations. Either they'd have to be entered directly in the source code (bulky) or we'd switch over to a code generation scheme (complex). Neither seemed justified.
Our startup performance guru [<NAME>](https://stackoverflow.com/users/2397895/claes-redestad) did some measurements and found that there was a speedup in having *fewer* list implementations. The reason is *megamorphic dispatch*. Briefly, if the JVM is compiling the code for a virtual call site and it can determine that only one or two different implementations are called, it can optimize this well. But if there are many different implementations that can be called, it has to go through a slower path. (See this article for [Black Magic](https://shipilev.net/blog/2015/black-magic-method-dispatch/) details.)
For the list implementations, it turns out that we can get by with fewer implementations without losing much space. The `List1` and `List2` implementations can be combined into a two-field `List12` implementation, with the second field being null if there's only one element. We only need one zero-length list, since it's immutable! For a zero-length list, we can get rid of `List0` just use a `ListN` with a zero-length array. It's bigger than an old `List0` instance, but we don't care, since there's only one of them.
These changes just went into the JDK 11 mainline. Since the API is completely decoupled from the implementations, there is no compatibility issue.
There are additional possibilities for future enhancements. One potential optimization is to fuse an array onto the end of an object, so the object has a fixed part and a variable-length part. This will avoid the need for an array object's header, and it will probably improve locality of reference. Another potential optimization is with value types. With value types, it might be possible to avoid heap allocation entirely, at least for small lists. Of course, this is all highly speculative. But if new features come along in the JVM, we can take advantage of them in the implementations, since they're are entirely hidden behind the API.
Upvotes: 4 |
2018/03/21 | 774 | 2,507 | <issue_start>username_0: i have this Code in my .htaccess file:
```
#Rewrite everything to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)/?$ index.php?witz=$1 [L,QSA]
ErrorDocument 404 https://example.com/erorrpage.php
ErrorDocument 403 https://example.com/erorrpage.php
```
i have one argument like this:
<https://example.com/var><issue_comment>username_1: I will suppose that you use apache.
1. Ensure that your .htaccess file are on the right directory (like root directory for example) or `erorrpage.php` is accessible on the `https://example.com/`
2. Try to simplify it with `ErrorDocument 404 "Custom very simple 404 error"`, just to see if it works
3. Ensure that your mod rewrite is enabled (on `httpd.conf`, uncomment the `;LoadModule rewrite_module modules/mod_rewrite.so` if not. Then restart apache)
4. Find the relevant directory tag for your www root (on other words, on your apache config of your root directory) and change `AllowOverride None` to `AllowOverride All`
5. If the problem occured in a web hosting, the ensure that it allow the .htaccess
6. If all of these does not work, try to check [apache official docs](http://httpd.apache.org/docs/2.2/mod/core.html#errordocument)
Upvotes: 0 <issue_comment>username_2: Your `ErrorDocument` is not getting triggered because of the following Rule you have in your htaccess
```
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)/?$ index.php?witz=$1 [L,QSA]
```
The Rule redirects everything that doesn't exist as directory `!-d` and `!-f` file to `/index.php` . Since `mod-rewrite` Rules are applied before `mod-core` your ErrorDocument will never get applied.
To solve this,You need to use a `mod-rewrite` Rule instead of ErrorDocument to Redirect non-existent requests to 404 page. So put the following at the top of your `htaccess`
```
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)/?$ - [R=404,L]
```
If you want to redirect 404 requests to a specific page ,you can use the following
```
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)/?$ /errorpage.php [R= 404,L]
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 554 | 1,799 | <issue_start>username_0: I'm using xxHash to create hashes from elements id. I just don't want to show real id on website. I created script to test is there option to get same hashes:
```
const _ = require('lodash');
const XXH = require('xxhashjs');
let hashes = []
let uniq_hashes = []
for(let i = 0; i < 1000000; i++){
var h = XXH.h32(i.toString(), 0xABCD).toString(16)
hashes.push(h)
}
uniq_hashes = _.uniq(hashes)
console.log(hashes.length, uniq_hashes.length);
```
Log from the script is `1000000 999989`, so some hashes was the same. Is it correct way how xxHash works?
Also, first pair is '1987' and '395360'
If i need really unique hashes (no crypto) what should I use?<issue_comment>username_1: By the birthday paradox you should see a collisions at around 1:16^2 or 10^6 / 2^16 = ~15 so 11 collisions seems about right. (Note: the math is grossly simplified, see [Birthday problem](https://en.wikipedia.org/wiki/Birthday_problem) for good math.)
Too reduce the number of collisions increase the hash size and use a cryptographic hash such as SHA-256. Cryptographic hash functions are designed to avoid collisions.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You should use a hash with a larger hash digest. Even a 32-bit chunk of a secure cryptographic hash will have unavoidable collisions eventually.
Since you are using Node.js and want something faster than cryptographic hashes, try [MetroHash128](https://github.com/robertklep/node-metrohash) or [murmur128](https://github.com/hideo55/node-murmurhash3) or [CityHash128](https://github.com/fbzhong/node-cityhash). There's also CityHash256 is you want to go completely overboard. These should be very fast due to using C++ bindings, and the chance of random collision is reduced astronomically.
Upvotes: 0 |
2018/03/21 | 411 | 1,149 | <issue_start>username_0: I have a table as below
```
Id | PriceCardId | Days
1 | 1 | 2
2 | 1 | 4
3 | 1 | 5
4 | 1 | 6
5 | 1 | 3
6 | 2 | 5
7 | 2 | 3
8 | 3 | 6
```
How to write SQL query to get all PriceCardId has Day contain
```
List days
Example days = [2,4,5,6], with data as above result is 1
```
Thanks!<issue_comment>username_1: I think you want:
```
select pricecardid
from t
where day in (2, 4, 5, 6)
group by pricecardid
having count(*) = 4; -- the number of days you are looking for
```
This assumes no duplicates in your table. If there are duplicates, use `having count(distinct day)` instead of `count(*)`.
Note: You can phrase this as:
```
with d as (
select v.dy
from values ( (2), (4), (5), (6) ) v(dy)
)
select pricecardid
from t
where day in (select d.dy from d)
group by pricecardid
having count(*) = (select count(*) from d);
```
Upvotes: 2 <issue_comment>username_2: Try this:
```
SELECT PriceCardId
FROM [My_Table]
WHERE [Day] IN(2,4,5,6)
GROUP BY PriceCardId
HAVING COUNT(DISTINCT [Day])=4
```
Upvotes: 1 |
2018/03/21 | 324 | 1,045 | <issue_start>username_0: In Moodle, I can see the following roles - Student and Manager. I have created 2 managers and 5 students. Is there a way to assign 3 students to 1 manager so that whenever these 2 students send any requests for approval, it will be shown only to their respective Manager?<issue_comment>username_1: I think you want:
```
select pricecardid
from t
where day in (2, 4, 5, 6)
group by pricecardid
having count(*) = 4; -- the number of days you are looking for
```
This assumes no duplicates in your table. If there are duplicates, use `having count(distinct day)` instead of `count(*)`.
Note: You can phrase this as:
```
with d as (
select v.dy
from values ( (2), (4), (5), (6) ) v(dy)
)
select pricecardid
from t
where day in (select d.dy from d)
group by pricecardid
having count(*) = (select count(*) from d);
```
Upvotes: 2 <issue_comment>username_2: Try this:
```
SELECT PriceCardId
FROM [My_Table]
WHERE [Day] IN(2,4,5,6)
GROUP BY PriceCardId
HAVING COUNT(DISTINCT [Day])=4
```
Upvotes: 1 |
2018/03/21 | 607 | 2,113 | <issue_start>username_0: I'm battling to understand how to resolve the warning:
>
> `key` is not a prop. Trying to access it will result in `undefined`
> being returned. If you need to access the same value within the child
> component, you should pass it as a different prop.
>
>
>
I have added 'i' in my map function, and passing it to my child as 'key'.
I'm not sure what it means by 'pass it as a different prop'. What am I doing wrong?
```
{
this.state.accounts.map(function(account, i){
return (
)
})
}
```
In the AccountCard component, I access the key/id like this:
```
```<issue_comment>username_1: I think the problem is not in this snippet (altough the use of index as key is not recommended, use `account.id` as key), but in the `AccountCard` component declaration. I think there you're trying to do something like `props.key`.
If you really need that `i` in the child component, add another props just for that and use that in the child.
```
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Don't access `this.props.key`. Key is for React itself. If you need value of key *"pass it as a different prop"*. For example:
```
```
`Key` is for React, `myKey` is for you to access with `this.props.myKey`. See the [docs](https://reactjs.org/docs/lists-and-keys.html) for examples.
Upvotes: 2 <issue_comment>username_3: While the other answers are correct, I'd like to add an alternative solution.
Instead of passing the key down via some arbitrary prop, you can provide a key directly by wraping a `div` around each `AccountCard`. Like so:
```
this.state.accounts.map(function(account, i){
return (
)
})
```
---
**OR**, use [fragments](https://reactjs.org/docs/fragments.html) if you are using React v16.2 or later:
```
this.state.accounts.map(function(account, i){
return (
)
})
```
Using [fragments](https://reactjs.org/docs/fragments.html) will not add any unnecessary elements to the DOM (like the `div` in the first example). You can also use the `<>` and shorthand syntax if you prefer.
Upvotes: 2 |
2018/03/21 | 539 | 1,879 | <issue_start>username_0: I have a table which has 3 columns StudentID, Score and ClassNumber.
What I need now is to select top 5 students of each Class (according to their Score result).
For example if there are 20 students in Class1, 40 students in Class2 and students in Class3, I need to select 15 top score students for each Class(5 for Class1, 5 for Class2, 5 for Class3)
How can I do this in one SQL query?<issue_comment>username_1: I think the problem is not in this snippet (altough the use of index as key is not recommended, use `account.id` as key), but in the `AccountCard` component declaration. I think there you're trying to do something like `props.key`.
If you really need that `i` in the child component, add another props just for that and use that in the child.
```
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Don't access `this.props.key`. Key is for React itself. If you need value of key *"pass it as a different prop"*. For example:
```
```
`Key` is for React, `myKey` is for you to access with `this.props.myKey`. See the [docs](https://reactjs.org/docs/lists-and-keys.html) for examples.
Upvotes: 2 <issue_comment>username_3: While the other answers are correct, I'd like to add an alternative solution.
Instead of passing the key down via some arbitrary prop, you can provide a key directly by wraping a `div` around each `AccountCard`. Like so:
```
this.state.accounts.map(function(account, i){
return (
)
})
```
---
**OR**, use [fragments](https://reactjs.org/docs/fragments.html) if you are using React v16.2 or later:
```
this.state.accounts.map(function(account, i){
return (
)
})
```
Using [fragments](https://reactjs.org/docs/fragments.html) will not add any unnecessary elements to the DOM (like the `div` in the first example). You can also use the `<>` and shorthand syntax if you prefer.
Upvotes: 2 |
2018/03/21 | 583 | 2,427 | <issue_start>username_0: I have a piece of code that can be called both within and outside a HTTP request, but wants to access information in the HttpServletRequest if it is available. My first attempt was the following:
```
@Inject
private Instance httpReq;
void doSomethingIfInRequest(){
if (httpReq.isUnsatisfied()){
return;
}
httpReq.get()
// ...
}
```
However, even outside a request, `isUnsatisfied()` returns `false`, leading `get()` to throw `org.jboss.weld.exceptions.IllegalStateException: WELD-000710: Cannot inject HttpServletRequest outside of a Servlet request`.
I can solve this by catching the exception or creating another class that holds the request but was wondering whether CDI/Weld offers something to deal with this.<issue_comment>username_1: `HttpServletRequest` is a so called built-in bean. CDI (Weld) provides it for you. It is always present and detected, hence `Instance.isUnsatisfied()` is going to be `false`.
You can glance at the implementation (for Weld 3) [here](https://github.com/weld/core/blob/master/modules/web/src/main/java/org/jboss/weld/module/web/HttpServletRequestBean.java). The short story is - context state (`RequestScoped`) is checked and based on the result, you either get your bean, or the exception you are seeing.
Solution - best way is probably to check whether context is active, but you probably cannot avoid catching the exception if it's not.
This can be achieved for instance via `BeanManager`:
```
@Inject
BeanManager bm;
public boolean isReqScopeActive() {
try {
return bm.getContext(RequestScoped.class).isActive();
} catch (ContextNotActiveException e) {
// this is expected response to bm.getContext() if that context is inactive
return false;
}
}
```
Upvotes: 2 <issue_comment>username_2: In addition to the solution by username_1, the following code can be used to check whether the current context is HttpServletRequestContext or not.
```
@Inject
BeanManager bm;
public boolean isHttpRequestScopeIsActive() {
if (isHttpRequestScopeActive == null) {
try {
Context context = bm.getContext(RequestScoped.class);
isHttpRequestScopeActive = context instanceof HttpRequestContextImpl;
} catch (ContextNotActiveException e) {
isHttpRequestScopeActive = false;
}
}
return isHttpRequestScopeActive;
}
```
Upvotes: 0 |
2018/03/21 | 719 | 2,060 | <issue_start>username_0: Let's say we have:
```
var array1 = [{ id: 1 }, { id: 4}, { id: 3 }]
var array2 = [{ id: 1 }, { id: 2}]
```
I know you can concat the two arrays like this (without having duplicates):
```
Array.from(new Set(array1.concat(array2)))
```
Now, how to create a new array with **only** the objects that share the same values?
```
var array2 = [{ id: 1 }]
```<issue_comment>username_1: You can use `.filter()` and `.some()` to extract matching elements:
```js
let array1 = [{ id: 1 }, { id: 4}, { id: 3 }]
let array2 = [{ id: 1 }, { id: 2}]
let result = array1.filter(({id}) => array2.some(o => o.id === id));
console.log(result);
```
**Useful Resources:**
* [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
* [`Array.prototype.some()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some)
Upvotes: 2 <issue_comment>username_2: You could take a set with the `id` of the objects and filter `array2`
```js
var array1 = [{ id: 1 }, { id: 4}, { id: 3 }] ,
array2 = [{ id: 1 }, { id: 2}],
s = new Set(array1.map(({ id }) => id)),
common = array2.filter(({ id }) => s.has(id));
console.log(common);
```
The requested sameness with identical objects.
```js
var array1 = [{ id: 1 }, { id: 4}, { id: 3 }] ,
array2 = [array1[0], { id: 2}],
s = new Set(array1),
common = array2.filter(o => s.has(o));
console.log(common);
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Assuming, by your definition, that the objects, even if they have the same structure, are not really the same object, I define an 'equality function', and then, with `filter` and `some`:
```js
var array1 = [{ id: 1 }, { id: 4}, { id: 3 }]
var array2 = [{ id: 1 }, { id: 2}];
var equal = function(o1, o2) { return o1.id === o2.id };
var result = array2.filter(function(item1) {
return array1.some(function(item2) { return equal(item1, item2) });
});
console.log(result);
```
Upvotes: 1 |
2018/03/21 | 1,845 | 6,860 | <issue_start>username_0: I am implementing Passport Facebook Authentication by linking the Facebook Authentication API route to a button using href like:
```
[Facebook Login](auth/facebook)
```
When I click on the button, it redirects to the Facebook Authentication page. But on the page, an error message is displayed saying something like ***"Insecure Login Blocked: You can't get an access token or log in to this app from an insecure page. Try re-loading the page as https://"***
How can I fix this issue?<issue_comment>username_1: Amazingly I just started trying to do the same thing like an hour ago and have been having the same issue. If you go into the FB developer portal and go to **Settings** under **Facebook Login** there's an option to Enforce HTTPS.
[](https://i.stack.imgur.com/md9hI.png)
*Further Investigation Showed*:
"Enforce HTTPS. This setting requires HTTPS for OAuth Redirects and pages getting access tokens with the JavaScript SDK. All new apps created as of March 2018 have this setting on by default and you should plan to migrate any existing apps to use only HTTPS URLs by March 2019. Most major cloud application hosts provide free and automatic configuration of TLS certificates for your applications. If you self-host your app or your hosting service doesn't offer HTTPS by default, you can obtain a free certificate for your domain(s) from Let's Encrypt."
Reference: [Login Security](https://developers.facebook.com/docs/facebook-login/security/#surfacearea)
Upvotes: 4 <issue_comment>username_2: In my case, I modified my package.json file.
```
"start": "node scripts/start.js" =>
"start": "set HTTPS=true&&node scripts/start.js"
```
I hope help you.
Upvotes: 0 <issue_comment>username_3: Since Facebook have been requiring usage of HTTPS for our redirect URIs we can use ngrok at localhost for start up a local secure HTTP tunnel. It is a clean and fast suggested alternative for now.
* Get [official ngrok package](https://ngrok.com/download)
* Unzip to your preferred directory
`unzip /opt/ngrok.zip`;
* Make your first HTTP tunnel: `/opt/ngrok http 3000`
See more great use cases in [ngrok docs](https://ngrok.com/docs).
Upvotes: 2 <issue_comment>username_4: **This for php sdk reference**
Now **https is required for the web-application to login via Facebook**.
Following procedure is required get valid authentication from Facebook.
**Basic Seetings**
1. set **App Domains** as your root domain (*www.example.com*)
2. Privacy Policy URL (*<https://www.example.com/privacy-demo/>*)
3. Terms of Service URL (*<https://www.example.com/terms-demo/>*)
4. Set Category
5. Site URL (*<https://www.example.com/facebook-login/>*) `facebook-login` this folder contain my all facebook login files
**Advanced**
6. Server IP Whitelist (your host ip address *124.25.48.36*)
**Products below Facebook login settings**
7. Valid OAuth Redirect URIs (*<https://www.example.com/facebook-login/fb-callback.php>*)
**Quick start**
8. Select website put site url (*<https://www.example.com/facebook-login/>*)
Save all changes and live your app (ie: on your app) Now your app status will live.
You can refer this code <https://github.com/facebook/php-graph-sdk>
Upvotes: 0 <issue_comment>username_5: Since you're using `passport`, also check your `auth.js` settings, or where ever you keep these settings. **Even if your website has a certificate**, the following code will still fail:
```
'facebookAuth' : {
'clientID' : '.............', // App ID
'clientSecret' : '............................', // App Secret
'callbackURL' : 'localhost:9999/auth/facebook/callback',
'profileURL' : 'https://graph.facebook.com/v2.5/me?fields=first_name,last_name,email',
'profileFields' : ['id', 'email', 'name']
},
```
The problem lies with the `callbackUrl`.
```
'callbackURL' : '/auth/facebook/callback'
'callbackURL' : 'http://localhost:9999/auth/facebook/callback'
```
The statements above will both fail. The callbackUrl needs to start with `https`. The first one will try to load `http://localhost` and append the callbackUrl. The second one obiviously loads the full url with `http`, and both fail to connect with FB. So try one of the following. If your site has a certificate, provide the full url. If you're testing this on a localhost, create your own certificate and access it by https like:
```
'callbackURL' : 'https://example.com/auth/facebook/callback'
'callbackURL' : 'https://localhost:9999/auth/facebook/callback'
```
Upvotes: 3 <issue_comment>username_6: To fix, for local development, generate ssl certs on your machine. Run the commands below(tested on Mac High Sierra, you will need the openssl lib installed on your os) to create a `cert.pem` and a `key.pem` file in your working directory.
```
openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
openssl rsa -in keytmp.pem -out key.pem
```
Change your node http server to use https. You will need to import the `https` module in place of the `http` module.
```
const https = require('https')
const path = require('path')
const fs = require('fs')
const options = {
cert: fs.readFileSync(path.resolve(__dirname, '')),
key: fs.readFileSync(path.resolve(\_\_dirname, ''))
}
const server = https.createServer(options, )
server.listen()
```
Go to the app on your facebook developer console and set the Valid OAuth Redirect URIs to the https version of your localhost domain. Do same for the app domain and site url.
Upvotes: 1 <issue_comment>username_7: use a vpn worked for me cyber ghost is free try it
Upvotes: 0 <issue_comment>username_8: In your passport setting change your redirect url to some **<https://someUrl>**
'https' is important
Upvotes: 0 <issue_comment>username_9: There are 2 ways you can solve that:
First:
You can go to your google Passport strategy and add proxy: true
```
passport.use(
new FacebookStrategy(
{
clientID: facebookID,
clientSecret: facebookSecret,
callbackURL: "/auth/facebook/callback",
proxy: true
}
)
);
```
What happens most of the time is that, when you deploy or app through Heroku, for example, they have a Proxy that allows Heroku to direct the requests to your specific server and Passport assumes that if your request goes through a proxy it might not be safe (So... No https).
The second way you can solve that is by using a specific path for your callbackURL.
For example, instead of using:
```
callbackURL: "/auth/facebook/callback"
```
you would use:
```
callbackURL: https://mydomain/auth/facebook/callback
```
Keep in mind that if you are going to use this approach you might need to create environment variables to hold the values of your specific redirectURL for development as well as for production.
Upvotes: 2 |
2018/03/21 | 1,894 | 6,856 | <issue_start>username_0: i am having four fields as shown in code. i want to sum the `night_firsthotel`,`night_secondhotel`,`night_thirdhotel` and assign result to `total_night`.
How would i do this?
```
= $form-field($model, 'nights_firsthotel')->dropDownList(range(1, 10)); ?>
= $form-field($model, 'nights_secondhotel')->dropDownList(range(1, 10)); ?>
= $form-field($model, 'nights_thirdhotel')->dropDownList(range(1, 10)); ?>
= $form-field($model, 'total_nights')->textInput(['readOnly'=> true]) ?>
```<issue_comment>username_1: Amazingly I just started trying to do the same thing like an hour ago and have been having the same issue. If you go into the FB developer portal and go to **Settings** under **Facebook Login** there's an option to Enforce HTTPS.
[](https://i.stack.imgur.com/md9hI.png)
*Further Investigation Showed*:
"Enforce HTTPS. This setting requires HTTPS for OAuth Redirects and pages getting access tokens with the JavaScript SDK. All new apps created as of March 2018 have this setting on by default and you should plan to migrate any existing apps to use only HTTPS URLs by March 2019. Most major cloud application hosts provide free and automatic configuration of TLS certificates for your applications. If you self-host your app or your hosting service doesn't offer HTTPS by default, you can obtain a free certificate for your domain(s) from Let's Encrypt."
Reference: [Login Security](https://developers.facebook.com/docs/facebook-login/security/#surfacearea)
Upvotes: 4 <issue_comment>username_2: In my case, I modified my package.json file.
```
"start": "node scripts/start.js" =>
"start": "set HTTPS=true&&node scripts/start.js"
```
I hope help you.
Upvotes: 0 <issue_comment>username_3: Since Facebook have been requiring usage of HTTPS for our redirect URIs we can use ngrok at localhost for start up a local secure HTTP tunnel. It is a clean and fast suggested alternative for now.
* Get [official ngrok package](https://ngrok.com/download)
* Unzip to your preferred directory
`unzip /opt/ngrok.zip`;
* Make your first HTTP tunnel: `/opt/ngrok http 3000`
See more great use cases in [ngrok docs](https://ngrok.com/docs).
Upvotes: 2 <issue_comment>username_4: **This for php sdk reference**
Now **https is required for the web-application to login via Facebook**.
Following procedure is required get valid authentication from Facebook.
**Basic Seetings**
1. set **App Domains** as your root domain (*www.example.com*)
2. Privacy Policy URL (*<https://www.example.com/privacy-demo/>*)
3. Terms of Service URL (*<https://www.example.com/terms-demo/>*)
4. Set Category
5. Site URL (*<https://www.example.com/facebook-login/>*) `facebook-login` this folder contain my all facebook login files
**Advanced**
6. Server IP Whitelist (your host ip address *172.16.17.32*)
**Products below Facebook login settings**
7. Valid OAuth Redirect URIs (*<https://www.example.com/facebook-login/fb-callback.php>*)
**Quick start**
8. Select website put site url (*<https://www.example.com/facebook-login/>*)
Save all changes and live your app (ie: on your app) Now your app status will live.
You can refer this code <https://github.com/facebook/php-graph-sdk>
Upvotes: 0 <issue_comment>username_5: Since you're using `passport`, also check your `auth.js` settings, or where ever you keep these settings. **Even if your website has a certificate**, the following code will still fail:
```
'facebookAuth' : {
'clientID' : '.............', // App ID
'clientSecret' : '............................', // App Secret
'callbackURL' : 'localhost:9999/auth/facebook/callback',
'profileURL' : 'https://graph.facebook.com/v2.5/me?fields=first_name,last_name,email',
'profileFields' : ['id', 'email', 'name']
},
```
The problem lies with the `callbackUrl`.
```
'callbackURL' : '/auth/facebook/callback'
'callbackURL' : 'http://localhost:9999/auth/facebook/callback'
```
The statements above will both fail. The callbackUrl needs to start with `https`. The first one will try to load `http://localhost` and append the callbackUrl. The second one obiviously loads the full url with `http`, and both fail to connect with FB. So try one of the following. If your site has a certificate, provide the full url. If you're testing this on a localhost, create your own certificate and access it by https like:
```
'callbackURL' : 'https://example.com/auth/facebook/callback'
'callbackURL' : 'https://localhost:9999/auth/facebook/callback'
```
Upvotes: 3 <issue_comment>username_6: To fix, for local development, generate ssl certs on your machine. Run the commands below(tested on Mac High Sierra, you will need the openssl lib installed on your os) to create a `cert.pem` and a `key.pem` file in your working directory.
```
openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
openssl rsa -in keytmp.pem -out key.pem
```
Change your node http server to use https. You will need to import the `https` module in place of the `http` module.
```
const https = require('https')
const path = require('path')
const fs = require('fs')
const options = {
cert: fs.readFileSync(path.resolve(__dirname, '')),
key: fs.readFileSync(path.resolve(\_\_dirname, ''))
}
const server = https.createServer(options, )
server.listen()
```
Go to the app on your facebook developer console and set the Valid OAuth Redirect URIs to the https version of your localhost domain. Do same for the app domain and site url.
Upvotes: 1 <issue_comment>username_7: use a vpn worked for me cyber ghost is free try it
Upvotes: 0 <issue_comment>username_8: In your passport setting change your redirect url to some **<https://someUrl>**
'https' is important
Upvotes: 0 <issue_comment>username_9: There are 2 ways you can solve that:
First:
You can go to your google Passport strategy and add proxy: true
```
passport.use(
new FacebookStrategy(
{
clientID: facebookID,
clientSecret: facebookSecret,
callbackURL: "/auth/facebook/callback",
proxy: true
}
)
);
```
What happens most of the time is that, when you deploy or app through Heroku, for example, they have a Proxy that allows Heroku to direct the requests to your specific server and Passport assumes that if your request goes through a proxy it might not be safe (So... No https).
The second way you can solve that is by using a specific path for your callbackURL.
For example, instead of using:
```
callbackURL: "/auth/facebook/callback"
```
you would use:
```
callbackURL: https://mydomain/auth/facebook/callback
```
Keep in mind that if you are going to use this approach you might need to create environment variables to hold the values of your specific redirectURL for development as well as for production.
Upvotes: 2 |
2018/03/21 | 1,595 | 5,895 | <issue_start>username_0: **Tools**
* MSBuild v14
* Visual Studio 2013
* Jenkins v2.111 running on Windows Server 2012
* Git (bare repo on local file server)
* Windows Batch
**My goal**
Build a c# Visual Studio project using MSBuild that pulls back the major and minor version numbers from the projects AssemblyInfo.cs for use during the build. The build would produce something like 1.2.$BUILD\_NUMBER resulting in something like 1.2.121, 1.2.122, 1.2.123 and so on. Once the user opts to 'release' the build, a clickonce deployment with correct version in the folder name is copied to its target destination and a tag applied to the Git repository.
**Pipeline example**
Below is a 'work in progress' of what I've got up to. Any suggestions to improve are welcome. For those that are wondering why I'm coping the codebase out to a temporary folder. I'm using a multi-branch job in Jenkins and the folders that are auto-generated are extremely long! This gave me errors along the lines that my file name, project name or both are too long (because the entire path is above the 255 or so character length). So the only way to get around this was to copy out contents so the build and publish would work.
```
pipeline {
agent none
stages {
stage ('Checkout'){
agent any
steps
{
checkout scm
}
}
stage ('Nuget Restore'){
agent any
steps
{
bat 'nuget restore "%WORKSPACE%\\src\\Test\\MyTestSolution.sln"'
}
}
stage('Build Debug') {
agent any
steps
{
bat "xcopy %WORKSPACE%\\src\\* /ey d:\\temp\\"
bat "\"${tool 'MSBuild'}\" d:\\temp\\Test\\MyTestSolution.sln /p:Configuration=Debug /target:publish /property:PublishUrl=d:\\temp\\ /p:OutputPath=d:\\temp\\build\\ /p:GenerateBootstrapperSdkPath=\"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.1A\\Bootstrapper\" /p:VersionAssembly=1.0.$BUILD_NUMBER /p:ApplicationVersion=1.0.$BUILD_NUMBER"
}
}
stage('Deploy to Dev'){
agent none
steps {
script {
env.DEPLOY_TO_DEV = input message: 'Deploy to dev?',
parameters: [choice(name: 'Deploy to dev staging area?', choices: 'no\nyes', description: 'Choose "yes" if you want to deploy this build')]
}
}
}
stage ('Deploying to Dev')
{
agent any
when {
environment name: 'DEPLOY_TO_DEV', value: 'yes'
}
steps {
echo 'Deploying debug build...'
}
}
stage ('Git tagging')
{
agent any
steps
{
bat 'd:\\BuildTargets\\TagGit.bat %WORKSPACE% master v1.0.%BUILD_NUMBER%.0(DEV) "DEV: Build deployed."'
}
}
}
}
```
At the moment I've hard coded the major and minor version in the above script. I want to pull these values out of the AssemblyInfo.cs so that developers can control it from there without editing the Jenkinsfile. Any suggestions/best practice to achieve this?
Because I'm doing a clickonce deployment for a winforms app I've had to use MSBuild's VersionAssembly and ApplicationVersion switches to pass in the version. This seems to help with correctly labelling folders when MSBuild publishes the files. Have I have missed something in my setup which would negate these switches and make life simpler?
The last action in my pipeline is to trigger a .bat file to add a tag back into the master branch of the repository. This is another reason that I need to make the major and minor version accessible to the pipeline script.
**MSBuild target for editing AssemblyInfo.cs**
This code was taken from here: <http://www.lionhack.com/2014/02/13/msbuild-override-assembly-version/>
```
xml version="1.0" encoding="utf-8"?
CommonBuildDefineModifiedAssemblyVersion;
$(CompileDependsOn);
`try {
var rx = new System.Text.RegularExpressions.Regex(this.Regex);
for (int i = 0; i < Files.Length; ++i)
{
var path = Files[i].GetMetadata("FullPath");
if (!File.Exists(path)) continue;
var txt = File.ReadAllText(path);
txt = rx.Replace(txt, this.ReplacementText);
File.WriteAllText(path, txt);
}
return true;
}
catch (Exception ex) {
Log.LogErrorFromException(ex);
return false;
}`
```
**Git tagging**
This bat file is kicked off and passed values used to create and push a tag to the defined repository.
```
echo off
set gitPath=%1
set gitBranchName=%2
set gitTag=%3
set gitMessage=%4
@echo on
@echo Adding tag to %gitBranchName% branch.
@echo Working at path %gitPath%
@echo Tagging with %gitTag%
@echo Using commit message: %gitMessage%
d:
cd %gitPath%
git checkout %gitBranchName%
git pull
git tag -a %gitTag% -m %gitMessage%
git push origin %gitBranchName% %gitTag%
```
If there are any other gold nuggests that would help streamline or improve this overall workflow, would welcome those too!<issue_comment>username_1: I recently had the same problem which i solved by creating a Windows Script.
```
for /f delims^=^"^ tokens^=2 %%i in ('findstr "AssemblyFileVersion" %1\\AssemblyFile.cs') DO SET VERSION=%%i
```
This script extracts the version number from the AssemblyInfo.cs and put it inside an variable so it can be used later to tag the commit (in the same step though) :
```
CALL FindAssemblyVersion .\Properties
git tag %VERSION%
git push http://%gitCredentials%@url:port/repo.git %VERSION%
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Not exactly from the assembly file but a very handy workaround to get the file version from the DLL while working with Jenkins, and using batch (or `powershell`) command:
>
> Goto the directory where your DLL exists [CD Foo/Bar ]
>
>
>
```
FOR /F "USEBACKQ" %F IN (`powershell -NoLogo -NoProfile -Command (Get-Item "myApi.dll").VersionInfo.FileVersion`) DO (SET fileVersion=%F )
echo File version: %fileVersion%
```
Upvotes: 0 |
2018/03/21 | 445 | 1,598 | <issue_start>username_0: I tried forcing "Full Screen" in my styles like this:
```
true
true
```
I tried from my activity:
```
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
```
I even tried this, which makes the intent that would get called when I press on the "full screen display" button :
```
public static boolean goToFullScreen(final Activity activity) {
PackageManager packageManager = activity.getPackageManager();
try {
if ("huawei".equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
final Intent huaweiIntent = new Intent();
huaweiIntent.setComponent(new ComponentName("com.android.systemui", "com.android.systemui.settings.HwChangeButtonActivity"));
if (huaweiIntent.resolveActivity(packageManager) != null) {
activity.startActivity(huaweiIntent);
return true;
}
}
} catch (Exception e) {
Utils.appendLog("goToBatterySettings exception:" + e.getMessage(), "E", Constants.OTHER);
}
return false;
}
```
But I always get this [Screenshot](https://s3.amazonaws.com/uploads.hipchat.com/39260/829560/yEa6LtrbE0wIeGw/upload.png)
Any ideea how to fix this?<issue_comment>username_1: Try to add
```
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
```
Upvotes: 0 <issue_comment>username_2: Add the following to the element:
```
```
See: <https://android-developers.googleblog.com/2017/03/update-your-app-to-take-advantage-of.html>
Upvotes: 2 |
2018/03/21 | 298 | 1,077 | <issue_start>username_0: I would like to display an online image in an image view with the use of Intent Service.
```
public class IntentServiceClass extends IntentService {
public IntentServiceClass() {
super("IntentServiceClass");
}
@Override
protected void onHandleIntent( Intent intent) {
if (intent != null) {
String URLImage = "https://tortoisesvn.net/assets/img/logo-256x256.png";
Bitmap bmp = null;
try{
InputStream inputStream = new java.net.URL(URLImage).openStream();
bmp = BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
}
I do not know if I am doing this wrong and how to continue.
Can someone help me please?<issue_comment>username_1: Try to add
```
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
```
Upvotes: 0 <issue_comment>username_2: Add the following to the element:
```
```
See: <https://android-developers.googleblog.com/2017/03/update-your-app-to-take-advantage-of.html>
Upvotes: 2 |
2018/03/21 | 750 | 2,835 | <issue_start>username_0: I have two applications A and B which call the same dll (C), in this (C) I have a UC (E) which use another UC (D) as a Popup where is an objectlistview,
When i use E in A everything is ok.
When I use E in B, when E call D I have a BrightIdeasSoftware.MungerException
(see image below) it tells 'try to access to undefined method'
[](https://i.stack.imgur.com/Mdidj.png)<issue_comment>username_1: Did you check if all of the properties of your object are set to public?
See this link:
[Exception when adding list to ObjectListView](https://stackoverflow.com/questions/17107791/exception-when-adding-list-to-objectlistview)
Upvotes: 0 <issue_comment>username_2: This happens when the Model objects you assign to the list i.e using `ListView.SetObjects()` doesn't implement a property or method that the column `AspectNames` are set too or that those properties/methods are declared private.
Makes sure the `AspectName` properties on your Object Listview columns match the properties on your objects and that those properties are declared public.
Upvotes: 1 <issue_comment>username_3: Thank you for answers.
So Finally the problem is solved but i didn't know why and how? so this what happens :
First, before posting my question, I've all ready check that my properties are public and matches with the AspectNames Columns.
Since I didn't understand the source of the problem, and I needed go forward, I've install the dotnetbar2 tool to replace the listbox of objectlistview.
Just after the install of the tool, my visual studio "passed away", no way to view codes, i've got just a black screen, i've become crazy, i didn't understand whats happen, so i decided to uninstal the devnotbar2 tool and use a classic list view of the MS framework. But what happens is strange my problem with the Objectlistview disappear, i've did change anything in my code but there's no more Munger Exception.
Anyone have an explication of what it happens? And how, the install and the uninstall of a tool could change something?
And why my visual studio became crazy after the install of the dotnetbar?
It's very useful tool, and I want to use it but i'm afraid that it make troubles again.
Upvotes: 0 <issue_comment>username_4: The easiest way to figure out which Property/Aspect is causing this is:
1. **Check ON** the Common Language Runtime Exceptions in the Exceptions Settings
[](https://i.stack.imgur.com/aH7nr.png)
2. Place two breakpoints here. MungerException happens at the second breakpoint. Pin `this.AspectName` variable, and see if it reaches the 2nd breakpoint or not.
[](https://i.stack.imgur.com/8SPax.png)
Upvotes: 0 |
2018/03/21 | 753 | 2,770 | <issue_start>username_0: I have a list of numpy arrays. My list contains 5000 numpy arrays and each one has the size (1x1000). I want to construct a numpy array of size 5000x1000. I am trying to do something like:
```
db_array = np.asarray(db_list) # my db_list has 5000 samples of 1x1000 size
```
The result was a matrix of size (5000, 1, 1000). How can I construct a matrix with size (5000, 1000)?<issue_comment>username_1: Did you check if all of the properties of your object are set to public?
See this link:
[Exception when adding list to ObjectListView](https://stackoverflow.com/questions/17107791/exception-when-adding-list-to-objectlistview)
Upvotes: 0 <issue_comment>username_2: This happens when the Model objects you assign to the list i.e using `ListView.SetObjects()` doesn't implement a property or method that the column `AspectNames` are set too or that those properties/methods are declared private.
Makes sure the `AspectName` properties on your Object Listview columns match the properties on your objects and that those properties are declared public.
Upvotes: 1 <issue_comment>username_3: Thank you for answers.
So Finally the problem is solved but i didn't know why and how? so this what happens :
First, before posting my question, I've all ready check that my properties are public and matches with the AspectNames Columns.
Since I didn't understand the source of the problem, and I needed go forward, I've install the dotnetbar2 tool to replace the listbox of objectlistview.
Just after the install of the tool, my visual studio "passed away", no way to view codes, i've got just a black screen, i've become crazy, i didn't understand whats happen, so i decided to uninstal the devnotbar2 tool and use a classic list view of the MS framework. But what happens is strange my problem with the Objectlistview disappear, i've did change anything in my code but there's no more Munger Exception.
Anyone have an explication of what it happens? And how, the install and the uninstall of a tool could change something?
And why my visual studio became crazy after the install of the dotnetbar?
It's very useful tool, and I want to use it but i'm afraid that it make troubles again.
Upvotes: 0 <issue_comment>username_4: The easiest way to figure out which Property/Aspect is causing this is:
1. **Check ON** the Common Language Runtime Exceptions in the Exceptions Settings
[](https://i.stack.imgur.com/aH7nr.png)
2. Place two breakpoints here. MungerException happens at the second breakpoint. Pin `this.AspectName` variable, and see if it reaches the 2nd breakpoint or not.
[](https://i.stack.imgur.com/8SPax.png)
Upvotes: 0 |
2018/03/21 | 931 | 3,578 | <issue_start>username_0: How do we load additional jar at runtime along with boot jar.
**Primary jar**: `Main`.jar
**Additional jar**: `Support`.jar
`Main` project is a gradle boot project.
`Support` project is NOT a gradle project but is given compile time dependencies to the required jars.
Contents of Support project:
```
@RestController
@RequestMapping("/test")
public class CustomService implements WebMvcConfigurer {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public @ResponseBody String get() {
return "Done!!";
}
}
```
What i tried:
```
java -cp Support.jar:Main.jar -Dloader.path=Support.jar -Xbootclasspath/p:alpn-boot-8.1.11.v20170118.jar -Dloader.main=com.abc.app.MyApplication org.springframework.boot.loader.PropertiesLauncher
```
The boot starts up fine but the endpoint is not registered.
NOTE:
I had mentioned annotation scanning.
```
@SpringBootApplication
@ComponentScan("com.abc")
public class MyApplication {
....
}
```
Also the Main.jar will be run from various places by various users. Each user might provide his own version of Support.jar. So, hardcoding the dependency into the gradle file of Main project is not feasible.<issue_comment>username_1: Did you check if all of the properties of your object are set to public?
See this link:
[Exception when adding list to ObjectListView](https://stackoverflow.com/questions/17107791/exception-when-adding-list-to-objectlistview)
Upvotes: 0 <issue_comment>username_2: This happens when the Model objects you assign to the list i.e using `ListView.SetObjects()` doesn't implement a property or method that the column `AspectNames` are set too or that those properties/methods are declared private.
Makes sure the `AspectName` properties on your Object Listview columns match the properties on your objects and that those properties are declared public.
Upvotes: 1 <issue_comment>username_3: Thank you for answers.
So Finally the problem is solved but i didn't know why and how? so this what happens :
First, before posting my question, I've all ready check that my properties are public and matches with the AspectNames Columns.
Since I didn't understand the source of the problem, and I needed go forward, I've install the dotnetbar2 tool to replace the listbox of objectlistview.
Just after the install of the tool, my visual studio "passed away", no way to view codes, i've got just a black screen, i've become crazy, i didn't understand whats happen, so i decided to uninstal the devnotbar2 tool and use a classic list view of the MS framework. But what happens is strange my problem with the Objectlistview disappear, i've did change anything in my code but there's no more Munger Exception.
Anyone have an explication of what it happens? And how, the install and the uninstall of a tool could change something?
And why my visual studio became crazy after the install of the dotnetbar?
It's very useful tool, and I want to use it but i'm afraid that it make troubles again.
Upvotes: 0 <issue_comment>username_4: The easiest way to figure out which Property/Aspect is causing this is:
1. **Check ON** the Common Language Runtime Exceptions in the Exceptions Settings
[](https://i.stack.imgur.com/aH7nr.png)
2. Place two breakpoints here. MungerException happens at the second breakpoint. Pin `this.AspectName` variable, and see if it reaches the 2nd breakpoint or not.
[](https://i.stack.imgur.com/8SPax.png)
Upvotes: 0 |
2018/03/21 | 544 | 1,941 | <issue_start>username_0: I have 2 classes. `Son` inherits from `Dad`. (Note code has been simplified)
```
@interface Dad : NSObject
@interface Son : Dad
```
**Dad Class**
```
- (void)setupSession
{
dadSession = [NSURLSession config:config delegate:self delegateQueue:mainQueue];
// PROBLEM: self == Son, not Dad
}
```
**Son class**
```
- (void)startDadSession
{
[super setupSession];
}
```
then someone somewhere calls...
```
[son startDadSession];
```
I want the Dad class to be its own delegate for its session, but when I call `[super setupSession]` from the `Son` class, when the execution goes into the Dad class `self == Son`.
Is there a way to have `self` not be the instance of the Child class here?<issue_comment>username_1: modify Dad Class's
```
- (void)setupSession
```
with
```
- (void)setupSessionWithDelegate:(id)delegate
```
and
```
dadSession = [NSURLSession config:config delegate:self delegateQueue:mainQueue];
```
with
```
dadSession = [NSURLSession config:config delegate:delegate delegateQueue:mainQueue];
```
Then implement delegate methods.
Upvotes: 0 <issue_comment>username_2: Sadly, inheritance and delegates may sometimes interact in bad ways. Generally I find it hard to write code when a class inherits from another class that is a delegate. But it is necessary from time to time.
One solution I try is to override the delegate methods in the subclass and add a check for the correct instance of`NSURLSession`, or whichever is the correct object. If it is the wrong session, pass it on to the super class implementation. E.g.
```
- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
if (session == self.sonSession) {
// do stuff
} else {
// Unknown session, should be the dadSession so pass it on
[super URLSession:session didBecomeInvalidWithError:error];
}
}
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 1,054 | 3,494 | <issue_start>username_0: I am trying to use the currency pipe in angular to display a whole number price, I don't need it to add .00 to my number, the thing is, its not formatting it according to my instructions.
here is my HTML:
```
##### {{billingInfo.amount | currency:billingInfo.currencyCode:'1.0-0'}} {{billingInfo.period}}
```
here is my ts:
```
ngOnInit() {
this.billingInfo = {amount: 100, currencyCode: 'USD', period: 'Hour'};
}
```
and here is the output:
```
$100.00 Hour
```
things I tried to do:
1.use the decimal number pipe(no good, the currency pipe turns it into a string)
2.add number formater(:1.0-0) to my currencyPipe but it seems to be ignored
what am I missing?<issue_comment>username_1: Best I can tell you're just missing the display parameter which is supposed to be the 2nd parameter to the currency pipe, so if you change it to the following it should work:
```
##### {{billingInfo.amount | currency:billingInfo.currencyCode:'symbol':'1.0-0'}} {{billingInfo.period}}
```
Upvotes: 3 <issue_comment>username_2: To remove `.00` from the currency pipe you can use this pattern. See the digitsInfo section on [CurrencyPipe](https://angular.io/api/common/CurrencyPipe) for more information.
```
{{ amount | currency : 'USD' : 'symbol' : '1.0-0' }}
```
If you don't need the decimal you can use the number pipe.
```
${{amount | number}}
```
Upvotes: 7 <issue_comment>username_3: reference <https://angular.io/api/common/DecimalPipe>
```
##### {{billingInfo.amount |
currency:billingInfo.currencyCode:true:'1.0-0'}} {{billingInfo.period}}
```
Upvotes: 0 <issue_comment>username_4: In Angular, to format a currency, use the currency pipe on a number as shown here.
```
{{amount | currency:'USD':true:'1.2-2'}}
```
* The first parameter, 'USD', of the pipe is an ISO currency code (e.g.
‘USD’,’EUR’, etc.)
* The second parameter, true, is an optional boolean to specify whether
or not you want to render the currency symbol (‘$’, ‘€’); default is
false
* The third parameter,'1.2-2', also optional, specifies how to format
the number, using the same formatting rules as apply to the number
pipe.
Upvotes: 2 <issue_comment>username_5: **Here is my solution:**
```
amount = 5; //or 5.00;
{{ amount | currency: 'USD':true:'2.0' }}
Output would be: 5,
```
if the amount is set to `5.99` then the output would be `5.99`.
You can lean more from angular CurrencyPipe here <https://angular.io/api/common/CurrencyPipe>
Upvotes: 2 <issue_comment>username_6: I was reading through this topic and didn't saw the "perfect" answer if you ask me. The following workaround i used to show the decimals if provided, but strip them if they are unwanted.
```
{{ value | currency: 'EUR':'symbol': (value % 1 == 0) ? '1.0-0': '1.2-2' }}
```
So as you can see the `value % 1 == 0` is a mod functionality that checks if the value is dividable by a whole number. If thats not the case it will return `false`
```
(15.00 % 1 == 0) -> true
(15.50 % 1 == 0) -> false
```
Upvotes: 2 <issue_comment>username_7: For those looking to perform this currency formatting without decimals inside your TypeScript, you can use the CurrencyPipe's transform method like so:
```
import { CurrencyPipe } from '@angular/common';
```
```
constructor(private readonly currencyPipe: CurrencyPipe)
ngOnInit() {
const billingAmount = 100;
this.billingInfo = this.currencyPipe.transform(billingAmount, 'USD', 'symbol', '1.0-0');
}
```
Upvotes: 0 |
2018/03/21 | 2,432 | 9,179 | <issue_start>username_0: I am a newbie in F# and have been following guides to try to make a piece of code work but it hasn't.
I create types of single and coop sports through inheritance.
Then I use pattern matching to know the type and, if it is a coop sport, get also the number of players. Then rank each accordingly.
However, I have been getting errors. I followed Microsoft examples on this and I don't really understand the errors. I don't have a functional programming background.
```
type Sport (name: string) =
member x.Name = name
type Individual(name: string) =
inherit Sport(name)
type Team(name: string, numberOfPlayers : int) =
inherit Sport(name)
member x.numberOfPlayers = numberOfPlayers
let MK = new Individual("Combate Mortal")
let SF = new Individual("Lutadores de Rua")
let Tk = new Individual("<NAME>")
let MvC = new Team("<NAME>", 3)
let Dbz = new Team("<NAME>", 3)
let interpretSport (sport:string) (players:int) =
match sport with
| "Combate Mortal" -> printfn "Rank1"
| "Lutadores de Rua" -> printfn "Rank2"
| "Tekken Chupa" -> printfn "Rank3"
| "<NAME>" -> printfn "Rank4. No of players: %d " players
| "<NAME>" -> printfn "Rank5. No of players: %d" players
| _ -> printfn "not a sport in our list..."
let matchSport (sport:Sport) =
match sport with
| :? Individual -> interpretSport(sport.Name)
| :? Team as teamSport -> interpretSport(teamSport.Name,teamSport.numberOfPlayers)
| _ -> printfn "not a sport"
matchSport(MK)
matchSport(SF)
matchSport(Tk)
matchSport(MvC)
matchSport(Dbz)
```
1st error when calling function with more than 1 argument:
[](https://i.stack.imgur.com/Hhzz5.png)
2nd error when printing:
[](https://i.stack.imgur.com/c9d1b.png)<issue_comment>username_1: Your function `interpretSport` has two arguments but your first call to it has only one. Try calling it like so:
```
| :? Individual -> interpretSport sport.Name 1
```
Also, the second call uses tupled parameters but the function is declared to take curried parameters. Try calling it like so:
```
| :? Team as teamSport -> interpretSport teamSport.Name teamSport.numberOfPlayers
```
Upvotes: 3 <issue_comment>username_2: There are several small problems with your code. The most obvious is in matchSport, you are calling interpretSport in an uncurried style, with an argument tuple. The call should look like:
```
Team as teamSport -> interpretSport teamSport.Name teamSport.numberOfPlayers
```
However, that's a problem, because on the first case of the pattern matching you call `interpretSport` with only one argument, so you partially apply it and you get a type `int -> unit`, but when you fully apply it on the second case you get `unit`, and of course all types of the pattern matching cases must match. The cheapest solution would be to add a `1` to your call on the first case like this:
```
Individual -> interpretSport sport.Name 1
```
But you probably want to use the sports you bound before (maybe in a list you give as a parameter) to do the checking. It is in general a bad idea (in functional programming and elsewhere) to hard-code that many strings, you probably want to do some kind of association List, or Map of the Sports to the Ranks, then fold over the sports List and match when found with individual or team and then print whatever the Map gives you for that case. This would be shorter and more extensible.
Upvotes: 2 <issue_comment>username_3: If this is a F# learning exercise then it's best to avoid classes and inheritance completely. The fundamental idiomatic F# types are records and discriminated unions.
The intent of your code is not clear to me at all, but I have attempted to refactor to remove the use of classes:
```
type Players =
| Individual
| Team of numberOfPlayers:int
type Sport = { Name : string; Players : Players }
let MK = { Name = "<NAME>"; Players = Individual }
let SF = { Name = "Lutadores de Rua"; Players = Individual }
let Tk = { Name = "<NAME>"; Players = Individual }
let MvC = { Name = "<NAME>"; Players = Team 3 }
let Dbz = { Name = "<NAME>"; Players = Team 3 }
let interpretSport (sport:Sport) =
let players =
match sport.Players with
| Individual -> ""
| Team numberOfPlayers -> sprintf ". No of players: %d" numberOfPlayers
let rank =
match sport.Name with
| "<NAME>" -> Some 1
| "Lutadores de Rua" -> Some 2
| "<NAME>" -> Some 3
| "<NAME>" -> Some 4
| "<NAME>" -> Some 5
| _ -> None
match rank with
| Some r -> printfn "Rank%d%s" r players
| None -> printfn "not a sport in our list..."
```
Upvotes: 3 <issue_comment>username_4: The question has already been answered, but because the asker says he is a newby in F#, maybe it's worth to iterate a little.
To begin, you define a function with two parameters:
```
let interpreteSport (sport:string) (player:int) =
```
In F#, there is no notion of optional parameters in the same sense that they exist in C#, so if you declare a function with two parameters, and you want to invoke it, and get its return value, you must supply all the parameters you put in its definition.
So in the first branch of your match expression, when you write:
```
:? Individual -> interpretSport(sport.Name)
```
you are making an error, passing only one parameter to a function that takes two.
But wait! **Why the compiler don't alert you with an error saying you are calling a function with one parameter when it expects two?**
Because it turns out that what you write, even if it does not call the interpreteSport function as you believed, it's a perfect valid expression in F#.
What it returns is an expression called "partially applied function", that is, a function that has received its first parameter, and is waiting for another one.
If you assign the result of such an expression to a value, let's say:
```
let parzFun = interpretSport sport.Name
```
you can then pass this value around in your code and, when you are ready to supply the missing parameter, evaluate it like this:
```
let result = parzFun 1
```
That's what the compiler is telling you when it talks about `'int -> unit'`: function signatures in F# are given in this form:
`a -> b -> c -> d -> retval`, where a, b, c, d etc. are the types of the parameters, and retVal the return value.
Your interpreteSport function has a signature of: `string -> int -> unit`, where `unit` is the special type that means 'no value', similar to C# void, but with the big difference that unit is an expression that you can correctly assign to a value, while void is just a keyword, and you cannot assign a variable to void in C#.
OK, so, when you call your function passing only the first parameter (a string), what you obtain is an expression of type `int -> unit`, that is another function that expects and integer and returns unit.
Because this expression is in a branch of a match expression, and because all the branches of a match expression must return the same type, the other 2 branches are also expected to return an `int -> unit` function, what it's not, and that explain your second error.
More on this in a moment, but before, we must look at the first error reported by the compiler, caused by this line of code:
```
:? Team as teamSport -> interpretSport(teamSport.Name,teamSport.numberOfPlayers)
```
Here, you are thinking your are calling your function with 2 parameters, but your are actually not: when you put 2 values in parenthesis, separated by a comma, you are creating a tuple, that is, a single value composed of two or more values. It's like your are passing again only the first parameter, but now with the wrong type: the first parameter of you function is a string, and you are instead passing a tuple: ('a \* 'b) is how F# represents tuples: that means a single value composed of a value of type 'a (generic, in your case string) and another of type 'b (generic, in your case integer).
To call your function correctly you must call it so:
```
:? Team as teamSport -> interpretSport teamSport.Name teamSport.numberOfPlayers
```
But even if you limit yourself to this correction you will have all the same the second error because, remember, the first expression of your match returns a partially applied funcion, so `int -> unit` (a function that expects an integer and returns a unit) while your second and your third expressions are now of type `unit`, because they actually call two functions that return `unit` (`interpreteSport` and `printfn`). To completely fix your code, as has already been said in other answers, you must supply the missing integer parameter to the first call, so:
```
let matchSport (sport:Sport) =
match sport with
| :? Individual -> interpretSport sport.Name 1
| :? Team as teamSport -> interpretSport teamSport.Name teamSport.numberOfPlayers
| _ -> printfn "not a sport"
```
Upvotes: 4 [selected_answer] |
2018/03/21 | 1,090 | 3,761 | <issue_start>username_0: I want to add multiline text message with proper line breaks that are provided by me.
```
this.sampleStringErrorMsg = 'The sample is not valid:\n' +
'- The key and key value are required in the sample.\n ' +
'- The delimiter must be entered when the sample contains several key-value pairs.\n' +
'- The delimiter must not be equal to the key or key value.\n';
```
`sampleStringErrorMsg` is the text I show in snackbar.
Right now snackbar ommit `\n` from the text and aligns the the whole message as shown in the image below
[](https://i.stack.imgur.com/QYnNl.jpg)<issue_comment>username_1: Your solution is to create a `snackbar` component.
Without seeing your code, I'm guessing you have roughly something like this:
```
this.snackBar.open(this.sampleStringErrorMsg, null, {
verticalPosition: 'top'
});
```
As far as I'm aware, there's no way to achieve what you want by doing like the above.
1. Create a component. I'll call it `ErrorSnackBarComponent`.
On the `html` add the contents of your error message. It will look like something like this:
```html
The sample is not valid:
The key and key value are required in the sample.
The delimiter must be entered when the sample contains several key-value pairs.
The delimiter must not be equal to the key or key value.
```
2. Make sure the `ErrorSnackBarComponent` is referenced in the `app.module.ts` under:
* declarations
* entryComponents
3. Use your recently created `snackbar` component:
>
>
> ```
> this.snackBar.openFromComponent(ErrorSnackBarComponent, {
> verticalPosition: 'top'
> });
>
> ```
>
>
**Extra step**
If you want to pass data to the `ErrorSnackBarComponent`, change your snackbar component's constructor to this:
```
constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) { }
```
and instead of 3., use this:
```
this.snackBar.openFromComponent(ErrorSnackBarComponent, {
verticalPosition: 'top',
data:
});
```
and you should be able to use `data` from the `ErrorSnackBarComponent` and display your error message alongside with any other details such as properties.
[Here is the documentation](https://material.angular.io/components/snack-bar/overview) for `snackbar` for your reference.
Upvotes: 3 <issue_comment>username_2: Coming late to the party ... but I have just had to solve this issue and found that creating a function that 're-builds' the string with newlines in works:
```js
this.snackBar.open(
this.toNewLineString(this.snackBarText), 'Close', {
panelClass: "snack-bar"
});
toNewLineString(input: string) {
var lines = input.split('\\n');
var output = "";
lines.forEach(element => {
output += element + "\n";
});
return output;
}
```
Upvotes: 0 <issue_comment>username_3: I just added `white-space: pre-wrap`
// ts
```
const msg: string = `Registration successful. \n Please, confirm your email`;
this._snackBar.open(msg, '', {
duration: 8000,
panelClass: ['success-snackbar']
});
```
//css
```
.success-snackbar {
background: #1fcd98;
white-space: pre-wrap
}
```
Upvotes: 5 <issue_comment>username_4: My reputation is too low to comment directly. I suggest an addition to [Marias](https://stackoverflow.com/users/13094234/maria-odintsova) [answer](https://stackoverflow.com/a/61404124/3071395).
I am using Angular v7.3.7 and had to add `::ng-deep`, when I placed the CSS in a components CSS file like this
```
::ng-deep .success-snackbar {
background: #1fcd98;
white-space: pre-wrap
}
```
in order for it to work. Alternatively you could add the CSS to the global `styles.css` file of your project.
Upvotes: 2 |
2018/03/21 | 1,354 | 4,744 | <issue_start>username_0: I'm trying to identify user similarities by comparing the keywords used in their profile (from a website). For example, `Alice = pizza, music, movies`, `Bob = cooking, guitar, movie` and `Eve = knitting, running, gym`. Ideally, `Alice` and `Bob` are the most similar. I put down some simple code to calculate the similarity. To account for possible plural/singular version of the keywords I use something like:
```
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
wnl = WordNetLemmatizer()
w1 = ["movies", "movie"]
tokens = [token.lower() for token in word_tokenize(" ".join(w1))]
lemmatized_words = [wnl.lemmatize(token) for token in tokens]
```
So that, `lemmatized_words = ["movie", "movie"]`.
Afterwards, I do some pairwise keywords comparison using [`spacy`](https://spacy.io/usage/vectors-similarity), such as:
```
import spacy
nlp = spacy.load('en')
t1 = nlp(u"pizza")
t2 = nlp(u"food")
sim = t1.similarity(t2)
```
Now, the problem starts when I have to deal with compound words such as: `artificial intelligence`, `data science`, `whole food`, etc. By tokenizing, I would simply split those words into 2 (e.g. `artificial` and `intelligence`), but this would affect my similarity measure. What is (would be) the best approach to take into account those type of words?<issue_comment>username_1: There are many ways to achieve this. One way would be to create the embeddings (vectors) yourself. This would have two advantages: first, you would be able to use bi-, tri-, and beyond (n-) grams as your tokens, and secondly, you are able to define the space that is best suited for your needs --- Wikipedia data is general, but, say, children's stories would be a more niche dataset (and more appropriate / "accurate" if you were solving problems to do with children and/or stories). There are several methods, of course `word2vec` being the most popular, and several packages to help you (e.g. `gensim`).
However, my guess is you would like something that's already out there. The best word embeddings right now are:
* [Numberbatch](https://github.com/commonsense/conceptnet-numberbatch) ('classic' best-in-class ensemble);
* [fastText](https://fasttext.cc/), by Facebook Research (created at the character level --- some words that are out of vocabulary can be "understood" as a result);
* [sense2vec](https://github.com/explosion/sense2vec), by the same guys behind Spacy (created using parts-of-speech (POS) as additional information, with the objective to disambiguate).
The one we are interested in for a quick resolve of your problem is `sense2vec`. You should read the [paper](https://arxiv.org/abs/1511.06388), but essentially these word embeddings were created using Reddit with additional POS information, and (thus) able to discriminate entities (e.g. nouns) that span multiple words. [This blog post](https://explosion.ai/blog/sense2vec-with-spacy) describes `sense2vec` very well. Here's some code to help you get started (taken from the prior links):
Install:
```
git clone https://github.com/explosion/sense2vec
pip install -r requirements.txt
pip install -e .
sputnik --name sense2vec --repository-url http://index.spacy.io install reddit_vectors
```
Example usage:
```
import sense2vec
model = sense2vec.load()
freq, query_vector = model["onion_rings|NOUN"]
freq2, query_vector2 = model["chicken_nuggets|NOUN"]
print(model.most_similar(query_vector, n=5)[0])
print(model.data.similarity(query_vector, query_vector2))
```
Important note, `sense2vec` **requires** `spacy>=0.100,<0.101`, meaning *it will downgrade your current `spacy` install*, not too much of a problem if you are only loading the `en` model. Also, here are the POS tags used:
```
ADJ ADP ADV AUX CONJ DET INTJ NOUN NUM PART PRON PROPN PUNCT SCONJ SYM VERB X
```
You could use `spacy` for POS and dependency tagging, and then `sense2vec` to determine the similarity of resulting entities. Or, depending on the frequency of your dataset (not too large), you could grab n-grams in descending (n) order, and sequentially check to see if each one is an entity in the `sense2vec` model.
Hope this helps!
Upvotes: 1 <issue_comment>username_2: There is approach using nltk:
```
from nltk.tokenize import MWETokenizer
tokenizer = MWETokenizer([("artificial","intelligence"), ("data","science")], separator=' ')
tokens = tokenizer.tokenize("I am really interested in data science and artificial intelligence".split())
print(tokens)
```
The output is given as:
```
['I', 'am', 'really', 'interested', 'in', 'data science', 'and', 'artificial intelligence']
```
For more reference you can read [here](http://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.mwe).
Upvotes: 0 |
2018/03/21 | 1,672 | 4,646 | <issue_start>username_0: In my application I am in need to set different background color to table row based on similar td value which is dynamic data. I tried to achieve this but I was unable to group the table row with different background color. I have attached the expected result screen-cap along with the fiddle link.
[fiddle](https://jsfiddle.net/t5ft82z2/21/)
**HTML CODE**
```
| roll | name | Random number |
| --- | --- | --- |
| 1 | Name 1 | 73023-04041 |
| 2 | Name 2 | 73023-04042 |
| 3 | Name 3 | 73023-04040 |
| 4 | Name 4 | 73023-04042 |
| 5 | Name 5 | 73023-04041 |
```
**JS CODE**
```
$("table tr td:nth-child(2)").each(function () {
var tdVal = $(this).children().find("span").text();
var valueColor = $(this).children().find("span").text();
if (valueColor == tdVal) {
//alert("if");
$(this).parent("tr").addClass("trColor");
}
});
```
**Expected Result**
[](https://i.stack.imgur.com/nh834.png)<issue_comment>username_1: Here is my jsfiddle with working code. You need to give multiple classes in css and assign different colors.
<https://jsfiddle.net/SmitRaval/t5ft82z2/58/>
HTML
----
```
| roll | name | Random number |
| --- | --- | --- |
| 1 | Name 1 | 73023-04041 |
| 2 | Name 2 | 73023-04042 |
| 3 | Name 3 | 73023-04040 |
| 4 | Name 4 | 73023-04042 |
| 5 | Name 5 | 73023-04041 |
```
CSS
---
```
table td {
border:1px solid #000;
}
.trColor0 {
background-color:pink;
}
.trColor1 {
background-color:red;
}
.trColor2 {
background-color:blue;
}
.trColor3 {
background-color:green;
}
.trColor4 {
background-color:yellow;
}
```
JS
--
```
$(document).ready(function(){
var i = 0;
$("table tr td:nth-child(3)").each(function () {
var tdVal = $(this).text();
$("table tr td span").each(function(){
if(tdVal == $(this).text()){
$(this).closest("tr").addClass("trColor"+i);
}
});
i++;
});
});
```
Upvotes: 2 <issue_comment>username_2: You could use a filter in an each loop:
```js
var $lastChildren = $("tbody td:last-child"); // get all last children
var colourCounter = 1;
$lastChildren.each(function() { // loop
var $child = $(this); // get the current child
if (!$child.hasClass('coloured')) { // check if it has already been coloured
var testNumber = $child.text(); // if not get the text
var $filtered = $lastChildren.filter(function() {
return $(this).text() === testNumber; // filter any other children with same text
})
if ($filtered.length) {
$filtered.addClass('coloured') // add class to say it is colored (and not include in further tests)
.parent().addClass('trColor' + colourCounter); // add colour class to row
colourCounter++;
}
}
});
```
```css
/* not sure how you were going to do this colouring - I've used an incremental counter */
.trColor1 {
background-color:green;
}
.trColor2 {
background-color:lightblue;
}
.trColor3 {
background-color:yellow;
}
```
```html
| roll | name | Random number |
| --- | --- | --- |
| 1 | Name 1 | 73023-04041 |
| 2 | Name 2 | 73023-04042 |
| 3 | Name 3 | 73023-04040 |
| 4 | Name 4 | 73023-04042 |
| 5 | Name 5 | 73023-04041 |
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: You can have a look at following a piece of code as well.
Basically, I am creating an object with desired keys with respective Colors associated with them.
```js
var colorMap = {};
$("table tr td:nth-child(3)").each(function () {
var tdVal = $(this).find("span").text();
//alert(tdVal);
if(checkItemExist(tdVal,colorMap) == false)
colorMap[tdVal] = 'trColor'+ (Object.keys(colorMap).length+1)+'';
//alert(JSON.stringify(colorMap));
$(this).parent("tr").addClass(colorMap[tdVal]);
});
function checkItemExist(item,array){
for (var k in array){
if (k == item){
return true;
}
}
return false;
//colorMap.indexOf(tdVal) == -1
}
```
```css
table td{
border:1px solid #000;
}
.trColor1{
background-color:pink;
}
.trColor2{
background-color:red;
}
.trColor3{
background-color:green;
}
.trColor4{
background-color:blue;
}
```
```html
| roll | name | Random number |
| --- | --- | --- |
| 1 | Name 1 | 73023-04041 |
| 2 | Name 2 | 73023-04042 |
| 3 | Name 3 | 73023-04040 |
| 4 | Name 4 | 73023-04042 |
| 5 | Name 5 | 73023-04041 |
```
Upvotes: 1 |
2018/03/21 | 1,027 | 3,305 | <issue_start>username_0: I need to access all elements of a list, but only ever 10 elements at most in one go. For this I thought about a nested loop like this:
```
for (int i = 0; i < 50 / 10; i++) {
for (int k = 0; k < 10; k++) {
paramList.addParam(xyz)
}
sendRequest(paramList);
}
```
With this nested loop I can access all elements from 0-49 and only ever 10 elements in the inner loop. My problem occurs when the list only hast 49 elements instead of 50. Then I only get up to 39 elements with this logic. Also my best thought on only accessing e.g. 5 elements in the last iteration (list size = 45), is to break the loop, before it goes any further.
So my question is, how can I access all elements in a `List` with undefined size, but only a maximum of 10 elements in the inner loop (and less if list size doesn't allow 10)?<issue_comment>username_1: As an option you can just iterate in outer loop using step of 10 elements:
```
int step = 10;
for (int i = 0; i < list.size(); i+=step) {
for (int k = i; k < i + step && k < list.size()); k++) {
System.out.println(list.get(k));
}
}
```
Upvotes: 2 <issue_comment>username_2: as user7 say, you can add a condition to the nested loop
```
for (int i = 0; i < list.size(); i+=10) {
for (int k = i; k < list.size() && (k-i) < 10; k++) {
System.out.println(k);
}
}
```
Upvotes: 2 <issue_comment>username_3: I had to find a reason for your need, breaking the iteration with an inner loop like your snippet doesn't do anything useful, it's still iterate a list.
The only reason I see your logic needed is if you want to call a method after 10 element like :
```
for (int i = 0; i < 50 / 10; i++) {
for (int k = 0; k < 10; k++) {
System.out.println((i * 10) + k);
}
System.out.println("####");
}
```
That would make sense, but that second loop is not needed and also give a "complex" code to understand.
As an alternative, you can iterate normally a list and add a condition to execte that method. It gives a much more readable code
```
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
if( (i + 1)%10 == 0){ //add one to not trigger this on the first iteration
System.out.println("####");
}
}
```
From your comment:
>
> I retrieve up to 50 records from my database. For each record I need to create a request which will be send in a POST request. Each POST request can contain 10 data requests and I can only send 5 of those request per minute (5\*10=50). Since I always fetch TOP 50 data from my database, it can happen that I only get 35 entries instead of 50. To create my requests, I need that data from my database and therefore I have to iterate the whole list, but only ever 10 elements in 1 go to create 1 full POST request
>
>
>
I can see the need here, let's assume you have an instance `post` that have two method `addParam` and `sendRequest`. You need to iterate the list to send `String` parameters :
```
int i = 0;
for(String s : params){
post.addParam(s);
if( ++i % 10 == 0){
post.sendRequest();
}
}
//If the last `addParam` was not sended, we check again.
if( i % 10 != 0){
post.sendRequest();
}
```
Note the condition change outside the loop
Upvotes: 3 [selected_answer] |
2018/03/21 | 844 | 2,771 | <issue_start>username_0: I want to fire some action when there was NO drag event between mouse pressed and released events. In other words - when user kept his mouse cursor still while clicking.
The question is specificly about rective way achive it. Really would appreciate RxJava2 solution (I'm using it with RxJavaFx).<issue_comment>username_1: As an option you can just iterate in outer loop using step of 10 elements:
```
int step = 10;
for (int i = 0; i < list.size(); i+=step) {
for (int k = i; k < i + step && k < list.size()); k++) {
System.out.println(list.get(k));
}
}
```
Upvotes: 2 <issue_comment>username_2: as user7 say, you can add a condition to the nested loop
```
for (int i = 0; i < list.size(); i+=10) {
for (int k = i; k < list.size() && (k-i) < 10; k++) {
System.out.println(k);
}
}
```
Upvotes: 2 <issue_comment>username_3: I had to find a reason for your need, breaking the iteration with an inner loop like your snippet doesn't do anything useful, it's still iterate a list.
The only reason I see your logic needed is if you want to call a method after 10 element like :
```
for (int i = 0; i < 50 / 10; i++) {
for (int k = 0; k < 10; k++) {
System.out.println((i * 10) + k);
}
System.out.println("####");
}
```
That would make sense, but that second loop is not needed and also give a "complex" code to understand.
As an alternative, you can iterate normally a list and add a condition to execte that method. It gives a much more readable code
```
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
if( (i + 1)%10 == 0){ //add one to not trigger this on the first iteration
System.out.println("####");
}
}
```
From your comment:
>
> I retrieve up to 50 records from my database. For each record I need to create a request which will be send in a POST request. Each POST request can contain 10 data requests and I can only send 5 of those request per minute (5\*10=50). Since I always fetch TOP 50 data from my database, it can happen that I only get 35 entries instead of 50. To create my requests, I need that data from my database and therefore I have to iterate the whole list, but only ever 10 elements in 1 go to create 1 full POST request
>
>
>
I can see the need here, let's assume you have an instance `post` that have two method `addParam` and `sendRequest`. You need to iterate the list to send `String` parameters :
```
int i = 0;
for(String s : params){
post.addParam(s);
if( ++i % 10 == 0){
post.sendRequest();
}
}
//If the last `addParam` was not sended, we check again.
if( i % 10 != 0){
post.sendRequest();
}
```
Note the condition change outside the loop
Upvotes: 3 [selected_answer] |
2018/03/21 | 325 | 1,300 | <issue_start>username_0: I am able to connect, pass the data to MQ , but not able to retrieve data from MQ. On some base level analysis I found out that the only difference between successful messages and unsuccessful one is the 'Handle State' column;
[](https://i.stack.imgur.com/2cQ2k.png)
which is inactive for failed cases and 'Active' for successful cases.<issue_comment>username_1: Handle State indicates if an API call is in progress. You would only see this as Active if the application has issued a GET with wait and the GET has not completed because no messages are available. In the screen shot both handles show Input Shared, but only one has Output Yes, if the handle with Output Yes is the process putting to the queue then it would be normal for you to see the Handle State as Inactive.
<NAME> wrote a great blog on this subject that I would suggest you review:
[IBM MQ Little Gem #32: HSTATE](https://www.imwuc.org/blog/ibm-mq-little-gem-32-hstate)
Upvotes: 0 <issue_comment>username_2: Handle state shows 'Inactive' when the request text for that specific queue backend logic doesnot match the required syntax. It started to be in 'Active' once the data format was corrected
Upvotes: -1 [selected_answer] |
2018/03/21 | 999 | 3,284 | <issue_start>username_0: I tried
```
find "$1" -print | grep -i '.*[.]c' | sort
```
to find out all the files in a folder that have .c file extensions.
1) But I also need to printout each c file`s content. For example, assuming that there are "practice.c" and "practice\_1.c" files in test folder,
```
test/practice.c:
void function(int loc)
int function1()
test/practice_1.c:
void function2()
char function3(char locc)
```
like this... I have to print out only the function names, not all the contents.
If I use -exec cat, it prints out all of its contents so I am stuck here.
-----------------------edit --------------------------------------
```
find "$1" -type f -name *.c -exec echo {} \; -exec grep "(*)" {} \; | sed 's/{//g'
```
When I use the above code, this prints out as
```
test/practice.c
void function(int loc)
int function1()
test/practice_1.c
void function2()
char function3(char locc)
```
How can I make it to output as:
```
test/practice.c:
void function(int loc)
int function1()
test/practice_1.c:
void function2()
char function3(char locc)
```
(need to add semicolon after the file name and also a new line after a one file display is done...)<issue_comment>username_1: Finding C Files
===============
First of all, don't grep `find`'s output. You can use `find`'s `-iname` option instead. To also allow filenames with newlines in them use `-print0` instead of `-print`.
```
find "$1" -iname '*.c' -print0 | sort -z
```
But there's an even better way: `bash`'s globstar (see **Putting Things Together**).
Print Functions
===============
In this case it would be better to use a dedicated program instead of hacking something together. [`ctags -x`](https://man.openbsd.org/ctags) or [`cscope`](http://cscope.sourceforge.net/cscope_man_page.html) seem to be up for the job. `ctags` output relies on the formatting of your files, so we auto-format them using `indent`.
To print the function definitions from one file as in your example use the following function:
```
printFunctions() {
printf "%s:\n\n" "$1" # filename at the top
indent -l0 -npsl < "$1" > tmp.c
ctags -x tmp.c |
awk '$2 == "function"' |
tr -s ' ' |
cut -d' ' -f5-
rm tmp.c
echo # empty line at the end
}
```
Putting Things Together
=======================
```
short -s globstar
for cfile in **/*.c; do
printFunctions "$cfile"
done
```
Upvotes: 1 <issue_comment>username_2: try this one. if this fulfills your criteria.
```
find "$1" -type f -name *.c -exec echo {}":" \; -exec grep "(*)" {} \; |sed 's/{//g' | awk '{if(($0~/:/)&&(NR>1)){$0="\n"$0};print}'
```
`find "$1" -type f -name *.c -exec echo {}":" \;` ###this will find all the .c files in $1 folder. so \*.c means file names ending with .c and it also append : in filenames in output.
`-exec grep "(*)" {} \;` ###this will grep within the files searched for line having ( and ) both round brackets which we use in command c function syntax
`| sed 's/{//g'` ###all the things searched are piped to this sed command. As the function name has { after their name declaration so removing it here
`awk '{if($0~/:/){$0="\n"$0};print}'` ###here we are appending \n in the start of line which contains :
Upvotes: 1 [selected_answer] |
2018/03/21 | 861 | 2,806 | <issue_start>username_0: I got a situation like this:
```js
var orders = [
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];
const bill = document.querySelector("#ordersListed");
for(var x in orders) {
bill.innerHTML += orders[x].order;
}
```
```html
Document
```
Each time I click a button, an item gets added to the array.
I've been trying to loop through the array to print each *order* in a HTML element.
Should show up in the div as:
>
> string describing the first order
>
> string describing the second order
>
>
>
My results:
>
> first order
>
> first order
>
> second order
>
>
><issue_comment>username_1: `for...in` is for iterating over `Object` properties, not for `Array`. Use `for...of`:
```js
var orders = [{ ID: "sampleID1", order: "string describing the first order" }, { ID: "sampleID2", order: "string describing the second order" }]
for (order of orders) {
let para = document.createElement('p')
para.textContent = order.order
ordersListed.appendChild(para)
}
```
```css
#ordersListed {
background: #f8f8f8;
border: 4px dashed #ddd;
padding: 5px 15px;
}
```
**Note**: I prefer to create real DOM Nodes so I can easily add attributes and attach event handlers. In the second example I show adding title and alerting the order ID on click:
```js
var orders = [{ ID: "sampleID1", order: "string describing the first order" }, { ID: "sampleID2", order: "string describing the second order" }]
for (order of orders) {
let para = document.createElement('p')
para.textContent = order.order
para.title = order.ID
para.addEventListener('click', function() { alert(this.title) })
ordersListed.appendChild(para)
}
```
```css
#ordersListed {
background: #f8f8f8;
border: 4px dashed #ddd;
padding: 5px 15px;
}
#ordersListed p {
cursor: pointer;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: How about:
```
var orders = [
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];
for (var i = 0; i < orders.length; i++ ) {
orderListContainer.textContent += orders[i]['order'];
}
```
As far as I can see you were appending the array element instead of the correct property to the array element.
Upvotes: 0 <issue_comment>username_3: Just adding a to the `innerHTML` in each iteration of Array's `forEach()` will do the trick:
```js
var orders = [
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];
const bill = document.querySelector("#ordersListed");
orders.forEach(o => bill.innerHTML += o.order + '
');
```
Upvotes: 2 |
2018/03/21 | 993 | 3,265 | <issue_start>username_0: I've been trying to do a renamer program in c# for 2 different paths and I keep getting error "Path includes invalid characters" I have no clue how to fix it, I've tried adding @ and deleting \ and keeping only one . But still didn't figure out how to fix it. Would love any help.
This is what gives me an error:
```
if (French.Checked)
{
directoryfile = @"C:\Users\" + curruser + @"\Appdata\Local\fo4renamer\directory.txt";
label1.Text = directoryfile;
readpath = File.ReadAllText(directoryfile);
string shouldwork = readpath + "data";
string french = shouldwork + "\\french";
string german = shouldwork + "\\german";
string tmp = shouldwork + "tmp.txt";
label1.Text = french;
string path2 = @"C:\Users\duchacekda\Desktop\e\Renamer\Renamer\bin\Debug\tmp.txt";
string filename = @"C:\Users\duchacekda\Desktop\e\Renamer\Renamer\bin\Debug\french.txt";
File.Move(french, german);
}
```
Here is the whole code:
<https://pastebin.com/0i7fzh24>
Edit: this is the string for curruser
`string curruser = System.Environment.UserName;`
The exception was given by this line
```
File.Move(french, german);
```<issue_comment>username_1: `for...in` is for iterating over `Object` properties, not for `Array`. Use `for...of`:
```js
var orders = [{ ID: "sampleID1", order: "string describing the first order" }, { ID: "sampleID2", order: "string describing the second order" }]
for (order of orders) {
let para = document.createElement('p')
para.textContent = order.order
ordersListed.appendChild(para)
}
```
```css
#ordersListed {
background: #f8f8f8;
border: 4px dashed #ddd;
padding: 5px 15px;
}
```
**Note**: I prefer to create real DOM Nodes so I can easily add attributes and attach event handlers. In the second example I show adding title and alerting the order ID on click:
```js
var orders = [{ ID: "sampleID1", order: "string describing the first order" }, { ID: "sampleID2", order: "string describing the second order" }]
for (order of orders) {
let para = document.createElement('p')
para.textContent = order.order
para.title = order.ID
para.addEventListener('click', function() { alert(this.title) })
ordersListed.appendChild(para)
}
```
```css
#ordersListed {
background: #f8f8f8;
border: 4px dashed #ddd;
padding: 5px 15px;
}
#ordersListed p {
cursor: pointer;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: How about:
```
var orders = [
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];
for (var i = 0; i < orders.length; i++ ) {
orderListContainer.textContent += orders[i]['order'];
}
```
As far as I can see you were appending the array element instead of the correct property to the array element.
Upvotes: 0 <issue_comment>username_3: Just adding a to the `innerHTML` in each iteration of Array's `forEach()` will do the trick:
```js
var orders = [
{ID: "sampleID1", order: "string describing the first order"},
{ID: "sampleID2", order: "string describing the second order"}
];
const bill = document.querySelector("#ordersListed");
orders.forEach(o => bill.innerHTML += o.order + '
');
```
Upvotes: 2 |
2018/03/21 | 791 | 3,029 | <issue_start>username_0: What is the simplest way to perform a git pull request via CLI. I am tired of going to Bitbucket the whole time to create a pull request manually. Which is quite simple indeed:
1. Pull requests tab
2. Create pull request
3. Select source and destiny branches (edit comments, reviewers, etc)
4. Confirm
Pretty simple. How can I achieve this behavior through cli?
Let's say, in my teams' repository, I want to perform a PR from `develop` to `master` branch.
I have been checking [documentation](https://git-scm.com/docs/git-request-pull) and it doesn't seem so obvious. It asks me to choose a starting commit and, in the previous steps I described, I don't even get the chance to choose which commit should the PR start from.<issue_comment>username_1: You could use a command line tool like [curl](https://curl.haxx.se/) on the [bitbucket rest api](https://developer.atlassian.com/bitbucket/api/2/reference/). How to create a pull request with `HTTP POST` [is documented here](https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/pullrequests#post).
Give it a try:
```
curl \
-X POST \
-H "Content-Type: application/json" \
-u username:password \
https://bitbucket.org/api/2.0/repositories/account/reponame/pullrequests \
-d @pullrequest.json
```
with file `pullrequest.json` containing
```
{
"title": "Merge some branches",
"description": "stackoverflow example",
"source": {
"branch": {
"name": "mybranchToMerge"
},
"repository": {
"full_name": "account/reponame"
}
},
"destination": {
"branch": {
"name": "master"
}
},
"reviewers": [ { "username": "reviewerUsername" } ],
"close_source_branch": false
}
```
For more options look here:
[Bitbucket: Send a pull request via command line?](https://stackoverflow.com/questions/8721730/bitbucket-send-a-pull-request-via-command-line)
More about `git request-pull` can be found here:
[Difference between 'git request-pull' and 'pull request'](https://stackoverflow.com/questions/49423624)
Upvotes: 2 <issue_comment>username_2: Probably the answer to your question is disappointing, as `Pull Requests` are not a native feature of git they are not supported through the CLI or any other standard `git` tool. Additionally there is no standard protocol for `Pull Requests` even outside of standard `git`. Each platform (`GitLab`, `GitHub` etc.) provides its own flavor of `Pull Requests`.
Since you question is about `Pull Requests` in general and not about `Pull Requests` on a specific provider the answer is that it cannot be done.
Upvotes: 1 <issue_comment>username_3: If you are using bitbucket enterprise, i prepared a script to create/delete pull requests - <https://github.com/username_3/bbcli>.
It also handles adding of default reviewers automatically to your PR which is configured in your repo settings.
Upvotes: 0 |
2018/03/21 | 977 | 2,407 | <issue_start>username_0: Given is a dataframe with the vectors x1 and y1:
```
x1 <- c(1,1,2,2,3,4)
y1 <- c(0,0,1,1,2,2)
df1 <- data.frame(x1,y1)
```
Also, I have a dataframe with the different values from the vector y1 and a corresponding probability:
```
y <- c(0,1,2)
p <- c(0.1,0.6,0.9)
df2 <- data.frame(y,p)
```
The following function compares a given probability (p) with a random number (runif(1)). Based on the result of the comparison, the value of df$x1 changes and is stored in df$x2 (for each value of x1 a new random number has to be drawn):
```
example_function <- function(x,p){
if(runif(1) <= p) return(x + 1)
return(x)
}
set.seed(123)
df1$x2 <- unlist(lapply(df1$x1,example_function,0.5))
> df1$x2
[1] 2 1 3 2 3 5
```
Here is my problem: In the example above I chose 0.5 for the argument "p" (manually). Instead, I would like to select a probability p from df2 based on the values for y1 associated with x1 in df1. Accordingly, I want p in
```
df1$x2 <- unlist(lapply(df1$x1,example_function,p))
```
to be derived from df2.
For example, df$x1[3], which is a 2, belongs to df$y1[3], which is a 1. df2 shows, that a 1 for y is associated with p = 0.6. In that case, the argument p for df1$x1[3] in "example\_function" should be 0.6. How can this kind of a query for the value p be integrated into the described function?<issue_comment>username_1: There is no need to do anything complicated here. You can get what you want using vector-expressions.
To pick your probabilities given `p` and `y1`, simply subscript:
```
> p[y1]
[1] 0.1 0.1 0.6 0.6
```
and then pick your `x2` from `x1` and the sample like this:
```
> ifelse(runif(1) <= p[y1], x1, x1 + 2)
[1] 3 4 3 4
```
Upvotes: 1 <issue_comment>username_2: ```
df1$x2 <- unlist(lapply(df1$x1,
function(z) {
example_function(z, df2$p[df2$y == df1$y1[df1$x1 == z][1])
}))
df1
# x1 y1 x2
# 1 1 0 1
# 2 2 0 2
# 3 3 1 4
# 4 4 1 4
# 5 5 2 6
# 6 6 2 7
```
Upvotes: 1 <issue_comment>username_3: One way to solve the problem is working with "merge" and "mapply" instead of "lapply":
```
df_new <- merge(df1, df2, by.x = 'y1', by.y = 'y')
set.seed(123)
df1$x2 <- mapply(example_function,df1$x1,df_new$p)
> df1
x1 y1 x2
1 1 0 1
2 1 0 1
3 2 1 3
4 2 1 2
5 3 2 3
6 4 2 5
```
Upvotes: 1 [selected_answer] |
2018/03/21 | 481 | 1,524 | <issue_start>username_0: I'm making sparklines next to bar charts but trying to get the positioning right.
The bars are set out with d3.scaleBand().paddingInner(0.1)
I'm translating the line paths by y.bandwidth() which gets me close (see below).
It looks like it needs to add a bit more for the padding. How much is the padding? It's set at 0.1 but 0.1 of what? How do I find out the padding in pixel to add to the translate?
[](https://i.stack.imgur.com/h5y6f.png)
Code is currently at <https://github.com/henryjameslau/new-trade-map/blob/master/worldmap/index2.html><issue_comment>username_1: The padding function allows you to set padding between the bands, and above and below, as seen below in the documentation.
[](https://i.stack.imgur.com/E8rUS.png)
My suggestion would be to add whatever padding you need to your y translation.
Upvotes: 0 <issue_comment>username_2: After reading the readme for [d3-scale](https://github.com/d3/d3-scale/blob/master/README.md#band_paddingOuter) it says
>
> The inner padding determines the ratio of the range that is reserved
> for blank space between bands.
>
>
>
so the answer is 0.1 of the range which is set in d3.scaleBand
I am now translating the paths by i\*(y.bandwidth()+0.1\*y.bandwidth())+0.05\*y.bandwidth()
[](https://i.stack.imgur.com/faYJj.png)
Upvotes: 2 |
2018/03/21 | 657 | 2,574 | <issue_start>username_0: A simple example to illustrate the problem:
1 - Here, does the program exits after the future is completed ?
```
def main(args: Array[String]): Unit = {
val future: Future[Unit] = myFunction()
}
```
2 - If not, should I had an `Await` to guarantee that the future terminates?
```
def main(args: Array[String]): Unit = {
val future: Future[Unit] = myFunction()
Await.result(future, Inf)
}
```<issue_comment>username_1: Reading [this](https://docs.scala-lang.org/overviews/core/futures.html) about Futures/Promises in Scala, the point is: it is **not** the Future that is about *concurrency*.
Meaning: what prevents the JVM from *exiting* are running threads. Coming from there: unless *something* in your code creates an additional thread that somehow prevents the JVM from exiting, your `main()` should simply end.
Futures are a mean to interact with content which becomes available at some later point in time. You should rather look into your code base to determine what kind of threading comes in place, and for example if some underlying thread pool executor is configured regarding the threads it is using.
Upvotes: 3 [selected_answer]<issue_comment>username_2: A `future` is value that is returned after executing a piece of task independently by a new thread(mostly) spawned by the another thread(say main).
To answer your question **Yes** the main thread will exit even if any `future` is still under execution.
```
import scala.concurrent._
import ExecutionContext.Implicits.global
object TestFutures extends App{
def doSomeOtherTask = {
Thread.sleep(1000) //do some task of 1 sec
println("Completed some task by "+Thread.currentThread().getName)
}
def returnFuture : Future[Int]= Future{
println("Future task started "+Thread.currentThread().getName)
Thread.sleep(5000) //do some task which is 5 sec
println("Future task completed "+Thread.currentThread().getName)
5
}
val x = returnFuture //this takes 5 secs
doSomeOtherTask // ~ 1 sec job
println(x.isCompleted)
doSomeOtherTask // ~ 2 sec completed
println(x.isCompleted)
doSomeOtherTask // ~ 3 sec completed
println(x.isCompleted)
println("Future task is still pending and main thread have no more lines to execute")
}
```
Output:-
--------
```
Future task started scala-execution-context-global-11
Completed some task by main
false
Completed some task by main
false
Completed some task by main
false
Future task is still pending and main thread have no more lines to execute
```
Upvotes: 2 |
2018/03/21 | 929 | 3,416 | <issue_start>username_0: I have dataset that consist of hundreds of column, and thousands of row
```
In [119]:
df.columns
Out[119]:
Index(['column 1', 'column2',
...
'column 100'],
dtype='object', name='var_name')
```
Usually I did `value_counts()` for every single column to see the distribution.
```
In [121]:
a = df['column1'].value_counts()
In [122]:
a
Out[122]:
1 77494
2 5389
0 2016
3 878
Name: column 1, dtype: int64
```
But for this dataframe, if I did this for every columns, this will make my notebook very messy, how to automate this? Is there any function that help?
If you have other information, all my data is `int64`, but I hope the best answer can give solution that works in every cases. I want to make the solution answer in pandas dataframe.
Based on @MaxU suggestion, this is my version of simplified dataframe
```
df
id column1 column2 column3
1 3 1 7
2 3 2 8
3 2 3 7
4 2 1 8
5 1 2 7
```
and my expected output is:
```
column 1 count
1 1
2 2
3 2
column 2 count
1 2
2 2
3 1
column 3 count
7 3
8 2
3 1
```<issue_comment>username_1: Reading [this](https://docs.scala-lang.org/overviews/core/futures.html) about Futures/Promises in Scala, the point is: it is **not** the Future that is about *concurrency*.
Meaning: what prevents the JVM from *exiting* are running threads. Coming from there: unless *something* in your code creates an additional thread that somehow prevents the JVM from exiting, your `main()` should simply end.
Futures are a mean to interact with content which becomes available at some later point in time. You should rather look into your code base to determine what kind of threading comes in place, and for example if some underlying thread pool executor is configured regarding the threads it is using.
Upvotes: 3 [selected_answer]<issue_comment>username_2: A `future` is value that is returned after executing a piece of task independently by a new thread(mostly) spawned by the another thread(say main).
To answer your question **Yes** the main thread will exit even if any `future` is still under execution.
```
import scala.concurrent._
import ExecutionContext.Implicits.global
object TestFutures extends App{
def doSomeOtherTask = {
Thread.sleep(1000) //do some task of 1 sec
println("Completed some task by "+Thread.currentThread().getName)
}
def returnFuture : Future[Int]= Future{
println("Future task started "+Thread.currentThread().getName)
Thread.sleep(5000) //do some task which is 5 sec
println("Future task completed "+Thread.currentThread().getName)
5
}
val x = returnFuture //this takes 5 secs
doSomeOtherTask // ~ 1 sec job
println(x.isCompleted)
doSomeOtherTask // ~ 2 sec completed
println(x.isCompleted)
doSomeOtherTask // ~ 3 sec completed
println(x.isCompleted)
println("Future task is still pending and main thread have no more lines to execute")
}
```
Output:-
--------
```
Future task started scala-execution-context-global-11
Completed some task by main
false
Completed some task by main
false
Completed some task by main
false
Future task is still pending and main thread have no more lines to execute
```
Upvotes: 2 |
2018/03/21 | 634 | 2,158 | <issue_start>username_0: `if ! /usr/bin/getent passwd sgate>/dev/null; then
%define bindir /home/sgate/elasticsearch
elif ! /usr/bin/getent passwd rgate>/dev/null; then
%define bindir /home/rgate/elasticsearch
fi`
RPM build errors:
```
File must begin with "/": if
File must begin with "/": !
Two files on one line: /usr/bin/getent
File must begin with "/": passwd
Two files on one line: /usr/bin/getent
File must begin with "/": sgate>/dev/null;
Two files on one line: /usr/bin/getent
File must begin with "/": the
File not found: /root/ES_RPM/ElasticSearchRPM/BUILDROOT/elasticsearch-5.2.2-1.x86_64/home/*/elasticsearch
File must begin with "/": elif
File must begin with "/": !
Two files on one line: /usr/bin/getent
File must begin with "/": passwd
Two files on one line: /usr/bin/getent
File must begin with "/": rgate>/dev/null;
Two files on one line: /usr/bin/getent
File must begin with "/": then
File not found: /root/ES_RPM/ElasticSearchRPM/BUILDROOT/elasticsearch-5.2.2-1.x86_64/home/*/elasticsearch
File must begin with "/": fi
```
I am getting this error while running RPM. Where am I going wrong with this if logic?<issue_comment>username_1: The `%define`s that you have there are not doing that you think; they are defining things and then leaving behind invalid shell code. You are probably going to need a wrapper shell or `Makefile` that calls `rpmbuild` with a definition of "`mybindir`" on the command line, *e.g.* `rpmbuild --define="mybindir /home/rgate/elasticsearch"`
**Having re-read the question**, what you are trying to do seems to be an install-time thing anyway, which you cannot decide on-the-fly like that. I would say install your stuff in a standard location, *e.g.* `/usr/share/yourpackage`, and then in the `%post` set a symlink to it in the proper user's home directory. In `%post` you are allowed to script things to do what you were expecting.
Upvotes: 0 <issue_comment>username_2: You cannot use shell script in `%files` section. You can use macros, e.g.:
```
%if
...
%endif
```
But those macros conditionals are evaluated during build time and not during installation.
Upvotes: 3 [selected_answer] |
2018/03/21 | 1,208 | 3,672 | <issue_start>username_0: This is data collected from a survey where there was a radio button to select from 1 of 5 choices. What is stored in the column is a simple 1 as a flag to say it was selected.
I am wanting to end up with a single column with the column headers as the values. Someone suggested using the IDXMAX method on my dataframe, but when I looked at the docs I couldn't really figure out how to apply it. It does look like it would be useful for this though...
I have a dataframe:
```
old = pd.DataFrame({'a FINSEC_SA' : [1,'NaN','NaN','NaN','NaN',1,'NaN'],
'b FINSEC_A' : ['NaN',1,'NaN','NaN','NaN','NaN','NaN'],
'c FINSEC_NO' : ['NaN','NaN',1,'NaN','NaN','NaN','NaN'],
'd FINSEC_D' : ['NaN','NaN','NaN',1,'NaN','NaN',1],
'e FINSEC_SD' : ['NaN','NaN','NaN','NaN',1,'NaN','NaN']})
```
[](https://i.stack.imgur.com/fc23D.png)
I would like to end up with a dataframe like this:
```
new = pd.DataFrame({'Financial Security':['a FINSEC_SA','b FINSEC_A',
'c FINSEC_NO','d FINSEC_D','e FINSEC_SD','a FINSEC_SA','d FINSEC_D']})
```
[](https://i.stack.imgur.com/0GARz.png)
I only have about 65k rows of data so performance is not top of list for me. I am most interested in learning a good way to do this - that is hopefully fairly simple. It would be really nice if the idxmax does this fairly easily.<issue_comment>username_1: You can directly use `idxmax` followed by `reset_index` to achieve this.
```
df = old.idxmax(axis=1).reset_index().drop('index', axis=1).rename(columns={0:'Financial'})
print(df)
Financial
0 a FINSEC_SA
1 b FINSEC_A
2 c FINSEC_NO
3 d FINSEC_D
4 e FINSEC_SD
5 a FINSEC_SA
6 d FINSEC_D
```
**Explanation:**
1. `idxmax` select max. value row wise across columns.
2. `drop` drops the unwanted column followed by removing `duplicate` values.
3. Finally, we `rename` the column as required.
Upvotes: 1 <issue_comment>username_2: idxmax can only work with numerics. So first, we need to convert 'NaN' (a string) to np.NaN (a numeric value). Then we can convert each column into a numerical series:
```
old = old.replace('NaN', np.NaN)
old = old.apply(pd.to_numeric)
```
alternatively you can do this in one line with:
```
old = old.apply(pd.to_numeric, errors='coerce')
```
finally, we can run idxmax. All you have to do is specify the axis. axis=1 to get the position of 1 (highest value) in each row, axis=0 to get the position of 1 in each column
```
new = old.idxmax(axis=1)
```
You can run the code in one line (if you don't need a copy of old after this):
```
new = old.apply(pd.to_numeric, errors='coerce').idxmax(axis=1)
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: In the code below, I created a function to check NaN separately, as I think in real data you will have np.NaN and not 'NaN' (strings). You can modify the string accordingly
```
def isNaN(num):
return num == 'NaN'
def getval(x):
if not isNaN(x['a FINSEC_SA']) : return 'a FINSEC_SA'
if not isNaN(x['b FINSEC_A']) : return 'b FINSEC_A'
if not isNaN(x['c FINSEC_NO']) : return 'c FINSEC_NO'
if not isNaN(x['d FINSEC_D']) : return 'd FINSEC_D'
if not isNaN(x['e FINSEC_SD']) : return 'e FINSEC_SD'
old.apply(getval, axis=1)
```
This is readable but not efficient answer. Melt functionality can be used to get the same answer in much more efficient manner -
```
old['id'] = old.index
new = pd.melt(old, id_vars= 'id', var_name = 'Financial')
new = new[new['value'] != 'NaN'].drop('value', axis=1).sort_index(axis=0)
```
Upvotes: 1 |
2018/03/21 | 1,116 | 3,599 | <issue_start>username_0: I am currently, going through this [great article on Y-combinator](https://mvanier.livejournal.com/2897.html) by [<NAME>](http://users.cms.caltech.edu/~mvanier/). Along the explanation the following line is dropped:
>
> It turns out that any let expression can be converted into an equivalent lambda expression using this equation:
>
>
> `(let ((x )) )
> ==> ((lambda (x) ) )`
>
>
>
The article illustrates this statement by converting:
```
(define (part-factorial self)
(let ((f (self self)))
(lambda (n)
(if (= n 0)
1
(* n (f (- n 1)))))))
```
to:
```
(define (part-factorial self)
((lambda (f)
(lambda (n)
(if (= n 0)
1
(* n (f (- n 1))))))
(self self)))
```
Now, I understand how and why two code snippets above are identical, though I can't get my head around the fact that general equation for converting `let` to `lambda` is:
```
(let ((x )) )
==> ((lambda (x) ) )
```
I'd appreciate the elaborate explanation.<issue_comment>username_1: I've ended up figuring it out myself =).
The point that I was missing is that in:
```
(let ((x )) )
==> ((lambda (x) ) )
```
`x` is present, somewhere, inside , so it's more like:
```
(let ((x )) )
==> ((lambda (x) ) )
```
With that being said, if we will substitute `x` for `f` in:
```
(define (part-factorial self)
(let ((f (self self)))
(lambda (n)
(if (= n 0)
1
(* n (f (- n 1)))))))
```
as well as in:
```
(define (part-factorial self)
((lambda (f)
(lambda (n)
(if (= n 0)
1
(* n (f (- n 1))))))
(self self)))
```
and will highlight `x`, and with different colors, the conversion formula should become clear then:
[](https://i.stack.imgur.com/23cAO.png)
Upvotes: 3 <issue_comment>username_2: You should imagine having a very little lisp language that has `lambda` but not `let`. You want to do:
```
(let ((nsq (square n)))
(+ nsq nsq))
```
You know that `nsq` is a new variable and that the body of the `let` could be made a function:
```
(lambda (nsq) (+ nsq nsq))
```
Then you need to use that to get the same value:
```
((lambda (nsq) (+ nsq nsq)) (square n))
```
Imagine that your simple scheme has macros and thus, you implement as `let`:
```
(define-syntax let
(syntax-rules ()
[(let ((binding value) ...)
body ...)
((lambda (binding ...)
body ...)
value ...)]))
```
Note, that in many implementations this actually happens exactly this way.
Upvotes: 3 <issue_comment>username_3: `let` lets you open a new environment in which variables are available. In programming language terms we say it "opens a new frame".
When you write `(let ((x 42)) )` you create a frame in which `x` is available inside , and assign it the value `42`.
Well, there is another tool that lets you open new frames. In fact, it's usually the basic brick with which you can build more abstract constructs: it is called `lambda`.
`lambda` opens a new frame in which its arguments are available to its body.
When you write `(lambda (x) )` you make `x` available to the of the function.
The only difference between `lambda` and `let` is that `let` immediately assigns a value to `x`, while `lambda` awaits the value as an argument.
Therefore, if you want to wrap a with a directly assigned value using `lambda`, you just have to pass that value!
```
((lambda (x) ) 42)
```
Which makes it exactly equivalent to:
```
(let ((x 42)) )
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 1,040 | 3,563 | <issue_start>username_0: I have managed to display a marker on the map in the current position and everytime I'm moving the camera is following me. I get the device current location every 1000 milliseconds like this:
```
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
```
When I'm using my app inside my car, my current location update is not animating like Google Map app does, is jumping from one point to another.
How can I get a smooth animation when the current location is changing? I'm not interested in having a method that uses a `LatLng startPosition` and a `LatLng destination`, I just want to have a nice user experience when moving.
This my method that helps me move the camera:
```
private void moveCamera(LatLng latLng, float zoom) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
```<issue_comment>username_1: I've ended up figuring it out myself =).
The point that I was missing is that in:
```
(let ((x )) )
==> ((lambda (x) ) )
```
`x` is present, somewhere, inside , so it's more like:
```
(let ((x )) )
==> ((lambda (x) ) )
```
With that being said, if we will substitute `x` for `f` in:
```
(define (part-factorial self)
(let ((f (self self)))
(lambda (n)
(if (= n 0)
1
(* n (f (- n 1)))))))
```
as well as in:
```
(define (part-factorial self)
((lambda (f)
(lambda (n)
(if (= n 0)
1
(* n (f (- n 1))))))
(self self)))
```
and will highlight `x`, and with different colors, the conversion formula should become clear then:
[](https://i.stack.imgur.com/23cAO.png)
Upvotes: 3 <issue_comment>username_2: You should imagine having a very little lisp language that has `lambda` but not `let`. You want to do:
```
(let ((nsq (square n)))
(+ nsq nsq))
```
You know that `nsq` is a new variable and that the body of the `let` could be made a function:
```
(lambda (nsq) (+ nsq nsq))
```
Then you need to use that to get the same value:
```
((lambda (nsq) (+ nsq nsq)) (square n))
```
Imagine that your simple scheme has macros and thus, you implement as `let`:
```
(define-syntax let
(syntax-rules ()
[(let ((binding value) ...)
body ...)
((lambda (binding ...)
body ...)
value ...)]))
```
Note, that in many implementations this actually happens exactly this way.
Upvotes: 3 <issue_comment>username_3: `let` lets you open a new environment in which variables are available. In programming language terms we say it "opens a new frame".
When you write `(let ((x 42)) )` you create a frame in which `x` is available inside , and assign it the value `42`.
Well, there is another tool that lets you open new frames. In fact, it's usually the basic brick with which you can build more abstract constructs: it is called `lambda`.
`lambda` opens a new frame in which its arguments are available to its body.
When you write `(lambda (x) )` you make `x` available to the of the function.
The only difference between `lambda` and `let` is that `let` immediately assigns a value to `x`, while `lambda` awaits the value as an argument.
Therefore, if you want to wrap a with a directly assigned value using `lambda`, you just have to pass that value!
```
((lambda (x) ) 42)
```
Which makes it exactly equivalent to:
```
(let ((x 42)) )
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 1,835 | 6,103 | <issue_start>username_0: I have a checkbox list which consists of 13 different values, and i am trying to use jquery to disable all of them when 9, 10, and 11 are selected.
So when 9 is checked, all are disabled except 10 and 11. When 10 is selected all is disabled except 9 and 11. when 11 is selected all is disabled except 9 and 10
```html
example
example
example
example
example
example
example
example
example
example
example
example
example
$(function () {
$("input[type='checkbox']").change(function () {
debugger;
if (($("input[type='checkbox']")[9]).checked) {
$("input[type='checkbox']").not($("input[type='checkbox']")[9]).attr("disabled", "disabled");
}
else {
$("input[type='checkbox']").not($("input[type='checkbox']")[9]).removeAttr("disabled");
}
});
});
```
Answer:
```
var indices = [9, 10, 11];
indices.forEach(function (i) {
$(".parent input[type='checkbox']").eq(i - 1).addClass("magic");
});
$(".parent input[type='checkbox']").change(function () {
if ($(this).hasClass("magic")) {
if (this.checked)
$(".parent input[type='checkbox']:not(.magic)").prop("checked", false).prop("disabled", true);
else {
if ($(".parent input.magic[type='checkbox']:checked").length == 0)
$(".parent input[type='checkbox']:not(.magic)").prop("disabled", false);
}
}
});
label {display: block;}
.magic + span {font-weight: bold;}
Input 1
Input 2
Input 3
Input 4
Input 5
Input 6
Input 7
Input 8
Input 9
Input 10
Input 11
Input 12
Input 13
Input 14
Input 15
```<issue_comment>username_1: Try to use `index()` and `eq` here...
First try to find the index of clicked checkbox using **[index()](https://api.jquery.com/index/)**...Then if it matches with the condition(9, 10 or 11) disable all using **[prop()](https://api.jquery.com/prop/)** and also add a class to the checked checkbox to check the count of **matched+checked** checkbox...And later if this count become `0` enable all the checkboxes
***Note:*** `index()` and `eq()` starts from 0
```js
$(".parent input[type='checkbox']").each(function() {
$(this).on("change", function() {
var index = $(this).closest("label").index();
if (index === 8 || index === 9 || index === 10) {
$("input[type='checkbox']").prop("disabled", true);
$("input[type='checkbox']").eq(8).prop("disabled", false);
$("input[type='checkbox']").eq(9).prop("disabled", false);
$("input[type='checkbox']").eq(10).prop("disabled", false);
$(this).prop("disabled", true);
if (this.checked) {
$(this).addClass("matched");
} else {
$(this).removeClass("matched");
}
if ($(".matched").length === 0) {
$("input[type='checkbox']").prop("disabled", false);
}
}
})
})
```
```css
label {
position: relative;
}
span {
position: absolute;
top: 100%;
left: 0;
}
```
```html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
```
Upvotes: 1 <issue_comment>username_2: You can add class to check boxes that you want to disable as follow.
```js
$(document).ready(function() {
$(function() {
$("input[type='checkbox']").change(function() {
if (this.checked) {
if (this.value == 'example9' || this.value == 'example10' || this.value == 'example11') {
$('.test').attr('disabled', true);
}
} else {
if (this.value == 'example9' || this.value == 'example10' || this.value == 'example11') {
if ($("input[type='checkbox']:not(.test):checked").length == 0)
$('.test').removeAttr('disabled');
}
}
});
});
});
```
```html
1
2
3
4
5
6
7
8
9
10
11
12
13
```
Upvotes: 1 <issue_comment>username_3: Extending the other answer, I made it well so that if one of those hot areas are selected (and can be configured), you won't be able to select the others and also others gets unselected.
So technically, what I am doing here:
* Select the magic ones, others except magic ones will be disabled and unselected.
* When all the magic ones are unselected, others behave normal.
* At any point of time, you won't be able to have magic as well as muggles selected.
* You don't need to go by indices, but instead, you can add a class `magic` to the input.
\* *By magic ones I mean, those are not supposed to be selected.*
```js
$(".parent input[type='checkbox']").change(function() {
if ($(this).hasClass("magic")) {
if (this.checked)
$(".parent input[type='checkbox']:not(.magic)").prop("checked", false).prop("disabled", true);
else {
if ($(".parent input.magic[type='checkbox']:checked").length == 0)
$(".parent input[type='checkbox']:not(.magic)").prop("disabled", false);
}
}
});
```
```css
label {display: block;}
.magic + span {font-weight: bold;}
```
```html
Input 1
Input 2
Input 3
Input 4
Input 5
Input 6
Input 7
Input 8
Input 9
Input 10
Input 11
Input 12
Input 13
Input 14
Input 15
```
**Update:** Fixed the syntax error and added labels. Added visual cues. Some code clean-up done.
---
If you prefer not to add classes, but just the indices, well, extending my answer, you get here:
```js
var indices = [9, 10, 11];
indices.forEach(function (i) {
$(".parent input[type='checkbox']").eq(i-1).addClass("magic");
});
$(".parent input[type='checkbox']").change(function() {
if ($(this).hasClass("magic")) {
if (this.checked)
$(".parent input[type='checkbox']:not(.magic)").prop("checked", false).prop("disabled", true);
else {
if ($(".parent input.magic[type='checkbox']:checked").length == 0)
$(".parent input[type='checkbox']:not(.magic)").prop("disabled", false);
}
}
});
```
```css
label {display: block;}
.magic + span {font-weight: bold;}
```
```html
Input 1
Input 2
Input 3
Input 4
Input 5
Input 6
Input 7
Input 8
Input 9
Input 10
Input 11
Input 12
Input 13
Input 14
Input 15
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 702 | 1,974 | <issue_start>username_0: I'm trying to create three columns based on date in seconds format.
My `user.updated_at = 1521533490`
I would like to get year, month and day separately and put these formatted values to columns for example:
year -> 2018, month -> 11, day -> 23
Does someone know how can I do that in `pgSQL`?<issue_comment>username_1: Try this approche to get differents arguments, then you can do whatever you want:
```
SELECT to_timestamp(1521533490); //2018-03-20T08:11:30.000Z
SELECT to_char(to_timestamp(1521533490), 'HH'); // 08 Hour
SELECT to_char(to_timestamp(1521533490), 'MI'); // 11 Minutes
SELECT to_char(to_timestamp(1521533490), 'SS'); // 30 Seconds
SELECT to_char(to_timestamp(1521533490), 'DD'); // 20 Day
SELECT to_char(to_timestamp(1521533490), 'Mon'); // MAR Month
SELECT to_char(to_timestamp(1521533490), 'YYYY'); // 2018 Year
```
Upvotes: 1 <issue_comment>username_2: >
> I would like to get year, month and day separately and put these formated values to columns
>
>
>
Don't do that.
Use a single column of type `date` or `timestamp`, depending on your application. Not every combination of your three columns will be a valid date. But every value in a single column of type `date` *will* be a valid date.
If you need the parts of a date separately, use [PostgreSQL's date/time functions](https://www.postgresql.org/docs/current/static/functions-datetime.html).
Upvotes: 3 [selected_answer]<issue_comment>username_3: Use the `EXTRACT` function.
```
SELECT to_timestamp(updated_at) "Date",
EXTRACT(YEAR FROM (to_timestamp(updated_at))) "Year",
EXTRACT(MONTH FROM (to_timestamp(updated_at))) "Month",
EXTRACT(DAY FROM (to_timestamp(updated_at))) "Day"
FROM users
```
Output
```
Date Year Month Day
2018-03-20T08:11:30Z 2018 3 20
```
SQL Fiddle: <http://sqlfiddle.com/#!15/afe0e/15/0>
More information on the [EXTRACT](https://www.techonthenet.com/oracle/functions/extract.php) function.
Upvotes: 0 |
2018/03/21 | 894 | 2,851 | <issue_start>username_0: I consider using an owner draw menu in a Windows application that should have the same look as the standard menu. (Reason: the standard menu doesn't work well in some mixed DPI situations.)
Currently I have a problem providing the correct width during *WM\_MEASUREITEM*.
This is a screenshot of the Edit menu of notepad where each item has a shortcut.
[](https://i.stack.imgur.com/HTCNV.png)
We can see that there is a constant gap between the item texts and shortcut texts as if they were columns. It seems as if the widths of the item texts and the widths of the shortcut texts are retrieved separately, as the longest item text "Time/Date" reserves a shortcut width suitable for `Ctrl`+`A` while it only needs one for `F5`.
I could not find any API functionality where I can give the width of the item text and the shortcut text separately, nor did I find any metric specifying the size of the gap.
So my question is: Is it possible to achieve the desired behavior within the usual *WM\_MEASUREITEM* message and if yes, how? If not, is there any other means to get this right or is it just not possible at all?<issue_comment>username_1: Try this approche to get differents arguments, then you can do whatever you want:
```
SELECT to_timestamp(1521533490); //2018-03-20T08:11:30.000Z
SELECT to_char(to_timestamp(1521533490), 'HH'); // 08 Hour
SELECT to_char(to_timestamp(1521533490), 'MI'); // 11 Minutes
SELECT to_char(to_timestamp(1521533490), 'SS'); // 30 Seconds
SELECT to_char(to_timestamp(1521533490), 'DD'); // 20 Day
SELECT to_char(to_timestamp(1521533490), 'Mon'); // MAR Month
SELECT to_char(to_timestamp(1521533490), 'YYYY'); // 2018 Year
```
Upvotes: 1 <issue_comment>username_2: >
> I would like to get year, month and day separately and put these formated values to columns
>
>
>
Don't do that.
Use a single column of type `date` or `timestamp`, depending on your application. Not every combination of your three columns will be a valid date. But every value in a single column of type `date` *will* be a valid date.
If you need the parts of a date separately, use [PostgreSQL's date/time functions](https://www.postgresql.org/docs/current/static/functions-datetime.html).
Upvotes: 3 [selected_answer]<issue_comment>username_3: Use the `EXTRACT` function.
```
SELECT to_timestamp(updated_at) "Date",
EXTRACT(YEAR FROM (to_timestamp(updated_at))) "Year",
EXTRACT(MONTH FROM (to_timestamp(updated_at))) "Month",
EXTRACT(DAY FROM (to_timestamp(updated_at))) "Day"
FROM users
```
Output
```
Date Year Month Day
2018-03-20T08:11:30Z 2018 3 20
```
SQL Fiddle: <http://sqlfiddle.com/#!15/afe0e/15/0>
More information on the [EXTRACT](https://www.techonthenet.com/oracle/functions/extract.php) function.
Upvotes: 0 |
2018/03/21 | 927 | 3,769 | <issue_start>username_0: I am using Spring Kafka 1.2.2.RELEASE. I have a Kafka Listener as consumer that listens to a topic and index the document in elastic.
My Auto commit offset property is set to true //default.
I was under the impression that in case there is an exception in the listener(elastic is down) the offsets should not be committed and the same message should be processed for the next poll
However this is not happening and the consumer commits the offset on the next poll.After reading posts and documentation i learnt that this is the case that with auto commit set to true to next poll will commit all offset
My doubt is why is the consumer calling the next poll and also how can i prevent any offset from committing with auto commit to true or do i need to set this property to false and commit manually.<issue_comment>username_1: I prefer to set it to false; it is more reliable for the container to manage the offsets for you.
Set the container's `AckMode` to `RECORD` (it defaults to `BATCH`) and the container will commit the offset for you after the listener returns.
Also consider upgrading to at least 1.3.3 (current version is 2.1.4); 1.3.x introduced a much simpler threading model, thanks to [KIP-62](https://cwiki.apache.org/confluence/display/KAFKA/KIP-62%3A+Allow+consumer+to+send+heartbeats+from+a+background+thread)
**EDIT**
With auto-commit, the offset will be committed regardless of success/failure. The container won't commit after a failure, unless `ackOnError` is true (another reason to not use auto commit).
However, that still won't help because the broker won't send the same record again. You have to perform a seek operation on the `Consumer` for that.
In 2.0.1 (current version is 2.1.4), we added the `SeekToCurrentErrorHandler` which will cause the failed and unprocessed records to be re-sent on the next poll. [See the reference manual](https://docs.spring.io/spring-kafka/reference/html/_reference.html#_seek_to_current_container_error_handlers).
You can also use a `ConsumerAwareListener` to perform the seek yourself (also added in 2.0).
With older versions (>= 1.1) you have to use a `ConsumerSeekAware` listener which [is quite a bit more complicated](https://docs.spring.io/spring-kafka/reference/html/_reference.html#seek).
Another alternative is to add [retry](https://docs.spring.io/spring-kafka/reference/html/_reference.html#retrying-deliveries) so the delivery will be re-attempted according to the retry settings.
Upvotes: 4 <issue_comment>username_2: Apparently, there will be message loss with Spring Kafka <=1.3.3 @KafkaListener even if you use ackOnError=false if we expect Spring Kafka to automatically (at least document) take care of this by retrying and "simply not doing poll again"? :). And, the default behavior is to just log.
We were able to reproduce message loss/skip on a consumer even with spring-kafka 1.3.3.RELEASE (no maven sources) and with a single partition topic, concurrency(1), AckOnError(false), BatchListener(true) with AckMode(BATCH) for any runtime exceptions. We ended up doing retries inside the template or explore ConsumerSeekAware.
@GaryRussell, regarding "broker won't send same record again" or continue returning next batch of messages without commit?, is this because, consumer poll is based on current offset that it seeked to get next batch of records and not exactly on last offsets committed? Basically, consumers need not commit at all assuming some run time exceptions on every processing and keep consuming entire messages on topic. Only a restart will start from last committed offset (duplicate).
Upgrade to 2.0+ to use ConsumerAwareListenerErrorHandler seems requires upgrading to at least Spring 5.x which is a major upgrade.
Upvotes: 2 |
2018/03/21 | 601 | 2,284 | <issue_start>username_0: Is it possible to use `removeClass` for `AJAX` loaded DIVs?
```
setInterval(function() {
$('.message').each(function() {
var message_id = $(this).data('id');
if ($(this).hasClass('message-not-read')) {
$.get('message-set-read.php?message-id=' + message_id, function(data) {
if (data == 'is-set-read') {
$(this).removeClass('message-not-read'));
}
});
}
});
}, 5000);
```
DIVs with class `.message` and `.message-not-read` are loaded through another `$.load()`<issue_comment>username_1: Yes, but you'll have to store your `this` before you make your AJAX call, since it changes your context :
```
setInterval(function() {
$('.message').each(function() {
var that = $(this); //Here
var message_id = that.data('id');
if (that.hasClass('message-not-read')) {
$.get('message-set-read.php?message-id=' + message_id, function(data) {
if (data == 'is-set-read') {
that.removeClass('message-not-read'));
}
});
}
});
}, 5000);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: The issue is because the scope of `this` has changed inside the `$.get` handler, so it no longer refers to the current `.message` element in the iteration. You need to store that reference in a variable for use in the inner scope.
Also note that you can include the required class in the selector and remove the `if` condition, like this:
```js
setInterval(function() {
$('.message.message-not-read').each(function() {
var $message = $(this);
$.get('message-set-read.php?message-id=' + $message.data('id'), function(data) {
$message.toggleClass('message-not-read', data !== 'is-set-read'));
});
});
}, 5000);
```
Also note that looping through all your messages and sending an AJAX request for each of them every 5 seconds is a really bad idea. It would make more sense to either invert the logic so that you make a single AJAX request which gets the state of all visible messages on the screen which you can then update, or better yet, use websockets if you need to keep the UI/server data in close synchronisation.
Upvotes: 1 |
2018/03/21 | 315 | 1,334 | <issue_start>username_0: Is it possible to sync / mirror two SharePoint librarys on two different sites?
So when a new document is added, modified or deleted, that the other library automatically updates this document?<issue_comment>username_1: There's no out of the box options to sync two libraries. There are several workarounds.
A hack to use the same web part in two different sites: <http://techtrainingnotes.blogspot.com/2009/03/sharepoint-one-library-multiple-sites.html>
Use the Search Web Part. This won't allow updates in both sites, just will let you see the content from a library in another web site in the same farm. By default it will not look like a library table view, but it can with some SharePoint Designer customization.
If both libraries are in the same Site Collection, then you can use the Content Query web part. Again, you will need to do some customization to make it look like a library table view.
For all of the above, the users in the second site will need permissions to the source site.
Upvotes: 1 <issue_comment>username_2: Try SharePointMigration tool - <https://learn.microsoft.com/en-us/sharepointmigration/introducing-the-sharepoint-migration-tool>
I use it for site to site and Network to SharePoint/OneDrive for business migrations.
Works flawlessly with detailed error logs
Upvotes: 0 |
2018/03/21 | 380 | 1,497 | <issue_start>username_0: I am working on the following scenario.
I click on an element in the main web page and it opens a dialog box. It is an iframe and i use `diver.switchTo().frame(1);` to access that frame. I am able to perform the required activites in that frame. Clicking on OK button in that frame will close it. Once the frame is closed i am not able to access any of the elements in the main page. I used the following to switch back to main page
`driver.switchTo().defaultContent()`and `driver.switchTo().frame(0)`. But none of them let me get back to the main page.
Since the frame gets closed i also tried without any switchTo() statements. But it didnt work either.
Please help me with other possible solutions for it. Thanks in advance!<issue_comment>username_1: You need to switch back to the original window (Java code)
```
String windowHandle = driver.getWindowHandle(); // save the original window handle
// handle the pop up
driver.switchTo().window(windowHandle);
```
Upvotes: 2 <issue_comment>username_2: As you are trying to switch back to the **Top-Level Browsing Context** your following code trial should have worked :
```
driver.switchTo().defaultContent();
```
As an alternative you can also try :
```
driver.switchTo().parentFrame();
```
Sometimes it may happen that the driver looses the window focus and in that case you have to regain the focus on the browser by :
```
((JavascriptExecutor) driver).executeScript("window.focus();");
```
Upvotes: 0 |
2018/03/21 | 535 | 1,552 | <issue_start>username_0: This is the error I get when I try to install gapps (obtained from [here](https://www.mediafire.com/file/qmd7z9x5ndsb54k/gapps-kk-20140105-signed.zip), following [these instructions](http://www.alteridem.net/2017/02/02/installing-google-play-gapps-visual-studio-android-emulators/)).
[](https://i.stack.imgur.com/30OCS.png)
I navigated to `HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node` as instructed in [here](https://msdn.microsoft.com/en-us/library/mt228282.aspx#LW_CollapsibleArea_Title), but I didn't found any "Android SDK Tools" folder:
[](https://i.stack.imgur.com/iy9Lk.png)
which is weird because I do have Android SDK tools installed:
[](https://i.stack.imgur.com/EIlO3.png)
What am I doing wrong?<issue_comment>username_1: Adding the key manually in the registry fixed it for me.
1. Type regedit.exe
2. Find the following node:
Computer\HKEY\_LOCAL\_MACHINE\SOFTWARE\WOW6432Node\
Add:
* Key: Android SDK Tools
* String Value: Path with the Path to your sdk
[](https://i.stack.imgur.com/meMjA.png)
Upvotes: 4 <issue_comment>username_2: The other answer didn't work for me but I stumbled on [this answer](https://stackoverflow.com/a/57228513/1978687) that points out (in #5) that newer versions expect the parent folder for `platform-tools` rather than the folder itself.
Upvotes: 1 |
2018/03/21 | 603 | 2,176 | <issue_start>username_0: So let’s say I have this method:
```
myMethod1() {
const a = 1;
const b = 2;
return callsAnotherFunction(`foo: ${a + b} $`);
}
```
Now I would like to have it in another function as well but with `bar` instead of `foo`.
```
myMethod2() {
const a = 1;
const b = 2;
return callsAnotherFunction(`bar: ${a + b} $`);
}
```
Is this possible without modifying `myMethod1`?
In a way that if `myMethod1` gets changed to something else, lets say:
```
myMethod1() {
const a = 1;
const CHANGE = 2;
return callsAnotherFunction(`foo: ${a + CHANGE} $`);
}
```
I do not have to touch `myMethod2` because it just clones `myMethod1` and changes the `foo` to `bar` thus giving me automatically:
```
myMethod2() {
const a = 1;
const CHANGE = 2;
return callsAnotherFunction(`bar: ${a + CHANGE} $`);
}
```
Maybe something like parsing the function into a string, replacing the certain text and outputting a new function? Something like this:
```
myMethod2() {
const hypothetical = @toString(myMethod1)
hypothetical.replace('foo', 'bar');
return @toFunction(hypothetical);
}
```
^ the code above is obviously not working because that syntax does not exist, it’s just to clarify what I would like to do.
Is something like this even possible?
Thanks for your help.
*Edit: I can’t edit/access method1*<issue_comment>username_1: You can use only one function - use a function argument to differentiate between the case. like:
```
myMethod2(type) {
const a = 1;
const b = 2;
return callsAnotherFunction(`${type}: ${a + b} $`);
}
```
Upvotes: 0 <issue_comment>username_2: If you cannot modify the function then you cannot modify hardcoded strings in its body. Using the function constructor is not a good idea and will not work in many cases due to [Content Security Policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) which can prevent the use of `eval/Function` (which are considered the same).
Upvotes: 2 [selected_answer] |
2018/03/21 | 609 | 1,753 | <issue_start>username_0: I am trying to access the previous values or the stochastic of the chart in MQL5. But I only know how to calculate for the current.
What I am trying to do is:
```
int stochastic_output = iStochastic(_Symbol,PERIOD_M1,5,3,3,MODE_SMA,STO_LOWHIGH);
```
But I don't know how I can get the value of the previous 15 candles or the previous 3 minutes. Kindly, help me how to get it.<issue_comment>username_1: ```
//--- inputs
input int Candles=15;
input int NeededCandle=3;
// --- global variables
int stoch_handle;
int OnInit(){
stoch_handle=iStochastic(_Symbol,PERIOD_M1,5,3,3,MODE_SMA,STO_LOWHIGH);
if(stoch_handle==INVALID_HANDLE)
return(INIT_FAILED);
}
void OnTick(){
double main[],signal[];
ArrayResize(main,Candles);
ArraySetAsSeries(main,true);
ArrayResize(signal,Candles);
ArraySetAsSeries(signal,true);
if(CopyBuffer(stoch_handle,MAIN_LINE,0,Candles,main)!=Candles)
return;
if(CopyBuffer(stoch_handle,SIGNAL_LINE,0,Candles,signal)!=Candles)
return;
printf("%i - main=%.2f, signal=%.2f",__LINE__,main[NeededCandle-1],signal[NeededCandle-1]);
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: There is a simple way to do that.
What you need is to copy the data per minute of previous 15 candles using `CopyBuffer`.
See the example:
```
double K[],D[];
ArraySetAsSeries(K,true);
ArraySetAsSeries(D,true);
int stochastic_output = iStochastic(_Symbol,PERIOD_M1,5,3,3,MODE_SMA,STO_LOWHIGH);
CopyBuffer(stochastic_output,0,0,15,K);
CopyBuffer(stochastic_output,1,0,15,D);
Print("K size: ",ArraySize(K));
Print("D size: ",ArraySize(D));
```
Output of the above:
```
K Size: 15
D Size: 15
```
Hope this will help you.
Upvotes: 2 |
2018/03/21 | 845 | 2,611 | <issue_start>username_0: When I am using new Date, I am getting something like as follows:
```
Wed Mar 21 2018 16:14:50 GMT+0530 (India Standard Time)
```
but what I want is `xxxxxxxxxxxxxxxx`/(`21032018041217PM`) formatted time string
Here(`21032018041217PM`) is 21 is `date, 03-month, 2018-year, 04-time, 12-minutes, 17-seconds` and It should be `AM/PM`.<issue_comment>username_1: I would suggest moment.js otherwise you can do string concatenations and calculations be careful month is 0-11 which means 3 might actually be 04 not 03.
Upvotes: 0 <issue_comment>username_2: You can handle this quite easily by using `momentjs` library. The documentation is quite detailed here: <https://momentjs.com/docs/#/displaying/>
It will allow you to handle date formatting any way you desire.
You can download it from here: <https://momentjs.com/>
**Without using `momentJS` library:**
To convert the current date and time to a UNIX timestamp do the following:
```
var ts = Math.round((new Date()).getTime() / 1000);
```
>
> getTime() returns milliseconds from the UNIX epoch, so divide it by 1000 to get the seconds representation. It is rounded using Math.round() to make it a whole number. The "ts" variable now has the UNIX timestamp for the current date and time relevent to the user's web browser.
>
>
>
You can also take a look here: [How do you get a timestamp in JavaScript?](https://stackoverflow.com/questions/221294/how-do-you-get-a-timestamp-in-javascript)
Upvotes: 1 <issue_comment>username_3: You could use [Moment.js](https://momentjs.com/) to achieve your desired format:
```js
console.log( moment().format('DDMMYYYYhhmmssA') )
```
Upvotes: 2 <issue_comment>username_4: I'm using like this,
```
date.getDate()+""+(date.getMonth() + 1)+""+date.getFullYear()+""+ date.getHours()+""+date.getMinutes() +""+date.getSeconds();
```
but this formate of the result `2132018163431` i'm getting
Upvotes: 0 <issue_comment>username_5: ```
var date = new Date();
var dateFormat = (date.getDate().toString().length == 1? "0":'' ) + date.getDate() + (date.getMonth().toString().length == 1? "0":'' ) + date.getMonth() + "" + date.getFullYear()
var hours = ((date.getHours()%12).toString().length == 1?'0':'') + "" + (date.getHours()%12);
var minuts = ((date.getMinutes()).toString().length == 1?'0':'') + "" + (date.getMinutes());
var seconds = ((date.getSeconds()).toString().length == 1?'0':'') + "" + (date.getSeconds());
var format = (date.getHours() >= 12 && date.getHours()%12 != 0) ? 'PM':'AM'
var yourDate = dateFormat + hours + minuts + seconds + format
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 530 | 1,695 | <issue_start>username_0: I would like to get all records in a relationship where its not null
so my table are
```
tbl_truck
id, name
tbl_checks
id
truck_id //foreign key from tbl_truck table id
```
So in my query i have
```
$query = TblTrucksModel::find()
->leftJoin('tbl_checks','tbl_trucks.id = tbl_checks.truck_id')
->where() //here add the condition
```
So basically i would like to fetch only the id's from `tbl_truck` which are also existent in `tbl_checks`
Nb: `TblTrucksModel` represents the `tbl_trucks` table
How do i go on about this.<issue_comment>username_1: Try this one.
```
$query = TblTrucksModel::find();
$query->select('t.*');
$query->from('tbl_truck t');
$query->leftjoin('tbl_checks c','t.id = c.truck_id');
$query->where('c.id is not null');
$result = $query->all();
```
Upvotes: 1 <issue_comment>username_2: Should be using the operator sintax
```
$query = TblTrucksModel::find()
->leftJoin('tbl_checks','tbl_trucks.id = tbl_checks.truck_id')
->where(['not', ['tbl_trucks.id' => null]])
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: If you intend not to show the trucks from the `tbl_truck` table that have no associated record in the `tbl_checks` and only show records that have an association then you should use `innerJoin` rather than `leftJoin` as left join will show all the records from the `tbl_truck` showing the `truck_id` as `NULL` for those records that have no association or matching `truck_id` in the `tbl_checks`
```
TblTrucksModel::find()
->innerJoin('tbl_checks','tbl_trucks.id = tbl_checks.truck_id')
```
You don't need an extra `where` clause in this case.
Upvotes: 0 |
2018/03/21 | 873 | 3,236 | <issue_start>username_0: If I have something like:
```python
model = Model(inputs = input, outputs = [y1,y2])
l1 = 0.5
l2 = 0.3
model.compile(loss = [loss1,loss2], loss_weights = [l1,l2], ...)
```
what does Keras do with the losses to obtain the final loss?
Is it something like:
```python
final_loss = l1*loss1 + l2*loss2
```
Also, what does it mean during training? Is the loss2 only used to update the weights on layers where y2 comes from? Or is it used for all the model's layers?<issue_comment>username_1: From [`model` documentation](https://keras.io/models/model/):
>
> **loss**: String (name of objective function) or objective function. See losses. If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses.
>
>
> ...
>
>
> **loss\_weights**: Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the weighted sum of all individual losses, weighted by the `loss_weights` coefficients. If a list, it is expected to have a 1:1 mapping to the model's outputs. If a tensor, it is expected to map output names (strings) to scalar coefficients.
>
>
>
So, yes, the final loss will be the "weighted sum of all individual losses, weighted by the `loss_weights` coeffiecients".
You can check the [code where the loss is calculated](https://github.com/keras-team/keras/blob/9118ea65f40874e915dd1299efd1cc3a7ca2c333/keras/engine/training.py#L816-L848).
>
> Also, what does it mean during training? Is the loss2 only used to update the weights on layers where y2 comes from? Or is it used for all the model's layers?
>
>
>
The weights are updated through [backpropagation](https://en.wikipedia.org/wiki/Backpropagation), so each loss will affect only layers that connect the input to the loss.
For example:
```
+----+
> C |-->loss1
/+----+
/
/
+----+ +----+/
-->| A |--->| B |\
+----+ +----+ \
\
\+----+
> D |-->loss2
+----+
```
* `loss1` will affect A, B, and C.
* `loss2` will affect A, B, and D.
Upvotes: 7 [selected_answer]<issue_comment>username_2: **For multiple outputs to back propagate, I think it is not a complete answer from what's mentioned by username_1.**
>
> Also, what does it mean during training? Is the loss2 only used to
> update the weights on layers where y2 comes from? Or is it used for
> all the model's layers?
>
>
>
For output C and output D, keras will compute a final loss F\_loss=w1 \* loss1 + w2 \* loss2. And then, the final loss F\_loss is applied to both output C and output D. Finally comes the backpropagation from output C and output D using the same F\_loss to back propagate.
Upvotes: 4 |
2018/03/21 | 618 | 1,901 | <issue_start>username_0: I'm writing an expression in a Transact SQL query to find the per-record minimum of two datetimes a,b where a cannot be null but b can be null (in which case return a).
I have the following, which I think is correct, and might even be efficient, but is certainly ugly.
Can we do better?
```
case when b is null then a else (case when b < a then b else a end) end as min_datetime
```<issue_comment>username_1: You can use an `ISNULL` to force a default maximum value.
```
CASE WHEN A < ISNULL(B, '2099-01-01') THEN A ELSE B END AS min_datetime
```
Upvotes: 2 <issue_comment>username_2: Try this:
```
SELECT CASE WHEN ISNULL(b, '1900-01-01')> a THEN ISNULL(b, '1900-01-01') ELSE a END
```
Upvotes: 0 <issue_comment>username_3: I think this will do it
```
min(isnull(b,a))
```
Upvotes: -1 <issue_comment>username_4: ```
SELECT MIN(Val)
FROM Table a
CROSS APPLY
(
VALUES (a.a),(a.b)
) x(Val)
```
Upvotes: 1 <issue_comment>username_5: In SQL Server, you can do this with a lateral join. The correct syntax is:
```
select t.*, v.min_dte
from t cross apply
(select min(v.dte) as min_dte
from values ( (t.a), (t.b) ) v(dte)
) v;
```
This is very handy as the number of values gets larger. However, the performance is likely to be slightly worse (but not much worse) than a single expression.
As for a single expression, I would go for:
```
case when b is null or a < b then a else b end as min_datetime
```
The performance of this should be essentially the same as your expression. I find this version simpler.
Upvotes: 3 [selected_answer]<issue_comment>username_6: ```
SELECT COALESCE(IIF(@a > @b, @b, @a), @a, @b ) as 'Minimum date'
```
**IIF(@a > @b, @b, @a)** will return the min date between the two. If one of the dates will be null then it will return null.
**COALESCE** will take care of returning the first not null value.
Upvotes: 1 |
2018/03/21 | 486 | 1,626 | <issue_start>username_0: Is it safe to rely on default deleter using `std::unique_ptr`?
I want to use it like this:
```
uint8_t* binaryData = new uint8_t[binaryDataSize];
std::unique_ptr binPtr(binaryData);
```
So the default deleter in `std::unique_ptr` looks like this:
```
template
typename enable\_if::value>::type
operator()(\_Up\* \_\_ptr) const
{
static\_assert(sizeof(\_Tp)>0,
"can't delete pointer to incomplete type");
delete [] \_\_ptr;
}
```
From my point of view it's safe to use for raw pointers allocated by `new[]` and not safe with raw pointers allocated by `std::malloc`.
Am i missing something? Is there a better solution?<issue_comment>username_1: >
> So the default deleter in `std::unique_ptr` looks like this:
>
>
>
That's the default deleter for arrays. You will only hit that deleter when using `std::unique_ptr`, not when using `std::unique_ptr`.
---
>
> From my point of view it's safe to use for raw pointers allocated by `new[]`
>
>
>
As long as you use `std::unique_ptr`, yes. You should use `std::make_unique` to avoid these issues.
---
>
> raw pointers allocated by `std::malloc`
>
>
>
`std::unique_ptr` doesn't support pointers allocated with `malloc`. Regardless, you shouldn't use `malloc` in C++.
Upvotes: 4 [selected_answer]<issue_comment>username_2: That should be `std::unique_ptr`, otherwise the default deleter is not that one but the one that calls plain `delete`, and that mismatch will trigger UB.
You cannot use the default deleter at all if you allocated with `std::malloc`, you'll need to provide your own deleter that calls `std::free`.
Upvotes: 2 |
2018/03/21 | 1,472 | 5,396 | <issue_start>username_0: I'm creating a form whereby the user can upload a picture and send it to the server along with the information in the form. Everything was working fine locally but when I uploaded the code to the server I started getting errors. I changed all the codes concerning the path but its still giving me some errors but a least I can now retrieve pictures.
So now unto the problem. When I submit the form it gives me a "Unable to create the "<http://xxx.xx.xx/profileLogo>" directory". This is when I'm trying to save the picture into a folder.
Here is the code where I believe the issue is coming from:
`$path = $request->file('logo')->move(
asset("/profileLogo/"), $fileNameToStore
);`
Here is the entire code for the controller:
```
php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Storage;
use DB;
use File;
class CompanyProfileController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$result= DB::table('tblcompany')-get();
if($result==null)
{
DB::table('tblcompany')->insert([
'companyName' =>' ']
);
}
$pic = DB::table('tblcompany')->select('logoName')->limit(1)->value('logoName');
if($pic==null)
{
DB::table('tblcompany')->update(['logoName' => 'noimage.png',]);
}
$data['getAllDetails']= DB::table('tblcompany')->get();
return view('companyProfile.companyProfile', $data);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
//dd(asset(''));
$this->validate($request, [
'companyname' =>'required',
'shortCode' =>'required',
'telnum' =>'required',
'emailid' =>'required',
'address' =>'required',
]);
//$file_path = asset('') . '/profileLogo/';
//$file_path = asset("/profileLogo/");
if($request->hasFIle('logo')){
$filenameWithExt = $request->file('logo')->getClientOriginalName();
$filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extention = $request->file('logo')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$pic = DB::table('tblcompany')->select('logoName')->limit(1)->value('logoName');
if($pic!='noimage.png')
{
//$deletePicPath = $file_path . $pic;
//die($deletePicPath);
//File::delete($deletePicPath );
}
$path = $request->file('logo')->move(
asset("/profileLogo/"), $fileNameToStore
);
DB::table('tblcompany')->update(['logoPath' => $path,'logoName' => $fileNameToStore,]);
}
$companyname= trim($request['companyname']);
$shortCode= trim($request['shortCode']);
$telnum= trim($request['telnum']);
$emailid= trim($request['emailid']);
$address= trim($request['address']);
DB::table('tblcompany')->update(
['companyName' => $companyname,
'shortCode' => $shortCode,
'phoneNo' => $telnum,
'emailAddress' => $emailid,
'contactAddress' => $address,]
);
return redirect('/company-profile')->with('message','Form Updated');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
```
}
So how can I successfully go to the folder and store the picture?<issue_comment>username_1: You need to give full access to that directory before performing any read write operation. To give permission you can write following command in your linux console.
```
sudo chmod -Rf 777 /path_to_folder
```
In your case
```
sudo chmod -Rf 777 /var/www/html/laravel/assets/profileLogo
```
Make sure you give the correct path of the folder as this is only example.
Upvotes: -1 <issue_comment>username_2: Change permissions to folder where you want to save file. For linux:
```
chmod a+rwx folder_name -R
```
It will change permission for folder\_name and all folders that are included.
You must do that as a system root.
For windows:
```
C:\>icacls "D:\path_to_folder" /grant John:(OI)(CI)F /T
```
Upvotes: 2 <issue_comment>username_3: If you are linux, you can log into the server and navigate to the folder you want to have your uploads folder in and create the uploads folder using
```
mkdir uploads
```
After that, give the uploads folder the read and write permission like below
```
sudo chmod -R 777 [path-to-your-uploads-folder]
```
That's what I did and it worked fine
Upvotes: 0 |
2018/03/21 | 739 | 2,028 | <issue_start>username_0: Let's say this is the query:
```
db.movies.aggregate([
{$match: {languages: "English", cast:{$exists:true}}},
{$unwind: "$cast"},
{$group: {_id: "$cast", numFilms:{$sum: 1}, average:{$avg: "$imdb.rating"}
}},
{$sort: {numFilms:-1}},
{$limit: 1}
])
```
And I get the output:
```
{ "_id" : "<NAME>", "numFilms" : 107, "average" : 6.424299065420561 }
```
How can I truncate `average` to single/double decimal points? I wanted to see an output like this:
```
{ "_id" : "<NAME>", "numFilms" : 107, "average" : 6.42 }
```
I tried this [post](https://stackoverflow.com/questions/17482623/rounding-to-2-decimal-places-using-mongodb-aggregation-framework), but seems like I can't get away doing the same with `$avg` operator. How can I achieve this?
Potential duplicate
-------------------
I believe the above linked isn't a duplicate, because mine deals with `$avg` operator.<issue_comment>username_1: You can achieve this with a `$project` stage with a `$trunc` but `$multiply` before and `$divide` after to deal with the decimal places.
For example if we add the following:
```
db.test.insertMany([{
number: 123.456
}, {
number: 456.789
}, {
number: 123
}]);
```
We can run an aggregation with the following:
```
db.test.aggregate([{
$project: {
number: {
$divide: [{
$trunc: {
$multiply: ["$number", 100]
}
}, 100]
}
}
}])
```
Which will give us:
```
{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f3"), "number" : 123.45 }
{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f4"), "number" : 456.78 }
{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f5"), "number" : 123 }
```
Upvotes: 3 <issue_comment>username_2: ```
$project : {
artistAmt : {
$divide: [{
$trunc: {
$multiply: ["$earnedAmount", 100]
}
}, 100]
}
}
before : "artistAmt": 1361.8100000000002
after : "artistAmt": 1361.81
```
Upvotes: 0 |
2018/03/21 | 762 | 1,965 | <issue_start>username_0: I have two little file that contain :
`f = 'employé numero 1'` at line 1 etc...
`f2 = 'a'` at line 1 etc...
I want to write in f3 to have at the first line : 'employé numero 1 a' etc
here is my code. After execute, no error msg but f3 is still empty :
```
f = open(r'c:\temp\merge1.txt','w',encoding='utf8')
for i in range(5): f.write(f"ligne {i+1}\n")
f.close()
f = open(r'c:\temp\merge1.txt','r',encoding='utf8')
f2 = open(r'c:\temp\merge2.txt','w',encoding='utf8')
for i in range(5): liste = ['a','b','c'] f.write(liste[i] "\n")
f2.close()
f2 = open(r'c:\temp\merge2.txt','r',encoding='utf8')
f3 = open(r'c:\temp\merge3.txt','w',encoding='utf8')
for line in f:
line_liste = line.split()
for line2 in f2:
line2_liste = line2.split()
line_liste.append(line2_liste)
f3.write(",".join(line_liste))
```<issue_comment>username_1: You can achieve this with a `$project` stage with a `$trunc` but `$multiply` before and `$divide` after to deal with the decimal places.
For example if we add the following:
```
db.test.insertMany([{
number: 123.456
}, {
number: 456.789
}, {
number: 123
}]);
```
We can run an aggregation with the following:
```
db.test.aggregate([{
$project: {
number: {
$divide: [{
$trunc: {
$multiply: ["$number", 100]
}
}, 100]
}
}
}])
```
Which will give us:
```
{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f3"), "number" : 123.45 }
{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f4"), "number" : 456.78 }
{ "_id" : ObjectId("5ab23dcb8094b7e4427b43f5"), "number" : 123 }
```
Upvotes: 3 <issue_comment>username_2: ```
$project : {
artistAmt : {
$divide: [{
$trunc: {
$multiply: ["$earnedAmount", 100]
}
}, 100]
}
}
before : "artistAmt": 1361.8100000000002
after : "artistAmt": 1361.81
```
Upvotes: 0 |
2018/03/21 | 1,003 | 3,594 | <issue_start>username_0: I am using MySQL DB. I have two tables -
1. Product\_Data (it has some columns including PK productDataId)
2. Product\_Data\_Link(it has 5 columns Id(PK), productDataId(FK), LinkTypeId, IsActive, ProductDataLinkUrl)
I am running this query in one service call for multiple products. Is there any way to optimize it for fast execution.
```
select
link1.ProductDataLinkUrl as ProductDataUrl1,
link2.ProductDataLinkUrl as ProductDataUrl2,
link3.ProductDataLinkUrl as ProductDataUrl3 ,
link4.ProductDataLinkUrl as ProductDataUrl4
FROM
product_data pd
left join
product_data_links link1
on link1.ProductDataId = pd.ProductDataId
and link1.ProductDataLinkTypeId = 1
and link1.ProductDataLinkIsActive = 1
left join
product_data_links link2
on link2.ProductDataId = pd.ProductDataId
and link2.ProductDataLinkTypeId = 2
and link2.ProductDataLinkIsActive = 1
left join
product_data_links link3
on link3.ProductDataId = pd.ProductDataId
and link3.ProductDataLinkTypeId = 3
and link3.ProductDataLinkIsActive = 1
left join
product_data_links link4
on link4.ProductDataId = pd.ProductDataId
and link4.ProductDataLinkTypeId = 4
and link4.ProductDataLinkIsActive = 1
WHERE
pd.ProductDataId = 99999
```<issue_comment>username_1: Your query should be fine with the following indexes:
* `product_data(ProductDataId)`
* `product_data_links(ProductDataId, ProductDataLinkTypeId, ProductDataLinkIsActive)`
Under some circumstances, it can be faster to use `group by`:
```
select max(case when ProductDataLinkTypeId = 1 then ProductDataLinkUrl end) as ProductDataUrl1,
max(case when ProductDataLinkTypeId = 2 then ProductDataLinkUrl end) as ProductDataUrl2,
max(case when ProductDataLinkTypeId = 3 then ProductDataLinkUrl end) as ProductDataUrl3,
max(case when ProductDataLinkTypeId = 4 then ProductDataLinkUrl end) as ProductDataUrl4
from product_data_links pdl
where ProductDataId = 99999 and
ProductDataLinkIsActive = 1 and
ProductDataLinkTypeId in (1, 2, 3, 4);
```
You want the second index above for this query.
Upvotes: 4 [selected_answer]<issue_comment>username_2: I think that it is important to add an index with the common related fields: newIndex(ProductDataId, ProductDataLinkTypeId, ProductDataLinkIsActive, ProductDataLinkUrl)
Then, I like subqueries because the bring just the required field instead of bringing the full table with a join.
```
(select
(select l1.ProductDataLinkUrl from product_data_links l1 where l1.ProductDataId = pd.ProductDataId
and l1.ProductDataLinkTypeId = 1
and l1.ProductDataLinkIsActive = 1 ) as ProductDataUrl1,
(select l2.ProductDataLinkUrl from product_data_links l2 where l2.ProductDataId = pd.ProductDataId
and l2.ProductDataLinkTypeId = 2
and l2.ProductDataLinkIsActive = 1 ) as ProductDataUrl2,
(select l3.ProductDataLinkUrl from product_data_links l3 where l3.ProductDataId = pd.ProductDataId
and l3.ProductDataLinkTypeId = 3
and l3.ProductDataLinkIsActive = 1 ) as ProductDataUrl3,
(select l4.ProductDataLinkUrl from product_data_links l4 where l4.ProductDataId = pd.ProductDataId
and l4.ProductDataLinkTypeId = 4
and l4.ProductDataLinkIsActive = 1 ) as ProductDataUrl4
FROM
product_data pd
WHERE
pd.ProductDataId = 99999)
```
I'll meassure times and result groups after each step of the refactor.
Good luck!
Upvotes: 0 |
2018/03/21 | 793 | 2,553 | <issue_start>username_0: I am trying to format the data labels that appear when I hover over part of a chart I have created using Plotly. The label is currently showing like [this](https://i.stack.imgur.com/6jKpE.png). I would like for the label to only show profit.
My code for creating the plot is:
```
output$monthlyProfits <- renderPlotly({
ggplot(profitTemp, aes(x = Date, y = Profit)) + geom_line(aes(text=Profit),
colour = "Blue")
```
How do I format the data label so that it will not show the X axis and only show the Y axis (profit)? I have tried with `aes(text=Profit)` but the X axis still shows.
Any help would be greatly appreciated.<issue_comment>username_1: It is more flexible to customize the plots that are directly made in `plotly`, however the requested operation is also possible using `ggplotly`. Here is an example on the iris data set:
```
library(plotly)
library(ggplot)
```
To define the hover info:
```
plot_ly(data = iris,
x = ~Sepal.Length,
y = ~Petal.Length,
color = ~Species,
hoverinfo = 'text',
text = ~Species)
```
[](https://i.stack.imgur.com/ZEtCo.png)
to do so with ggplotly leave the text argument blank when calling ggplot:
```
z <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species))+
geom_point()
```
and set the argument `tooltip` to `ggplotly`:
```
ggplotly(z, tooltip="Species")
```
[](https://i.stack.imgur.com/FuoaP.png)
compared to:
```
z <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species))+
geom_point(aes(text = Species))
ggplotly(z)
```
[](https://i.stack.imgur.com/umNin.png)
EDIT: custom text:
```
plot_ly(data = iris,
x = ~Sepal.Length,
y = ~Petal.Length,
color = ~Species,
hoverinfo = 'text',
text = ~paste(Species,
'', Petal.Length))
```
[](https://i.stack.imgur.com/uYOtW.png)
Upvotes: 4 [selected_answer]<issue_comment>username_2: To your second question in the comments (sorry for not leaving a comment - lacking the reputation to do so):
just supply a vector to the tooltip attribute, e.g.
```
ggplotly(produceMonthlyPlot, tooltip=c("QuantitySold","Product"))
```
With that you can control what should be displayed and what not.
Upvotes: 0 |
2018/03/21 | 734 | 2,304 | <issue_start>username_0: I have a column as below:
```
A
0 Australia
1 New Zealand
2 New Jersey,America
3 Hyderabad,India
```
I want to split it in two columns where there is ',' separator such as:
```
A B
0 Australia NaN
1 New Zealand NaN
2 New Jersey,America America
3 Hyderabad,India India
```
Any suggestion is welcomed<issue_comment>username_1: It is more flexible to customize the plots that are directly made in `plotly`, however the requested operation is also possible using `ggplotly`. Here is an example on the iris data set:
```
library(plotly)
library(ggplot)
```
To define the hover info:
```
plot_ly(data = iris,
x = ~Sepal.Length,
y = ~Petal.Length,
color = ~Species,
hoverinfo = 'text',
text = ~Species)
```
[](https://i.stack.imgur.com/ZEtCo.png)
to do so with ggplotly leave the text argument blank when calling ggplot:
```
z <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species))+
geom_point()
```
and set the argument `tooltip` to `ggplotly`:
```
ggplotly(z, tooltip="Species")
```
[](https://i.stack.imgur.com/FuoaP.png)
compared to:
```
z <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species))+
geom_point(aes(text = Species))
ggplotly(z)
```
[](https://i.stack.imgur.com/umNin.png)
EDIT: custom text:
```
plot_ly(data = iris,
x = ~Sepal.Length,
y = ~Petal.Length,
color = ~Species,
hoverinfo = 'text',
text = ~paste(Species,
'', Petal.Length))
```
[](https://i.stack.imgur.com/uYOtW.png)
Upvotes: 4 [selected_answer]<issue_comment>username_2: To your second question in the comments (sorry for not leaving a comment - lacking the reputation to do so):
just supply a vector to the tooltip attribute, e.g.
```
ggplotly(produceMonthlyPlot, tooltip=c("QuantitySold","Product"))
```
With that you can control what should be displayed and what not.
Upvotes: 0 |
2018/03/21 | 531 | 1,853 | <issue_start>username_0: I have a scenario where in I need to login only once per entire duration of the run and execute later requests n number of times. Brief explanation: Threads will be 1000 and duration will be 1 hour. We need to iterate the login request only once per the run (per 1000 users).But post login reuests have to be iterated many times (These requests can be sent to the server only after login). Please help me how can I achieve this in JMeter?<issue_comment>username_1: Put your "Login Request" under the [If Controller](http://jmeter.apache.org/usermanual/component_reference.html#If_Controller) and use the following code in "Condition" area:
```
${__groovy(ctx.getThreadNum() == 0 && vars.getIteration()==1,)}
```
This way your "Login Request" will be executed only once per 1000 threads/loops.
Demo:
[](https://i.stack.imgur.com/mvfKU.png)
References:
* [\_\_groovy function](https://jmeter.apache.org/usermanual/functions.html#__groovy)
* [JMeterContext](https://jmeter.apache.org/api/org/apache/jmeter/threads/JMeterContext.html) aka `ctx`
* [JMeterVariables](https://jmeter.apache.org/api/org/apache/jmeter/threads/JMeterVariables.html) aka `vars`
* [6 Tips for JMeter If Controller Usage](https://www.blazemeter.com/blog/six-tips-for-jmeter-if-controller-usage)
Upvotes: 1 <issue_comment>username_2: Put your Login request under [Once Only Controller](http://jmeter.apache.org/usermanual/component_reference.html#Once_Only_Controller) (can use right click -> Insert Parent menu).
>
> The Once Only Logic Controller tells JMeter to process the controller(s) inside it only once per Thread, and pass over any requests under it during further iterations through the test plan.
>
>
>
It'll be executed once per the run (per 1000 users).
Upvotes: 2 |
2018/03/21 | 856 | 3,024 | <issue_start>username_0: I want to execute VBA code, where the code itself is built from a string at runtime
I already found out how to do this via this existing SO answer:
[How to run a string as a command in VBA](https://stackoverflow.com/questions/43216390/how-to-run-a-string-as-a-command-in-vba)
For ease of reference, the solution is as follows:
```
Sub Testing()
StringExecute "MsgBox" & """" & "Job Done!" & """"
End Sub
Sub StringExecute(s As String)
Dim vbComp As Object
Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
vbComp.CodeModule.AddFromString "Sub foo()" & vbCrLf & s & vbCrLf & "End Sub"
Application.Run vbComp.Name & ".foo"
ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub
```
In a nutshell, it creates a new module within the same workbook; writes a sub according to the specified string; executes the sub; and then removes the module - all within the same runtime process. This works well.
However what if I want to perform the operation on any other workbook than ThisWorkbook? I'm trying the following modified code:
```
Option Explicit
Dim NewWB As Workbook
Sub Testing()
Set NewWB = Workbooks.Add
StringExecute "MsgBox" & """" & "Job Done!" & """"
End Sub
Sub StringExecute(s As String)
Dim vbComp As Object
Set vbComp = NewWB.VBProject.VBComponents.Add(1) ' Note the use of NewWB
vbComp.CodeModule.AddFromString "Sub foo()" & vbCrLf & s & vbCrLf & "End Sub"
Application.Run vbComp.Name & ".foo" ' <-- Error on this line
NewWB.VBProject.VBComponents.Remove vbComp
End Sub
```
As you can see, this code is identical but for the replacement of ThisWorkbook with NewWB. However it causes an error popup at the Application.Run line:
>
> *Run-time error '1004': Cannot run the macro 'Module1.foo'. The macro may not be available in this workbook or all macros may be disabled.*
>
>
>
Does anyone know why this wouldn't work with a new workbook? I already tried adding a reference to VBA Extensibility to the NewWB via code after creating it (NewWB.VBProject.References.AddFromGuid "{0002E157-0000-0000-C000-000000000046}", 5, 0) - however this did not help.<issue_comment>username_1: `Application.Run` will be looking for the module in the workbook creating the new workbook. Try (not fully tested) something along these lines:
```
application.run newwb.name & "!foo"
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Would you believe it - after 18 hours of scratching my head over this, I post a SO question and then within 5 minutes I realise the answer myself.
The problem was with the syntax of Application.Run. Apparently, it can be used in the format [ModuleName].[ProcedureName] when running a procedure in the calling workbook; but to specify another workbook, the syntax should be [WorkbookName]![ProcedureName].
So all I had to do was change the line to read:
```
Application.Run NewWB.Name & "!foo"
```
I thought that instead of deleting my question I should just answer it :)
Upvotes: 0 |
2018/03/21 | 551 | 1,887 | <issue_start>username_0: I have a problem with bash command output.
I want to save result of command to array and cut first part into [0] and seccond into [1]
```
result=$(findId PATTERN | tr -s " " | cut -d " " -f 1)
```
Output of findID is:
```
id errorcode nameOfProgramRunned
```
example:
```
12345 "compilation problem" fullScan.java
12346 "other problem" basicTest.java
```
I want to save `id` to `array[0]` and `nameofProgramRunned` to `array[1]`
Main problem is that I want to avoid executing command twice beacause result may be different.
Current code:
```
#!/bin/sh
echo 'Enter error code:'
read errorLine
result=$(findID PATTERN | awk '{print $1}')
while read -r line
do
dir="/proj/jobs/"$line"/screenlog.*"
if [ -e $dir ]
then
if grep -qi "$errorLine" $dir
then
echo -e "\e[101m$line:\e[49m"
grep $dir -i -e "$errorLine"
fi
fi
done <<<"$result"
```
I want to add nameOfProgramRunned to final grep
And I'm using bash<issue_comment>username_1: `Application.Run` will be looking for the module in the workbook creating the new workbook. Try (not fully tested) something along these lines:
```
application.run newwb.name & "!foo"
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Would you believe it - after 18 hours of scratching my head over this, I post a SO question and then within 5 minutes I realise the answer myself.
The problem was with the syntax of Application.Run. Apparently, it can be used in the format [ModuleName].[ProcedureName] when running a procedure in the calling workbook; but to specify another workbook, the syntax should be [WorkbookName]![ProcedureName].
So all I had to do was change the line to read:
```
Application.Run NewWB.Name & "!foo"
```
I thought that instead of deleting my question I should just answer it :)
Upvotes: 0 |
2018/03/21 | 791 | 2,469 | <issue_start>username_0: I use ssd\_mobilenet\_v1\_coco model with OpenCV for object detection.
```
cvNet = cv.dnn.readNetFromTensorflow('frozen_inference_graph.pb', 'graph.pbtxt')
```
When using original graph.pbtxt it is OK.
But when i create pbtxt file using tf\_text\_graph\_ssd
<https://github.com/opencv/opencv/blob/master/samples/dnn/tf_text_graph_ssd.py>
```
python tf_text_graph_ssd.py --input frozen_inference_graph.pb --output pbtxt/frozen_inference_graph.pbtxt
```
and then:
```
cvNet = cv.dnn.readNetFromTensorflow('frozen_inference_graph.pb', 'pbtxt/frozen_inference_graph.pbtxt')
```
it gives error:
```
OpenCV Error: Unspecified error (Input layer not found:
FeatureExtractor/MobilenetV1/zeros) in
cv::dnn::experimental_dnn_v3::`anonymous-
namespace'::TFImporter::populateNet, file C:
\projects\opencv-python\opencv\modules\dnn\src\tensorflow\tf_importer.cpp,
line 1061
Traceback (most recent call last):
File "opencv_tensorflow.py", line 3, in
cvNet = cv.dnn.readNetFromTensorflow('frozen\_inference\_graph.pb',
'pbtxt/frozen\_inference\_graph.pbtxt')
cv2.error: C:\projects\opencv-
python\opencv\modules\dnn\src\tensorflow\tf\_importer.cpp:1061: error: (-2)
Input layer not found: FeatureExtractor/MobilenetV1/zeros in function cv::d
nn::experimental\_dnn\_v3::`anonymous-namespace'::TFImporter::populateNet
```
What is the problem when converting pb to pbtxt?
Here my aim is create custom model using image retraining and use it on OpenCV.
<https://www.tensorflow.org/tutorials/image_retraining>
So I have a custom model but not pbtxt file.
First i try to create pbtxt for an example ssd\_mobilenet\_v1\_coco model.<issue_comment>username_1: I can create pbtxt file using tf\_text\_graph\_ssd.py with below command.
```
python tf_text_graph_ssd.py --input=C:\Users\Hp\Desktop\anas\Robomy\tfLearn\cell_inference_graph\frozen_inference_graph.pb --output=C:\Users\Hp\Desktop\anas\Robomy\tfLearn\cell_inference_graph\ssd_mobilenet_v1_balls_2018_05_20.pbtxt --config C:\Users\Hp\Desktop\anas\Robomy\tfLearn\data\ssd_mobilenet_v2_coco.config
```
this pbtxt worked perfectly on opencv
Upvotes: 1 <issue_comment>username_2: You have to specify config file as well. I consider if you have done transfer learning using tensorflow API, then you will find a file named pipeline.config along with frozen\_inference\_graph.pb file. Use that file as --config pipeline.config along with syntax. It should solve the problem.
Upvotes: 0 |
2018/03/21 | 1,500 | 3,556 | <issue_start>username_0: I have a dataframe like this:
```
Setting q02_id c_school c_home c_work c_transport c_leisure Country
Rural 11900006 0 5 3 1 1 Vietnam
Rural 11900031 10 5 0 0 0 China
Rural 11900033 0 3 0 0 3 Vietnam
Rural 11900053 0 7 2 0 0 Vietnam
Rural 11900114 3 6 0 0 0 Malaysia
Rural 11900446 0 6 0 0 0 Vietnam
```
and I would like to divide columns 2, 3, 4, 5, 6 by the total for that particular country.
Doing it in base R is a bit clumsy:
```
df[df$Country=="Vietnam",][c(3, 4, 5, 6)] = df[df$Country=="Vietnam",][c(3, 4, 5, 6)] / sum(df[df$Country=="Vietnam",][c(3, 4, 5, 6)])
```
(I think that works).
I'm trying to convert as much of my code as possible to use tidyverse functions. Is there a way of doing the same thing more efficiently using, `dplyr`, for instance?
Thanks.<issue_comment>username_1: I trust this is what you are after:
Divide each column by the sum of that column - grouped by Country
```
library(tidyverse)
df1 %>%
group_by(Country) %>%
mutate_at(vars(c_school: c_leisure), funs(./ sum(.)))
#output
Setting q02_id c_school c_home c_work c_transport c_leisure Country
1 Rural 11900006 NaN 0.238 0.600 1.00 0.250 Vietnam
2 Rural 11900031 1.00 1.00 NaN NaN NaN China
3 Rural 11900033 NaN 0.143 0 0 0.750 Vietnam
4 Rural 11900053 NaN 0.333 0.400 0 0 Vietnam
5 Rural 11900114 1.00 1.00 NaN NaN NaN Malaysia
6 Rural 11900446 NaN 0.286 0 0 0 Vietnam
```
or alternatively divide each column by the total sum for each country as in your example (only difference is I used columns 3:7 as I trust you intended.
```
df1 %>%
mutate(sum = rowSums(.[,3:7])) %>%
group_by(Country) %>%
mutate_at(vars(c_school: c_leisure), funs(./ sum(sum))) %>%
select(-sum)
#output
Setting q02_id c_school c_home c_work c_transport c_leisure Country
1 Rural 11900006 0 0.161 0.0968 0.0323 0.0323 Vietnam
2 Rural 11900031 0.667 0.333 0 0 0 China
3 Rural 11900033 0 0.0968 0 0 0.0968 Vietnam
4 Rural 11900053 0 0.226 0.0645 0 0 Vietnam
5 Rural 11900114 0.333 0.667 0 0 0 Malaysia
6 Rural 11900446 0 0.194 0 0 0 Vietnam
```
data:
```
df1 = read.table(text ="Setting q02_id c_school c_home c_work c_transport c_leisure Country
Rural 11900006 0 5 3 1 1 Vietnam
Rural 11900031 10 5 0 0 0 China
Rural 11900033 0 3 0 0 3 Vietnam
Rural 11900053 0 7 2 0 0 Vietnam
Rural 11900114 3 6 0 0 0 Malaysia
Rural 11900446 0 6 0 0 0 Vietnam", header = T)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I know you ask for `tidyverse` functions, but this is also a task where the `data.table` package shines:
```
library(data.table)
setDT(df)
df[, lapply(.SD, function(x) x / sum(x)), by = Country, .SDcols = 3:7]
Country c_school c_home c_work c_transport c_leisure
1: Vietnam NaN 0.2380952 0.6 1 0.25
2: Vietnam NaN 0.1428571 0.0 0 0.75
3: Vietnam NaN 0.3333333 0.4 0 0.00
4: Vietnam NaN 0.2857143 0.0 0 0.00
5: China 1 1.0000000 NaN NaN NaN
6: Malaysia 1 1.0000000 NaN NaN NaN
```
Upvotes: 2 |
2018/03/21 | 1,426 | 3,307 | <issue_start>username_0: I csv data file in below format:
```
1:
101
102
2:
103
104
105
3:
106
107
```
I want result as below in R
```
Value id
101 1
102 1
103 2
104 2
105 2
106 3
107 3
```
I did using for loop but it takes lot of time. Original data 3MB file.
Added extra column "m\_id" in test\_data dataframe and executed below code.
```
f <- function(x){
value = 0
if(endsWith(as.character(x) ,":") == TRUE){
value = substr(x,0,nchar(x)-1)
}
return (value)
}
for(row in 1:nrow(test_data)){
id = 0
id = f(as.character(test_data[row,1]))
if(id != 0){
m_id = id
}
test_data[row,2]<-m_id
}
```
How i can achieve the above requirement without for loop?<issue_comment>username_1: I trust this is what you are after:
Divide each column by the sum of that column - grouped by Country
```
library(tidyverse)
df1 %>%
group_by(Country) %>%
mutate_at(vars(c_school: c_leisure), funs(./ sum(.)))
#output
Setting q02_id c_school c_home c_work c_transport c_leisure Country
1 Rural 11900006 NaN 0.238 0.600 1.00 0.250 Vietnam
2 Rural 11900031 1.00 1.00 NaN NaN NaN China
3 Rural 11900033 NaN 0.143 0 0 0.750 Vietnam
4 Rural 11900053 NaN 0.333 0.400 0 0 Vietnam
5 Rural 11900114 1.00 1.00 NaN NaN NaN Malaysia
6 Rural 11900446 NaN 0.286 0 0 0 Vietnam
```
or alternatively divide each column by the total sum for each country as in your example (only difference is I used columns 3:7 as I trust you intended.
```
df1 %>%
mutate(sum = rowSums(.[,3:7])) %>%
group_by(Country) %>%
mutate_at(vars(c_school: c_leisure), funs(./ sum(sum))) %>%
select(-sum)
#output
Setting q02_id c_school c_home c_work c_transport c_leisure Country
1 Rural 11900006 0 0.161 0.0968 0.0323 0.0323 Vietnam
2 Rural 11900031 0.667 0.333 0 0 0 China
3 Rural 11900033 0 0.0968 0 0 0.0968 Vietnam
4 Rural 11900053 0 0.226 0.0645 0 0 Vietnam
5 Rural 11900114 0.333 0.667 0 0 0 Malaysia
6 Rural 11900446 0 0.194 0 0 0 Vietnam
```
data:
```
df1 = read.table(text ="Setting q02_id c_school c_home c_work c_transport c_leisure Country
Rural 11900006 0 5 3 1 1 Vietnam
Rural 11900031 10 5 0 0 0 China
Rural 11900033 0 3 0 0 3 Vietnam
Rural 11900053 0 7 2 0 0 Vietnam
Rural 11900114 3 6 0 0 0 Malaysia
Rural 11900446 0 6 0 0 0 Vietnam", header = T)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I know you ask for `tidyverse` functions, but this is also a task where the `data.table` package shines:
```
library(data.table)
setDT(df)
df[, lapply(.SD, function(x) x / sum(x)), by = Country, .SDcols = 3:7]
Country c_school c_home c_work c_transport c_leisure
1: Vietnam NaN 0.2380952 0.6 1 0.25
2: Vietnam NaN 0.1428571 0.0 0 0.75
3: Vietnam NaN 0.3333333 0.4 0 0.00
4: Vietnam NaN 0.2857143 0.0 0 0.00
5: China 1 1.0000000 NaN NaN NaN
6: Malaysia 1 1.0000000 NaN NaN NaN
```
Upvotes: 2 |
2018/03/21 | 666 | 1,948 | <issue_start>username_0: I have this enum :
```
object PhsIndType extends Enumeration{
type PhsIndType = Value
val A : Value = Value(1)
val R : Value= Value(2)
val O : Value = Value(3)
val E : Value = Value(4)
}
```
And i'm trying to load it into a map for easier use :
```
val map = PhsIndType.values.toMap[AnyVal, AnyVal]
```
I've tried using every type I could think of instead of AnyVal, but I always get the error :
```
Cannot prove that enumeration.PhsIndType.Value <:< (AnyVal, AnyVal).
val map = PhsIndType.values.toMap[AnyVal, AnyVal]
```
Anyone has a fix ?
Thanks for your time.<issue_comment>username_1: Use `toMap`
```
PhsIndType.values.map(x => x -> x.id).toMap
```
Type of the resultant map can be `Map[PhsIndType.Value,Int]`. You don't need to have `Map[AnyVal, AnyVal]`
Scala REPL
==========
```
scala> PhsIndType.values.map(x => x -> x.id).toMap
res14: scala.collection.immutable.Map[PhsIndType.Value,Int] = Map(A -> 1, R -> 2, O -> 3, E -> 4)
```
Upvotes: 0 <issue_comment>username_2: The signature of `toMap` is:
```
toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U]
```
That means that the underlying collection needs to have element of type `Tuple2`.
The type of `PhsIndType.values` is `PhsIndType.ValueSet` and not of type `Tuple2`
To achieve the desired result you want, you need to convert the underlying collection into type of `(T,U)` or `Tuple2` and you can this by mapping:
```
scala> :paste
// Entering paste mode (ctrl-D to finish)
object PhsIndType extends Enumeration {
type PhsIndType = Value
val A : Value = Value(1)
val R : Value= Value(2)
val O : Value = Value(3)
val E : Value = Value(4)
}
PhsIndType.values.map(x => (x.id, x)).toMap
// Exiting paste mode, now interpreting.
defined object PhsIndType
res0: scala.collection.immutable.Map[Int,PhsIndType.Value] = Map(1 -> A, 2 -> R, 3 -> O, 4 -> E)
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 991 | 2,483 | <issue_start>username_0: I have a dataframe that contains some `NaN`-values in a `t`-column. The values in the `t`-column belong to a certain `id` and should be the same per `id`:
```
df = pd.DataFrame({"t" : [4, 4, 1, 1, float('nan'), 2, 2, 2, float('nan'), 10],
"id": [1, 1, 2, 2, 3, 3, 3 , 3, 4, 4]})
```
Therefore, I would like to overwrite the `NaN` in `t` with the non-`NaN` in `t` for the respective `id` and ultimately end up with
```
df = pd.DataFrame({"t" : [4, 4, 1, 1, 2, 2, 2, 2, 10, 10],
"id": [1, 1, 2, 2, 3, 3, 3 , 3, 4, 4]})
```<issue_comment>username_1: New strategy... Create a map by dropping na and reassign using loc and mask.
```
import pandas as pd
df = pd.DataFrame({"t" : [4, 4, 1, 1, float('nan'), 2, 2, 2, float('nan'), 10],
"id": [1, 1, 2, 2, 3, 3, 3 , 3, 4, 4]})
# create mask
m = pd.isna(df['t'])
# create map
#d = df[~m].set_index('id')['t'].drop_duplicates()
d = df[~m].set_index('id')['t'].to_dict()
# assign map to the slice of the dataframe containing nan
df.loc[m,'t'] = df.loc[m,'id'].map(d)
print(df)
```
df returns:
```
id t
0 1 4.0
1 1 4.0
2 2 1.0
3 2 1.0
4 3 2.0
5 3 2.0
6 3 2.0
7 3 2.0
8 4 10.0
9 4 10.0
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Use [`sort_values`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html) with [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) and [`transform`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html) for same column with [`first`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html):
```
df['t'] = df.sort_values(['id','t']).groupby('id')['t'].transform('first')
```
Alternative solution is [`map`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html) by `Series` created by [`dropna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html) with [`drop_duplicates`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html):
```
df['t'] = df['id'].map(df.dropna(subset=['t']).drop_duplicates('id').set_index('id')['t'])
print (df)
id t
0 1 4.0
1 1 4.0
2 2 1.0
3 2 1.0
4 3 2.0
5 3 2.0
6 3 2.0
7 3 2.0
8 4 10.0
9 4 10.0
```
Upvotes: 2 |
2018/03/21 | 1,374 | 5,767 | <issue_start>username_0: In the activity\_main.xml I have a button that opens a AlertDialog with two textedit fields (dialog\_login.xml); but when I click on the "login" button, I try to store the textedit content in a string and I receive the following output:
"attempt to invoke virtual method on a null object reference".
I've noticed that if I put an EditText in the activity\_main.xml file with the same id of that in the alert dialog, I get no error, so the program look for an EditText in the activity\_main.xml, not in the dialog\_login.xml.
How can I do? Thanks
Here's my code:
MainActivity.java
```
public class MainActivity extends AppCompatActivity {
LayoutInflater inflater;
EditText mUsername;
EditText mPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button);
inflater = MainActivity.this.getLayoutInflater();
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v = inflater.inflate(R.layout.dialog_login, null);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setView(v);
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
mBuilder.setPositiveButton("Login", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
try
{ String username = mUsername.getText().toString(); }
catch(Exception e)
{ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); }
}
});
mBuilder.show();
}
});
}
}
```
activity\_main.xml
```
xml version="1.0" encoding="utf-8"?
```
dialog\_login.xml
```
xml version="1.0" encoding="utf-8"?
```<issue_comment>username_1: You `EditText` is not inside your Activity Layout you can not perform `findViewById` directly
Do `findViewById` like this
```
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
```
Instead of this
```
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
```
**`FYI`** You can use like this
```
mUsername = v.findViewById(R.id.username);
mPassword = v.findViewById(R.id.password);
```
Upvotes: 1 <issue_comment>username_2: You missed **dialog reference** before getting dialog views
your dialog reference is 'v'.
get your dialog views like this way
**mUserName = (EditText) dialogRefernce.findviewById(R.id.username);**
```
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
```
Your dialog reference saved into 'v'. Without using dialog(view) reference you cant get views.
Upvotes: 0 <issue_comment>username_3: I guess your Problem Here
```
v = inflater.inflate(R.layout.dialog_login, null);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setView(v);
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
```
and specifically here
```
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
```
thats Means you want to find your text In Activity Layout
FindViewById shoud be from layout where widgets is there
so this will be correct
```
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
```
Upvotes: 1 <issue_comment>username_4: This is because of you are not getting view from inflated layout.
**You just need to replace this**
```
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
```
**by this**
```
mUsername = (EditText)findViewById(R.id.username);
mPassword = (EditText)findViewById(R.id.password);
```
`v` is the actual view that contains your **EditText**.
by default findViewById getting view from Activity's binded layout that from **activity\_main** and it has not your dialog's EdiText, that's why it giving `NullPointerException`.
Upvotes: 0 <issue_comment>username_5: ```
The way you find ID is incorrect Please replace
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v = inflater.inflate(R.layout.dialog_login, null);
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setView(v);
mUsername = (EditText)v.findViewById(R.id.username);
mPassword = (EditText)v.findViewById(R.id.password);
mBuilder.setPositiveButton("Login", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int id)
{
try
{ String username = mUsername.getText().toString(); }
catch(Exception e)
{ Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show(); }
}
});
mBuilder.show();
}
});
}
```
Upvotes: 0 |
2018/03/21 | 877 | 3,472 | <issue_start>username_0: I'm using Firebase + Ionic in a project. my problem comes when loging out. I am subscribed to several `onSnapshot` events in some collections. I expect all subscriptions to be dismissed whenever the a user is logged out, but it is not like that, so whenever I logged out I receive several errors comming from Firebase:
>
> Uncaught Error in onSnapshot: Error: Missing or insufficient
> permissions.
>
>
>
Here my code:
### My controller
```
/**
* Logout button 'click' event handler
*/
onLogoutPressed(){
this.fbAuthServ.logout().then(() => {
this.navCtrl.setRoot(LoginPage);
});
}
```
### My service provider
```
// Firebase Modules
import { AngularFireAuth } from 'angularfire2/auth';
constructor(private afAuth: AngularFireAuth, private utils: UtilsProvider){}
...
/**
* Firebase Logout the current user
*/
async logout(){
this.afAuth.auth.signOut();
}
```
Could you please tell me what should I do to avoid those `Missing or insufficient permissions` errors??
Thank you in advance!
EDIT: How I get subscribe to onSnapshot events
==============================================
### Controller
```
ionViewDidEnter(){
this.fbDataServ.getPlacesByUserAllowed().onSnapshot(placeReceived=> {
this.placesByUserAllowed = placeReceived.docs.map(placeSnapshot => {
return this.utils.mapPlaceSnapshot(placeSnapshot )
});
this._concatPlaces();
//Dismiss loading whenever we have data available
this.utils.dismissLoading();
});
```
### Service Provider
```
// Firebase
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
constructor(private afs: AngularFirestore, private fbAuthServ: FirebaseAuthServiceProvider, private utils: UtilsProvider) { }
placesCollection: AngularFirestoreCollection = this.afs.collection("places");
/\*\*
\* Gets the collection of places where the user is 'allowed'
\*/
public getPlacesByUserAllowed(){
return this.placesCollection.ref
.where('users.' + this.fbAuthServ.getCurrentUser().uid + '.allowed', '==', true);
}
```<issue_comment>username_1: Since the error message mentions `onSnapshot` I assume you're accessing the Firebase Database or Cloud Firestore somewhere in your code.
The data that you're reading from the database has security rules configured that require that the user is authenticated. So when you log the user out, that requirement is no longer met, the app loses access to that data, and the observer is canceled.
To prevent this error from appearing, remove the observer before logging the user out.
**Update**
To remove the observer/listener follow the patterns shown in the [Firestore documentation on detaching a listener](https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener). First keep a reference to the return value you get from `onSnapshot`.
```
var unsubscribe = this.fbDataServ.getPlacesByUserAllowed().onSnapshot(placeReceived=> {
```
Then call that `unsubscribe()` just before signing the user out like this:
```
unsubscribe();
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Here's the updated link and code as of August 30th 2021:
<https://firebase.google.com/docs/firestore/query-data/listen#handle_listen_errors>
Here's the code:
```js
let listener = db.collection("cities").addSnapshotListener { querySnapshot, error in
// ...
}
// Stop listening to changes
listener()
```
Upvotes: 0 |
2018/03/21 | 621 | 2,001 | <issue_start>username_0: As I am trying to compare these doubles, it won't seem to be working correctly
Here it goes: (This is exactly my problem)
```
#include
#include
int main () {
int i\_wagen;
double dd[20];
dd[0]=0.;
dd[1]=0.;
double abstand= 15.;
double K\_spiel=0.015;
double s\_rel\_0= K\_spiel;
int i;
for(i=1; i<=9; i++)
{
i\_wagen=2\*(i-1)+2;
dd[i\_wagen]=dd[i\_wagen-1]-abstand;
i\_wagen=2\*(i-1)+3;
dd[i\_wagen]=dd[i\_wagen-1]-s\_rel\_0;
}
double s\_rel=dd[3-1]-dd[3];
if((fabs(s\_rel) - K\_spiel) == 0.)
{
printf("yes\n");
}
return(0);
}
```
After executing the programm, it wont print the yes.<issue_comment>username_1: Since the error message mentions `onSnapshot` I assume you're accessing the Firebase Database or Cloud Firestore somewhere in your code.
The data that you're reading from the database has security rules configured that require that the user is authenticated. So when you log the user out, that requirement is no longer met, the app loses access to that data, and the observer is canceled.
To prevent this error from appearing, remove the observer before logging the user out.
**Update**
To remove the observer/listener follow the patterns shown in the [Firestore documentation on detaching a listener](https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener). First keep a reference to the return value you get from `onSnapshot`.
```
var unsubscribe = this.fbDataServ.getPlacesByUserAllowed().onSnapshot(placeReceived=> {
```
Then call that `unsubscribe()` just before signing the user out like this:
```
unsubscribe();
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Here's the updated link and code as of August 30th 2021:
<https://firebase.google.com/docs/firestore/query-data/listen#handle_listen_errors>
Here's the code:
```js
let listener = db.collection("cities").addSnapshotListener { querySnapshot, error in
// ...
}
// Stop listening to changes
listener()
```
Upvotes: 0 |
2018/03/21 | 1,341 | 3,585 | <issue_start>username_0: I want my section background look like as shown in the image at the end, how can i do that using css?
```css
.bg{
width: 400px;
height: 200px;
padding: 20px;
text-align: center;
border: 1px solid #000;
background: red;
color: #fff;
display: flex;
}
.bg p{
text-align: center;
margin: auto;
font-size: 36px;
}
```
```html
Section Content
```
[](https://i.stack.imgur.com/FRD6d.jpg)<issue_comment>username_1: You can consider multiple background using `linear-gradient` like below without the need of extra elements:
```css
.bg{
width: 400px;
height: 220px;
padding: 50px 0;
box-sizing:border-box;
text-align: center;
background:
linear-gradient(to bottom left , red 50%,transparent 51%) bottom left,
linear-gradient(to bottom left , transparent 49%,red 50%) top left,
linear-gradient(to bottom right, red 50%,transparent 51%) bottom right,
linear-gradient(to bottom right, transparent 49%,red 50%) top right,
red content-box;
background-size:50% 50px;
background-repeat:no-repeat;
color: #fff;
display: flex;
}
.bg p{
text-align: center;
margin: auto;
font-size: 36px;
}
```
```html
Section Content
```
But in case you need border around I would then consider pseudo-elements like this:
```css
.bg{
width: 400px;
height: 200px;
padding: 20px;
text-align: center;
position:relative;
color: #fff;
display: flex;
z-index:0;
}
.bg:before,
.bg:after{
content:"";
position:absolute;
top:0;
bottom:0;
background:red;
border:2px solid #000;
z-index:-1;
}
.bg:before {
right:50%;
left:0;
transform:skewY(15deg);
transform-origin:top left;
border-right:none;
}
.bg:after {
left:50%;
right:0;
transform:skewY(-15deg);
transform-origin:top right;
border-left:none;
}
.bg p{
text-align: center;
margin: auto;
font-size: 36px;
}
```
```html
Section Content
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use [clip-path](https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path) to do such things and create them using [this tool](http://bennettfeely.com/clippy/).
```css
.bg {
width: 400px;
height: 200px;
padding: 20px;
text-align: center;
border: 1px solid #000;
background: red;
color: #fff;
display: flex;
-webkit-clip-path: polygon(100% 0, 100% 80%, 50% 100%, 0 80%, 0 0, 50% 20%);
clip-path: polygon(100% 0, 100% 80%, 50% 100%, 0 80%, 0 0, 50% 20%);
}
.bg p {
text-align: center;
margin: auto;
font-size: 36px;
}
```
```html
Section Content
```
Upvotes: 1 <issue_comment>username_3: You can do as follows to get shape you needed.
```css
.left {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
width: 150px;
height: 200px;
border: none;
color: rgba(0,0,0,1);
-o-text-overflow: clip;
text-overflow: clip;
background: #1abc9c;
-webkit-transform: skewY(15deg);
transform: skewY(15deg);
float: left;
margin-top: 20px;
}
.right {
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
width: 150px;
height: 200px;
border: none;
color: rgba(0,0,0,1);
-o-text-overflow: clip;
text-overflow: clip;
background: #1abc9c;
-webkit-transform: skewY(-15deg);
transform: skewY(-15deg);
float: left;
margin-top: 20px;
}
```
```html
Hello
World
```
Upvotes: -1 |
2018/03/21 | 541 | 1,732 | <issue_start>username_0: I have a function defined like...
```
def create_button(content)
title = content.dig(0, 'text')
url = content.dig(0, 'url')
return nil if title.nil? || url.nil?
return Button.new(
title,
url
)
end
```
Or something...
Anyway, I was wondering if it would be possible to smoosh those first few lines together and do the assignment, nil check and return in one line?<issue_comment>username_1: Anything like this?
```
def create_button(content)
title, url = content[0]&.values_at('text', 'url')
return nil if title.nil? || url.nil?
Button.new(title, url)
end
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can multiple assign values like this:
```
a, b = 'a', 'b'
```
When you have one result, like `return nil`, you could have two conditions in your if.
```
return nil if a.nil? or b.nil?
```
Or use `any?`
```
return nil if [a, b].any?(&:nil?)
```
So, the & symbol here is a shortcut to create a lambda, or reusable code block. It will try to run the method `nil?` on each item in the array. You can use this for other enumerable methods such as `each`, `select`, `reject` or `detect`.
Here's a nice short form of your method, doing all the same things:
```
def create_button(content)
title, url = content.dig(0, 'text'), content.dig(0, 'url')
return nil if [title,url].any(&:nil?)
return Button.new(title, url)
end
```
Upvotes: 1 <issue_comment>username_3: What you could do is
```
def create_button(content)
title = content.dig(0, 'text')
url = content.dig(0, 'url')
return nil if title.nil? || url.nil?
return Button.new(
title,
url
)
end
```
because either the title or url is nil you are returning nil.
Upvotes: 0 |
2018/03/21 | 640 | 2,098 | <issue_start>username_0: I'm trying to validate the all the components of the form using
`'formName'.valid` in Type Script.
I want to validate the "home form's all the fields" .In here I create the input field and validate using the validator.
If the form is valid "Home Form is valid" alert should be popped up,if not "Home Form is invalid" should be popped up.
The else part ("Home Form is invalid") is working when the form is invalid. But the if part ("Home Form is valid) is not working the when the form is valid.
I wrote the below code in constructor.
How to solve this problem?
```
if (this.homeForm.valid) {
alert("Home Form is valid");
}
else {
alert("Home Form is invalid");
}
```
[**Source Code-StackBlitz**](https://stackblitz.com/edit/angular-tr3yx5)<issue_comment>username_1: Anything like this?
```
def create_button(content)
title, url = content[0]&.values_at('text', 'url')
return nil if title.nil? || url.nil?
Button.new(title, url)
end
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can multiple assign values like this:
```
a, b = 'a', 'b'
```
When you have one result, like `return nil`, you could have two conditions in your if.
```
return nil if a.nil? or b.nil?
```
Or use `any?`
```
return nil if [a, b].any?(&:nil?)
```
So, the & symbol here is a shortcut to create a lambda, or reusable code block. It will try to run the method `nil?` on each item in the array. You can use this for other enumerable methods such as `each`, `select`, `reject` or `detect`.
Here's a nice short form of your method, doing all the same things:
```
def create_button(content)
title, url = content.dig(0, 'text'), content.dig(0, 'url')
return nil if [title,url].any(&:nil?)
return Button.new(title, url)
end
```
Upvotes: 1 <issue_comment>username_3: What you could do is
```
def create_button(content)
title = content.dig(0, 'text')
url = content.dig(0, 'url')
return nil if title.nil? || url.nil?
return Button.new(
title,
url
)
end
```
because either the title or url is nil you are returning nil.
Upvotes: 0 |
2018/03/21 | 1,471 | 5,311 | <issue_start>username_0: In Explorer sequence `Shift+F10 -> open command window here` opens cmd in current directory.
Is there any way to do the same via shortcuts to launch cmd with administration rights?<issue_comment>username_1: 1. Simply open cmd prompt from start as Run as Administrator,
2. Copy the path where you want to execute using location/Address Bar
3. Use CD space paste the address and press Enter
It will set to the desired folder path
Upvotes: 3 <issue_comment>username_1: Complete shortcuts are listed here
[Link to the answer](http://www.zdnet.com/article/windows-10-tip-the-fastest-smartest-ways-to-open-a-command-prompt/)
1. Right-click Start & choose Command Prompt or Command Prompt (Admin) from the Quick Link menu. You can also use keyboard shortcuts for this route: Windows key + X, followed by C (non-admin) or A (admin).
2. Type cmd in the search box, then press Enter to open the highlighted Command Prompt shortcut. To open the session as an administrator, press Alt+Shift+Enter.
3. From File Explorer, click in the address bar to select its contents; then type cmd and press Enter. That opens a non-admin Command Prompt session in the current folder.
4. In a File Explorer window, hold down Shift as you right-click on a folder or drive. That opens a non-admin Command Prompt session in the selected location.
5. To open an administrative Command Prompt window in the current folder, use this hidden Windows 10 feature: Navigate to the folder you want to use, then hold Alt and type F, S, A (that keyboard shortcut is the same as switching to the File tab on the ribbon, then choose Open command prompt as administrator).
Upvotes: 7 [selected_answer]<issue_comment>username_2: I added the commands to the Explorer context menu in the registry for the background, folders, and files.
I know that you wanted a keyboard shortcut. I am hoping that you can use and adapt the commands and use the existing Windows shortcut system that allows you to set keyboard shortcuts.
Here is a link to an article that has the commands and a link to a ZIP with a REG file:
<https://dkcool.tailnet.net/2019/05/add-open-admin-command-prompt-to-the-explorer-context-menu-in-windows-10/#tldr/>
>
> **Adding to the Windows registry:**
>
>
> **For the folder context-menu: (right-clicking on a folder in an explorer window)**
>
>
> `powershell -WindowStyle Hidden "start cmd \"/k cd /d %1\" -v runAs"`
>
>
> **For the background context-menu: (right-clicking on the background of
> an explorer window):**
>
>
> `powershell -WindowStyle Hidden "start cmd \"/k cd /d %V\" -v runAs"`
>
>
> **For the file context-menu: (right-clicking on a file in an Explorer
> window):**
>
>
> `powershell -WindowStyle Hidden "start cmd \"/k cd /d %w\" -v runAs"`
>
>
>
Here is a link to an article about the shell variables:
<https://superuser.com/questions/136838/which-special-variables-are-available-when-writing-a-shell-command-for-a-context>
**EDIT:**
I added keyboard shortcuts using Shift+F10, Shift+Context menu key, or Shift-Right click, and then a given letter for the desired option, which you can modify in the registry. I put all of the files onto GitHub at the link below.
<https://github.com/DKCTC/windows-terminal-admin-shortcuts-registry>
Upvotes: 2 <issue_comment>username_3: You can run a script in PowerShell something like below you can just have the syntax checked and can try implementing below sample
```
powershell changepath.sh
changepath.sh
CD $args[0]
chmod rwxrwxrwx user ...
```
Upvotes: -1 <issue_comment>username_4: I also needed the same so as to initiate my angular development test easier.
However without running Command prompt as an administrator 'ng serve' won't work.
Had been using Git Bash for a while. [Git Bash website](https://git-scm.com/download/win)
So I chose Gitbash to initiate the same, from the root folder of the app.
[Right Clicked inside the root folder and Chose Git Bash Here]
and ran the command 'ng serve'. The build was compiled and I was able to access the port[4200].
Upvotes: 0 <issue_comment>username_5: You can open the PowerShell by holding ALT and typing S->M->A. Then in the PS type cmd to move to cmd.
Upvotes: 0 <issue_comment>username_6: You can use powershell as well. It will be easy.
>
> 1. Go to your file location
> 2. PRESS **Alt + F + S + A** or **Alt + f + s + a**
>
>
>
Upvotes: 2 <issue_comment>username_7: If youre looking for a lazy solution which does not get you into powershell, you can use [this nice script](https://sites.google.com/site/eneerge/scripts/batchgotadmin) to run a batch file as admin. The only thing you have to do is add cmd.exe at the end. Place this batch file inside the folder you want and run it.
Upvotes: 0 <issue_comment>username_8: you can try to paste following command into .reg file and run:
```
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\Background\shell\AdminOpenCmd]
@="Open CMD here admin"
"Icon"="cmd.exe"
[HKEY_CLASSES_ROOT\Directory\Background\shell\AdminOpenCmd\command]
@="PowerShell -windowstyle hidden -Command \"Start-Process cmd.exe -ArgumentList '/s,/k, pushd,%V' -Verb RunAs\""
```
This command could open a cmd window and change current path as admin, but this will flashed powershell window in start.
Upvotes: 0 |
2018/03/21 | 429 | 1,647 | <issue_start>username_0: How can I remove a row by using Truncate in SQL instead of delete by using WHERE condition?
Truncate only use to remove the table or row? if can remove the row by truncate, let me know anyone<issue_comment>username_1: You can't. Only `DELETE` statements can have a `WHERE` condition on them, `TRUNCATE` removes all rows.
From [MSDN](https://learn.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql) :
>
> Removes all rows from a table or specified partitions of a table,
> without logging the individual row deletions. TRUNCATE TABLE is
> similar to the DELETE statement with no WHERE clause; however,
> TRUNCATE TABLE is faster and uses fewer system and transaction log
> resources.
>
>
>
Upvotes: 2 <issue_comment>username_2: You can only remove a single row with truncate if that row is the only one in the table.
Upvotes: 1 <issue_comment>username_3: [`Truncate`](https://learn.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql) is not like [`delete`](https://learn.microsoft.com/en-us/sql/t-sql/statements/delete-transact-sql).
You can't use truncate to delete specific rows.
In fact, the statement is `truncate table` - you can't truncate anything other then a full table.
Truncate will remove all rows from the table, and is only allowed if the table is not referenced by foreign keys, is not used as the basis of an indexed view, and is not published by transactional replication or merge replication.
Also, `truncate table` can't be executed inside a transaction.
`Truncate table` will also reset the identity column of the table (if one exists).
Upvotes: 1 |
2018/03/21 | 919 | 3,187 | <issue_start>username_0: I am currently, going through [this article](https://mvanier.livejournal.com/2897.html) on Y-combinator by [<NAME>](http://users.cms.caltech.edu/~mvanier/).
Along the way of Y-combinator derivation, this code:
```
(define (part-factorial self)
(lambda (n)
(if (= n 0)
1
(* n ((self self) (- n 1))))))
((part-factorial part-factorial) 5) ==> 120
(define factorial (part-factorial part-factorial))
(factorial 5) ==> 120
```
is worked out to:
```
(define (part-factorial self)
(let ((f (self self)))
(lambda (n)
(if (= n 0)
1
(* n (f (- n 1)))))))
(define factorial (part-factorial part-factorial))
(factorial 5) ==> 120
```
After that, article states:
>
> This will work fine in a lazy language. In a strict language, the `(self self)` call in the let statement will send us into an infinite loop, because in order to calculate `(part-factorial part-factorial)` (in the definition of factorial) you will first have to calculate (part-factorial part-factorial) (in the `let` expression).
>
>
>
and then reader is challenged:
>
> For fun: figure out why this wasn't a problem with the previous definition.
>
>
>
It seems to me I've figured out why, though I would like to confirm that:
1. I am correct in my understanding.
2. I don't miss any critical points, in my understanding.
My understanding is: in the first code snippet `(self self)` call won't result into infinite loop, because it is contained (wrapped) into `lambda` as a `part-factorial` function, and thus evaluated to `lambda (n)` until the call to `(self self)` is actually made, which happens only for `n > 0`. Thus, after `(= n 0)` evaluates to `#t`, there is no need in calling `(self self)`.<issue_comment>username_1: You can't. Only `DELETE` statements can have a `WHERE` condition on them, `TRUNCATE` removes all rows.
From [MSDN](https://learn.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql) :
>
> Removes all rows from a table or specified partitions of a table,
> without logging the individual row deletions. TRUNCATE TABLE is
> similar to the DELETE statement with no WHERE clause; however,
> TRUNCATE TABLE is faster and uses fewer system and transaction log
> resources.
>
>
>
Upvotes: 2 <issue_comment>username_2: You can only remove a single row with truncate if that row is the only one in the table.
Upvotes: 1 <issue_comment>username_3: [`Truncate`](https://learn.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql) is not like [`delete`](https://learn.microsoft.com/en-us/sql/t-sql/statements/delete-transact-sql).
You can't use truncate to delete specific rows.
In fact, the statement is `truncate table` - you can't truncate anything other then a full table.
Truncate will remove all rows from the table, and is only allowed if the table is not referenced by foreign keys, is not used as the basis of an indexed view, and is not published by transactional replication or merge replication.
Also, `truncate table` can't be executed inside a transaction.
`Truncate table` will also reset the identity column of the table (if one exists).
Upvotes: 1 |
2018/03/21 | 473 | 1,820 | <issue_start>username_0: I want to display the status of a user.If the user will be online then I have to show green icon on the user profile.If a user will be offline then I have to show grey icon and it might be possible that user will be logged in but not active in that case I have to display orange icon(for the idle user) on the profile.
I have to implement this feature in ASP.NET.<issue_comment>username_1: You can't. Only `DELETE` statements can have a `WHERE` condition on them, `TRUNCATE` removes all rows.
From [MSDN](https://learn.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql) :
>
> Removes all rows from a table or specified partitions of a table,
> without logging the individual row deletions. TRUNCATE TABLE is
> similar to the DELETE statement with no WHERE clause; however,
> TRUNCATE TABLE is faster and uses fewer system and transaction log
> resources.
>
>
>
Upvotes: 2 <issue_comment>username_2: You can only remove a single row with truncate if that row is the only one in the table.
Upvotes: 1 <issue_comment>username_3: [`Truncate`](https://learn.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql) is not like [`delete`](https://learn.microsoft.com/en-us/sql/t-sql/statements/delete-transact-sql).
You can't use truncate to delete specific rows.
In fact, the statement is `truncate table` - you can't truncate anything other then a full table.
Truncate will remove all rows from the table, and is only allowed if the table is not referenced by foreign keys, is not used as the basis of an indexed view, and is not published by transactional replication or merge replication.
Also, `truncate table` can't be executed inside a transaction.
`Truncate table` will also reset the identity column of the table (if one exists).
Upvotes: 1 |
2018/03/21 | 1,448 | 5,565 | <issue_start>username_0: This is my Custom List Adapter Class :
```
class MyAdapter extends ArrayAdapter {
private int resourceId;
String name="";
String phone;
private ArrayList sites = null;
private Context context;
private static class ViewHolder{
TextView RideDetails;
EditText mEdit;
}
public MyAdapter(Context context, int resource, ArrayList objects,String phone) {
super(context, resource, objects);
this.context = context;
this.resourceId = resource;
this.sites = objects;
this.phone=phone;
}
@Override
public String getItem(int position) {
return sites.get(position);
}
@Override
public int getCount() {
return sites.size();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
name = getItem(position);
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.home\_resource, parent, false);
}
TextView mTextView = (TextView) view.findViewById(R.id.ridedetails);
mTextView.setText(name);
Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Name",name);
String ridetrackno=name.substring(name.indexOf(":")+1,name.indexOf("Source")-2);
EditText mEdit;
mEdit = (EditText) view.findViewById(R.id.PriceQuotation);
String fare=mEdit.getText().toString();
String myUrl=".....API URL....."+phone+"/"+ridetrackno+"/"+fare;
Log.d("URL",myUrl);
HttpGetRequest getRequest = new HttpGetRequest();
try{
String result = getRequest.execute(myUrl).get();
Log.d("Details:",result);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
return view;
}
}
```
This is my resource\_file in which items are injected through REST API :
```
xml version="1.0" encoding="utf-8"?
```
Structure of List View :
Each list item is composed of a TextView(whose details I am able to get),Edit Text(causing Exception) and a simple button whose onClick function has been written.
**Now I am facing two problems:**
1. ***mEdit Reference*** : The program is failing with a null pointer exception when I am trying to get the text entered in Edit Text when button in a list item is clicked.
2. ***Always Last List Item is picked up*** : Irrespective of which button is clicked, the content of last TextView is only returned.<issue_comment>username_1: 1. Adapter will get all views in getView method at once, you trying to getting edittext in button click listener
write this line outside button click listener
```
final EditText mEdit = (EditText) view.findViewById(R.id.PriceQuotation);
```
2.
```
final TextView mTextView = (TextView) view.findViewById(R.id.ridedetails);
```
Inside button click listener
```
String vlaue = mTextView.getText().toString();
```
getView() Code :
```
@Override
public View getView ( final int position, View convertView, ViewGroup parent){
name = getItem(position);
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.home_resource, parent, false);
}
final TextView mTextView = (TextView) view.findViewById(R.id.ridedetails);
mTextView.setText(name);
final EditText mEdit = (EditText) view.findViewById(R.id.PriceQuotation);
Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String vlaue = mTextView.getText().toString();
Log.d("Name", vlaue);
String ridetrackno = vlaue.substring(vlaue.indexOf(":") + 1, vlaue.indexOf("Source") - 2);
String fare = mEdit.getText().toString();
String myUrl = ".....API URL....." + phone + "/" + ridetrackno + "/" + fare;
Log.d("URL", myUrl);
HttpGetRequest getRequest = new HttpGetRequest();
try {
String result = getRequest.execute(myUrl).get();
Log.d("Details:", result);
} catch (Exception e) {
e.printStackTrace();
}
}
});
return view;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You needed to put `EditText mEdit` either out of the `Button`'s `onClick()` event or you need to change object name of `view` as coded below
```
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
name = getItem(position);
View childView = convertView;
if (childView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
childView = inflater.inflate(R.layout.home_resource, parent, false);
}
TextView mTextView = (TextView) childView.findViewById(R.id.ridedetails);
mTextView.setText(name);
Button mButton = (Button) childView.findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText mEdit = (EditText) childView.findViewById(R.id.PriceQuotation);
}
});
}
```
Because `view` will be referred inside as button hence we named the main view to `childView`.
This will not give you `NullPointerException`.
Upvotes: 1 <issue_comment>username_3: For 2. inside `onClick` Try :
```
String namePos = getItem(position);
ridetrackno=namePos.substring(namePos.indexOf(":")+1,namePos.indexOf("Source")-2);
```
Hope this helps
Upvotes: 0 |
2018/03/21 | 596 | 2,235 | <issue_start>username_0: I've been trying to pull values from an enum and store them as a String in an array. However, depending on a variable, the values have to be unique, i.e. the same value can't be used twice.
I've used the following code to pull values:
```
public enum Colour
{
ROOD, GEEL, GROEN, BLAUW, PAARS;
public Colour getRandomColour(Random rn)
{
return values()[rn.nextInt(values().length)];
}
}
```
However, this can give duplicate values.
It seems that the values of my enum refuse to be put in code blocks. Sorry!
EDIT:
```
for (int i = 0; i < code.length; i++)
code[i] = kleur.getRandomColour(rn).toString();
```
It fills up the array 'code'. The array-length depends on several factors but it will always be smaller than or equal to the amount of values in the enum.<issue_comment>username_1: You could populate a list with all values from your `Colour` enum, shuffle, and then just access values sequentially:
```
List colourList = Arrays.asList(Colour.values());
Collections.shuffle(colourList);
```
Then, just iterate the list and access the colors in order, which of course should be random since the collection was shuffled:
```
for (Colour c : colourList) {
// do something with c
}
```
You could also go with your current approach, and store the colors into a set, rather than an ArrayList. But the problem there is that you may draw a duplicate value any number of times, and the chances of that happening as the set increases in size will go up.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Use a temporary list to check if the new value already exist and continue to generate a new value until a unique is found.
```
for (int i = 0; i < code.length; i++) {
String next = kleur.getRandomColour(rn).toString();
List tempList = Arrays.arrayAsList(code);
while (tempList.contains(next);
next = kleur.getRandomColour(rn).toString();
}
code[i] = next;
}
```
Upvotes: 0 <issue_comment>username_3: For those still wondering, I might have found a good solution.
Store the values of the array in an ArrayList. Using a for-loop to pull a value from the ArrayList then remove that index, essentially eliminating duplicates.
Upvotes: 0 |
2018/03/21 | 602 | 1,986 | <issue_start>username_0: When I was going to install my new codeigniter project. I got the error
>
> Fatal error: session\_start(): Failed to initialize storage module: user (path:
> C:\xampp\tmp) in C:\xampp\htdocs\Tetavendor\system\libraries\Session\Session.php
> on line 140
>
>
>
And I've found the similar question in stackoverflow
[PHP 7 user sessions issue - Failed to initialize storage module](https://stackoverflow.com/questions/34125849/php-7-user-sessions-issue-failed-to-initialize-storage-module/43551298)
But none of the solutions worked for me. My codeigniter version is 3.0.0. So how can solve this issue?<issue_comment>username_1: Just add a correct path to store session.
Example : Goto config file & replace
```
$config['sess_save_path'] = NULL;
```
With
```
$config['sess_save_path'] = APPPATH . 'cache/session/';
```
Don't forget to make 0777 permission to Cache folder.
Upvotes: 4 <issue_comment>username_2: I hope you have resolved this issue by now.
In my case, my session information is stored in the database.
```
$config['sess_use_database'] = TRUE;
```
The error was actually meaning that the database, aka storage, was not accessible. In my logs under /application/logs/, it had an error
>
> -> Unable to connect to the database
>
>
>
Set the ['db\_debug'] to TRUE and it will give you further tips on your particular issue.
```
$db['default']['db_debug'] = TRUE;
```
However, maybe it is the same issue that I encountered. The database hostname as 'localhost', which was perfectly fine until I upgraded MySql to 5.7 on my Mac High Sierra 10.13.6. Switching 'localhost' to '127.0.0.1' fixed the issue (for me).
```
$db['default']['hostname'] = '127.0.0.1';
```
This is from my /application/config/database.php file. I apologize if your system doesn't have the same config file. I inherited this codebase and I have never worked on another Codeigniter application before.
I do hope this helps someone.
Upvotes: 0 |
2018/03/21 | 603 | 2,624 | <issue_start>username_0: Refer to [Why are Azure Resource Groups associated with a specific region?](https://stackoverflow.com/questions/32406410/why-are-azure-resource-groups-associated-with-a-specific-region)
Say that I have a Resource Group A that has been deployed to the Australia South East Region.
In Resource Group A, I have resources that are deployed to multiple regions:
* Resource B - Australia South East
* Resource C - Australia East
Suppose that Australia South East Region has a complete outage. I understand that Resource B will be unavailable and that I will not be able to complete deployments into Resource Group A, as its metadata is also stored in Australia South East Region.
However, I'm interested in what the limitations associated with Resource C are? For example, if Resource C is a VM, can I shutdown/start/restart? Can I add a firewall rule? Can I make any other config changes in Portal or via Powershell/CLI?
I can't find this documented in detail anywhere and really need to understand what these restrictions are.
Can anyone help?
Thanks in advance.<issue_comment>username_1: It will all depend on what resources are located where. For example, as long as any dependent resources are not located in the down data center you should be fine. Such as having a storage outage in A but VMs hosted in B.
Azure offers a great deal of resiliency to outages and many ways for you to build and configure for high availability. Each of this configurations will different based on the service you are using.
So there is not a simple answer to your question as there are many variables involved. Generally it is suggested that a resource group should hold everything related to one project. So if you have a SQL farm all resources should be put into the same resource group. Then if you are done with the farm you simply delete the RG.
Upvotes: 0 <issue_comment>username_2: When the region a resource group is contained in is offline, you cannot perform any *write* operations to that resource group (which is not the same as a write to a resource in the group). Reads are fine as the storage for the metadata is redundant. So in your example, you could do anything you want to resource C as long as it doesn't require a write to the resource group.
There aren't very many operations that write to a group (add a tag to a RG, move a resource to/from a resource group and as you noted deploy to it). If you wanted to add an NSG to the NIC for the VM that should be fine as long as the NSG could be in a different resource group (or already existed).
That help?
Upvotes: 3 [selected_answer] |
2018/03/21 | 2,008 | 5,942 | <issue_start>username_0: I have an array with objects that looks like this:
```
[{
id: 34,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'Steven',
age: 24
}]
} ,{
id: 35,
users: [{
name: 'John',
age: 23,
}, {
name: 'Steven',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 36,
users: [{
name: 'Lisa',
age: 23,
}, {
name: 'John',
age: 24
}, {
name: 'Homer',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 37,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'John',
age: 24
}]
}]
```
I want to order the array based on a couple of conditions (prioritized):
First I want the objects that have users with name 'John' AND 'Lisa' and number of users is less than 3
Secondly I want the objects that have users with name 'John' AND 'Lisa' regardless of the number of participants
Then the rest of the objects
So, the array that I put as an example, would become:
```
[{
id: 37,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'John',
age: 24
}]
}, {
id: 36,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'John',
age: 24
}, {
name: 'Homer',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 34,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'Steven',
age: 24
}]
}, {
id: 35,
users: [{
name: 'John',
age: 23
}, {
name: 'Steven',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}]
```
I have this right now, which properly sorts based on the names AND number of participants. But if the number of participants doesn't match, then it doesn't care about the names to sort, which is wrong:
```
const names = ['John', 'Lisa']
unorderedLeagues.sort((a, b) => {
const aUserIncluded = every(names, priorityName =>
some(a.users, { name: priorityName }),
);
const bUserIncluded = every(names, priorityName =>
some(b.users, { name: priorityName }),
);
return (
(bUserIncluded && b.users.length <= 3) -
(aUserIncluded && a.users.length <= 3)
);
});
```
How should I modify this sorting to do the type of priority I described?<issue_comment>username_1: This method should do the job:
```js
var unsorted = [{
id: 34,
users: [{
name: 'Lisa',
age: 23
},
{
name: 'Steven',
age: 24
}
]
},
{
id: 35,
users: [{
name: 'John',
age: 23
},
{
name: 'Steven',
age: 24
},
{
name: 'Charlie',
age: 24
}
]
},
{
id: 36,
users: [{
name: 'Lisa',
age: 23
},
{
name: 'John',
age: 24
},
{
name: 'Homer',
age: 24
},
{
name: 'Charlie',
age: 24
}
]
},
{
id: 37,
users: [{
name: 'Lisa',
age: 23
},
{
name: 'John',
age: 24
}
]
}
];
var sorted = unsorted.sort((a, b) => sortMethod(a, b));
console.log(sorted);
function sortMethod(a, b) {
var con1a = a.users.find(u => u.name == 'Lisa') && a.users.find(u => u.name == 'John');
var con1b = b.users.find(u => u.name == 'Lisa') && b.users.find(u => u.name == 'John');
if (con1a && !con1b) return -1;
if (!con1a && con1b) return 1;
return a.users.length - b.users.length;
}
```
Side note: I had to reformat the invalid JSON first, to get it successfully parsed.
Upvotes: 0 <issue_comment>username_2: You could use a boolean value for checking if the wanted names are in `users`. Then take the length as well or not.
```js
var array = [{ id: 34, users: [{ name: 'John', age: 23}, { name: 'Steven', age: 24}] }, { id: 35, users: [{ name: 'John', age: 23}, { name: 'Steven', age: 24}, { name: 'Charlie', age: 24}] }, { id: 36, users: [{ name: 'Lisa', age: 23}, { name: 'John', age: 24}, { name: 'Homer', age: 24}, { name: 'Charlie', age: 24}] }, { id: 37, users: [{ name: 'Lisa', age: 23}, { name: 'John', age: 24}] }],
find = ['John', 'Lisa'];
array.sort(function (a, b) {
var aAll = find.every(n => a.users.find(({ name }) => name === n)),
bAll = find.every(n => b.users.find(({ name }) => name === n));
return (bAll && b.users.length === 2) - (aAll && a.users.length === 2) || bAll - aAll;
});
console.log(array);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Try some thing like this
```
yourObj.sort(function(curr,next){
return ((curr.users.filter(x=>x.name=='John'|| x.name=='Steven').length > 0) && curr.users.length < 3 )? 1 : 2;
})
```
```js
var arrObj= [{
id: 34,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'Steven',
age: 24
}]
} ,{
id: 35,
users: [{
name: 'John',
age: 23,
}, {
name: 'Steven',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 36,
users: [{
name: 'Lisa',
age: 23,
}, {
name: 'John',
age: 24
}, {
name: 'Homer',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 37,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'John',
age: 24
}]
}];
arrObj.sort(function(curr,next){
return ((curr.users.filter(x=>x.name=='John'|| x.name=='Steven').length > 0) && curr.users.length < 3 )? 1 : 2;
});
console.log(arrObj);
```
Upvotes: 0 |
2018/03/21 | 1,630 | 4,521 | <issue_start>username_0: I have space **peoples**:
1. id
2. name
3. age
with two indexes:
```
peoples = box.schema.space.create('peoples', {engine = 'memtx', field_count = 3, if_not_exists = true})
peoples:create_index('primary', {type = 'TREE', unique = true, parts = {1, 'unsigned'}, if_not_exists = true})
peoples:create_index('by_name_age', {type = 'TREE', unique = false, parts = {2, 'STR', 3, 'unsigned'}, if_not_exists = true})
```
and with data:
```
peoples:auto_increment{ 'name_1', 10 }
peoples:auto_increment{ 'name_1', 11 }
peoples:auto_increment{ 'name_1', 12 }
```
I need select peoples by name and by age more than some value.
For example, I want to select all 'Alex' with age > 10, waiting for the next result:
```
[1, 'Alex', 11]
[2, 'Alex', 12]
```
I try to execute the query:
```
peoples.index.by_name_age:select({'Alex', 10}, {{iterator = box.index.EQ},{iterator = box.index.GT}})
```
but get the result
```
[1, 'Alex', 10]
```
How can I use different iterators for name and age index parts?<issue_comment>username_1: This method should do the job:
```js
var unsorted = [{
id: 34,
users: [{
name: 'Lisa',
age: 23
},
{
name: 'Steven',
age: 24
}
]
},
{
id: 35,
users: [{
name: 'John',
age: 23
},
{
name: 'Steven',
age: 24
},
{
name: 'Charlie',
age: 24
}
]
},
{
id: 36,
users: [{
name: 'Lisa',
age: 23
},
{
name: 'John',
age: 24
},
{
name: 'Homer',
age: 24
},
{
name: 'Charlie',
age: 24
}
]
},
{
id: 37,
users: [{
name: 'Lisa',
age: 23
},
{
name: 'John',
age: 24
}
]
}
];
var sorted = unsorted.sort((a, b) => sortMethod(a, b));
console.log(sorted);
function sortMethod(a, b) {
var con1a = a.users.find(u => u.name == 'Lisa') && a.users.find(u => u.name == 'John');
var con1b = b.users.find(u => u.name == 'Lisa') && b.users.find(u => u.name == 'John');
if (con1a && !con1b) return -1;
if (!con1a && con1b) return 1;
return a.users.length - b.users.length;
}
```
Side note: I had to reformat the invalid JSON first, to get it successfully parsed.
Upvotes: 0 <issue_comment>username_2: You could use a boolean value for checking if the wanted names are in `users`. Then take the length as well or not.
```js
var array = [{ id: 34, users: [{ name: 'John', age: 23}, { name: 'Steven', age: 24}] }, { id: 35, users: [{ name: 'John', age: 23}, { name: 'Steven', age: 24}, { name: 'Charlie', age: 24}] }, { id: 36, users: [{ name: 'Lisa', age: 23}, { name: 'John', age: 24}, { name: 'Homer', age: 24}, { name: 'Charlie', age: 24}] }, { id: 37, users: [{ name: 'Lisa', age: 23}, { name: 'John', age: 24}] }],
find = ['John', 'Lisa'];
array.sort(function (a, b) {
var aAll = find.every(n => a.users.find(({ name }) => name === n)),
bAll = find.every(n => b.users.find(({ name }) => name === n));
return (bAll && b.users.length === 2) - (aAll && a.users.length === 2) || bAll - aAll;
});
console.log(array);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Try some thing like this
```
yourObj.sort(function(curr,next){
return ((curr.users.filter(x=>x.name=='John'|| x.name=='Steven').length > 0) && curr.users.length < 3 )? 1 : 2;
})
```
```js
var arrObj= [{
id: 34,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'Steven',
age: 24
}]
} ,{
id: 35,
users: [{
name: 'John',
age: 23,
}, {
name: 'Steven',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 36,
users: [{
name: 'Lisa',
age: 23,
}, {
name: 'John',
age: 24
}, {
name: 'Homer',
age: 24
}, {
name: 'Charlie',
age: 24
}]
}, {
id: 37,
users: [{
name: 'Lisa',
age: 23
}, {
name: 'John',
age: 24
}]
}];
arrObj.sort(function(curr,next){
return ((curr.users.filter(x=>x.name=='John'|| x.name=='Steven').length > 0) && curr.users.length < 3 )? 1 : 2;
});
console.log(arrObj);
```
Upvotes: 0 |
2018/03/21 | 702 | 1,897 | <issue_start>username_0: Even after having a proper route set in my `web.php`, I am getting the `404 not found` error in my Laravel application in `local` mode.
[](https://i.stack.imgur.com/QGxJT.png)
All the pages are working correctly except this one and I am getting this error with `POST` method after clicking on `submit` button on the form. Here is my `web.php` file.
```
Route::get('categories/create',"CategoryController@create");
Route::post('categories',"CategoryController@store");
```
**UPDATE:**
My logs says:
```
[Wed Mar 21 16:40:22 2018] 127.0.0.1:59460 [404]: /categories - No such file or directory
[Wed Mar 21 16:40:22 2018] 127.0.0.1:59464 [200]: /favicon.ico
[Wed Mar 21 16:41:00 2018] 127.0.0.1:59472 [404]: /categories - No such file or directory
[Wed Mar 21 16:41:00 2018] 127.0.0.1:59476 [200]: /favicon.ico
[Wed Mar 21 16:41:03 2018] 127.0.0.1:59480 [200]: /favicon.ico
[Wed Mar 21 16:41:09 2018] 127.0.0.1:59484 [404]: /categories - No such file or directory
[Wed Mar 21 16:41:09 2018] 127.0.0.1:59488 [200]: /favicon.ico
```
Here is my View file -> <https://pastebin.com/NEukzc5s><issue_comment>username_1: There are several possibilities,
1. You may not wrote your route entry in `auth middleware` group
2. You should have used resource to specify which url specifies controller which is deprecated in latest laravel versions as you need to write route for every single actions you call.
3. You should always give `/` before start of every url
4. If all fine, then you should fire command `php artisan route:clear`
Check all these possibilities and let me know if error.
Upvotes: 0 <issue_comment>username_2: you may have same `categories` named directory in project's public folder. `(public/categories)`
Just rename that directory to some other name and try.
Upvotes: 3 [selected_answer] |
2018/03/21 | 578 | 2,106 | <issue_start>username_0: I have worked with template driven forms before and I am slightly confused how the reactive forms work to store the data to my database. Initially I would just use **[(ngModel)]="user.date"**. How do I store the data now on submit? I have built one as follows:
```
this.formGroup = this._formBuilder.group({
formArray: this._formBuilder.array([
this._formBuilder.group({
dateFormCtrl: ['', Validators.required]
}),
this._formBuilder.group({
emailFormCtrl: ['', Validators.email]
}),
])
});
```
Here's an example of an input that I want to store to the db:
```
```
ATM I have this function which I built for the template driven form to store data:
```
create() {
this.http.post('http://localhost:3000/user', this.user).subscribe(res => { ............
```<issue_comment>username_1: your form should be like
```
this.form = this._formBuilder.group({
dateFormCtrl: ['', Validators.required],
emailFormCtrl: ['', Validators.email]
});
```
Your submit method should be like
```
onSubmit(): void{
const formObj ={
date: this.form.value.dateFormCtrl,
email: this.form.value.emailFormCtrl,
}
this.http.post('http://localhost:3000/user', formObj).subscribe(res =>
}
```
Upvotes: 2 <issue_comment>username_2: If you want to save form data to a server dynamically, then you can follow the below code. It is the best available option.
In your component.ts file:
```
form: FormGroup;
payLoad = '';
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
this.serverService.storeServers(this.payLoad)
.subscribe(
(response) => console.log(response),
(error) => console.log(error)
);
}
```
In your service.ts file:
```
constructor(private http: HttpClient) { }
storeServers(payLoad: any) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(' ***Complete URL*** ', payLoad, httpOptions);
}
```
Upvotes: 1 |
2018/03/21 | 465 | 1,697 | <issue_start>username_0: I want to update Django User table, and add another field into it. This is how I do.
```
class User(AbstractUser):
platform = models.CharField(max_length=10)
USERNAME_FIELD = 'email'
```
Now, since there's a field `USERNAME_FIELD` which takes a unique field. However, I want that `username and platform` should be `unique_together`, not just `username`.
How can I achieve that?<issue_comment>username_1: your form should be like
```
this.form = this._formBuilder.group({
dateFormCtrl: ['', Validators.required],
emailFormCtrl: ['', Validators.email]
});
```
Your submit method should be like
```
onSubmit(): void{
const formObj ={
date: this.form.value.dateFormCtrl,
email: this.form.value.emailFormCtrl,
}
this.http.post('http://localhost:3000/user', formObj).subscribe(res =>
}
```
Upvotes: 2 <issue_comment>username_2: If you want to save form data to a server dynamically, then you can follow the below code. It is the best available option.
In your component.ts file:
```
form: FormGroup;
payLoad = '';
onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
this.serverService.storeServers(this.payLoad)
.subscribe(
(response) => console.log(response),
(error) => console.log(error)
);
}
```
In your service.ts file:
```
constructor(private http: HttpClient) { }
storeServers(payLoad: any) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(' ***Complete URL*** ', payLoad, httpOptions);
}
```
Upvotes: 1 |
2018/03/21 | 889 | 3,628 | <issue_start>username_0: As title says, I'm using since yesterday **Kotlin**. I want to populate a **RecyclerView** with data from **Firebase**.
I tried something, I built an Adapter and tried to populate the **RecyclerView**, my data is going to Firebasebase but not showing in the **RecyclerView** and I get no errors.
I couldn't find any tutorials for my problem with **Kotlin** language
**Here is my Adapter:**
```
class QuestionAdapter(var items : ArrayList): RecyclerView.Adapter() {
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
var userDto = items[position]
holder?.titleTextView?.text = userDto.titlu
holder?.msgTextView?.text = userDto.uid
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent?.context)
.inflate(R.layout.conv\_layout, parent, false)
return ViewHolder(itemView)
}
class ViewHolder(row: View) : RecyclerView.ViewHolder(row) {
var titleTextView: TextView? = null
var msgTextView: TextView? = null
init {
this.titleTextView = row?.findViewById(R.id.titleTextView)
this.msgTextView = row?.findViewById(R.id.msgTextView)
}
}
}
```
And here is my code for Activity:
```
private fun populalteQuestionsList() {
val mChatDatabaseReference = FirebaseDatabase.getInstance().reference.child(Constants.USERS).child(mUserID).child(Constants.CHAT).child(Constants.QUESTION)
val query = mChatDatabaseReference.orderByChild("time")
query.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot?) {
mRecyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
mRecyclerView.setHasFixedSize(true)
val questions = ArrayList()
val adapter = QuestionAdapter(questions)
mRecyclerView.adapter = adapter
}
override fun onCancelled(error: DatabaseError?) {
}
})
}
```<issue_comment>username_1: >
> Recyclerview is not showing data from Firebase Kotlin
>
>
>
Because you are not adding any data inside your **`questions`** `ArrayList()`
check in your code
Try this
```
override fun onDataChange(dataSnapshot: DataSnapshot?) {
mRecyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
mRecyclerView.setHasFixedSize(true)
val questions = ArrayList()
val adapter = QuestionAdapter(questions)
// add data here inside your questions ArrayList()
mRecyclerView.adapter = adapter
}
```
Upvotes: 2 <issue_comment>username_2: i hope in your adater define getItemCount() method then you can change below code ...
```
private fun populalteQuestionsList() {
val mChatDatabaseReference = FirebaseDatabase.getInstance().reference.child(Constants.USERS).child(mUserID).child(Constants.CHAT).child(Constants.QUESTION)
val query = mChatDatabaseReference.orderByChild("time")
query.addListenerForSingleValueEvent(object: ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot?) {
mRecyclerView.layoutManager = LinearLayoutManager(this@MainActivity)
mRecyclerView.setHasFixedSize(true)
val questions = ArrayList()
val question = dataSnapshot.getValue(Question::class.java)
questions.add(question)
val adapter = QuestionAdapter(questions)
mRecyclerView.adapter = adapter
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError?) {
}
})
}
```
and i hope in adapter have below method ...
```
@Override
public int getItemCount() {
return items.size();
}
```
Upvotes: 1 |
2018/03/21 | 1,041 | 2,500 | <issue_start>username_0: here is my issue:
I have a big array that I want to split into an array of arrays. These subarrays must be of lengths given by a second array.
Example
```
x=[*1..10]
y=[1,4,2,3]
```
I am seeking `output=[[1],[2,3,4,5],[6,7],[8,9,10]]`
Is there a rubyistic trick to do this?
Thanks for your assistance :)<issue_comment>username_1: You could try `shift` which gives you the first element in an array, removing it from the start.
```
a = [1,2,3,4]
a.shift
# 1
a
# [2,3,4]
```
It also takes an argument for the amount to shift off the array.
```
a = [1,2,3,4]
a.shift(2)
# [1,2]
a
# [3,4]
```
So for your arrays...
```
x = [1,2,3,4,5,6,7,8,9,10]
y = [1,4,2,3]
z = y.map do |length|
x.shift(length)
end
z
# [[1], [2, 3, 4, 5], [6, 7], [8, 9, 10]]
```
* `shift` with an argument will return an array of that many elements taken off the start of the array. The opposite of this is `pop`, which works in the same way, but takes elements from the end of the array.
* `map` will iterate through the array, like `each`, but put the result of each iteration into a new array.
* So iterating through your array of lengths, we'll grab the first few from the array.
---
**Addendum:** Some commenters have expressed concern that this method mutates the initial variable. (after this process, x will be an emtpy array, because it's all been shifted out).
If you needed to use `x` again after splitting it up, you could use `dup` to keep an intact copy.
```
x2 = x.dup
x2
# [1,2,3,4,5,6,7,8,9,10]
z = y.map do |length|
x2.shift(length)
end
x
# [1,2,3,4,5,6,7,8,9,10]
x2
# []
```
Upvotes: 3 <issue_comment>username_2: You can use the `slice!` method along with an array initializer block:
```
x = (1..10).to_a # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 4, 2, 3]
c = Array.new(y.length) {|i| x.slice!(0...y[i])} # [[1], [2, 3, 4, 5], [6, 7], [8, 9, 10]]
```
or with `map`, as pointed out by @Stefan:
```
c = y.map { |i| x.slice!(0, i) }
```
Upvotes: 2 <issue_comment>username_3: Using explicit enumerators.
```
enumx = x.each
enumy = y.each
Array.new(y.size) { enumy.next.times.with_object([]) { |_, o| o << enumx.next } }
#=> [[1], [2, 3, 4, 5], [6, 7], [8, 9, 10]]
```
To improve readability we could wrap it up in a method.
```
def taker n, enum
n.times.with_object([]) { |_, o| o << enum.next }
end
enumx = x.each
enumy = y.each
Array.new(y.size) { taker enumy.next, enumx }
#=> [[1], [2, 3, 4, 5], [6, 7], [8, 9, 10]]
```
Upvotes: -1 |
2018/03/21 | 718 | 3,238 | <issue_start>username_0: So i have this `function` that checks if my `File` is still in use (in order to wait before try to copy and delete it):
```
private static bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
using (stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
}
}
catch (IOException)
{
// The file is unavailable because it is:
// 1. Still being written to.
// 2. Being processed by another thread.
// 3. Does not exist (has already been processed).
if (stream != null)
stream.Close();
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
```
So this is enough to call `Close()` method or maybe use `using` to ensure the `file` Closed after finish my method ?<issue_comment>username_1: I think you are missing the point of a using statement. Classes with IDisposible can be used with using statements. When the using statement finishes, the "used" class is automatically disposed. A properly written class will close all open operations and dispose the class. So, in short, just do something like the following. Play with the FileAccess and FileShare to meet your needs.
```
void t()
{
using (FileStream _fileStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader sr = new StreamReader(_fileStream))
{
// do file operations
}
}
}
```
Upvotes: 0 <issue_comment>username_2: The other answers and comments already point out the redundancies in your code and why your current approach might not to work out too well. I'll try to give you some guidelines on how to solve the more general problem.
The approach I'd use is the following:
1. Create a concurrent queue that keeps track of files pending copy. Update this queue conveniently adding files as needed; once whatever previous file processing has started with an unknown future completion(\*)).
2. Create a concurrent queue that keeps track of files pending deletion.
3. Set a timer on a worker thread and periodically iterate the files eligible for copying and try to copy each file. Remove files on success and enqueue them in the pending deletion queue.
4. On the same worker thread (or a different one with its own timer) iterate all files pending deletion and try to delete each one. Remove files on success.
5. Keep going until both queues are empty or the world ends.
Moral of the story: checking if a file is locked or not in order to perform some blocking action on it is pointless, nothing stops anything from locking it right after you've performed the check. The way to do this is to simply try and do what you need doing with the file, and if it doesn't work, try again later. If it does, hey, the work is done, great.
(\*) If you *do* know when the file processing finishes then all this is pointless, copy and delete when the previous step has finished.
Upvotes: 1 |
2018/03/21 | 456 | 1,615 | <issue_start>username_0: I want to display numbers from 1 to 100 but have some sort of delay in the display of the numbers. Currently it just displays the last number in the for loop is there a way to do this that is not too advanced.
```
1
```
Here is the Javascript Code
```
for(var i = 1; i <= 100; i++){
document.getElementById('freeRange').innerHTML = i;
}
```<issue_comment>username_1: You need to appendChild every time, not just rewriting the same element's content.
```
for(var i = 1; i <= 100; i++){
var p = document.getElementById('freeRange');
var d = document.createElement('DIV')
d.innerText = i;
p.appendChild(d)
}
```
Upvotes: 1 <issue_comment>username_2: You can simply use [`setInterval()`](https://developer.mozilla.org/fr/docs/Web/API/WindowTimers/setInterval) to achieve that :
Here, you keep track of the number being displayed, and increment this number every second.
```js
let div = document.getElementById('freeRange');
let count = 1; //Keep track of your displayed number
let interval = setInterval(() => {
div.innerHTML = count; //Replaces your displayed number
count++; //Increment your variable
if(count > 100) clearInterval(interval); //Stop the interval when you reach 100
},1000); //TIme to wait between every change, in millis
```
```html
0
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: ```
1
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = parseInt(document.getElementById("freeRange").innerHTML);
document.getElementById("freeRange").innerHTML = d+1;
}
```
Upvotes: 0 |
2018/03/21 | 524 | 1,126 | <issue_start>username_0: ```
Error:Execution failed for task ':app:mergeDebugResources'.
> C:\Users\vipin\Desktop\working\chatbot-watson-android\app\src\main\res\values\config.xml: Error: The resource name must start with a letter.
```
I am not able to find the bug. My gradle version is 3.0.1.
My `config.xml` file is below.
```html
xml version="1.0" encoding="utf-8"?
9a50095e-b6a7-4f05-80b0-3c5192f07e38
5bc78043-759d-4e52-9355-861b406bdaef
```
---
Please help!<issue_comment>username_1: replace with below
```
xml version="1.0" encoding="utf-8"?
02b40d22-cf18-49f6-a209-29167f5e51b2
0ea4b080-6bdd-48d8-b327-c8d4e4939c
oJFe0L4Svsbk
9a50095e-b6a7-4f05-80b0-3c5192f07e38
5bc78043-759d-4e52-9355-861b406bdaef
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You must change the names of resources mentioned to convenient ones.
For example instead of writing :
```
```
change it to :
```
02b40d22-cf18-49f6-a209-29167f5e51b2
```
You must change names of resources to start with a letter,
Thats what it means by **The resource name must start with a letter.**
Upvotes: 0 |
2018/03/21 | 811 | 2,517 | <issue_start>username_0: I have tabs like these:
```html
* [Home](#pills-home)
* [Profile](#pills-profile)
* [Contact](#pills-contact)
...
...
...
```
But instead of having them on the left, I'd like them in the center.
I tried `text-align: center;` and even setting `margin-left: 0` and `margin-right: 0` but neither is working. What's the easiest way to do this without re-writing the whole code?<issue_comment>username_1: You can use the following solution using [`justify-content-center`](https://getbootstrap.com/docs/4.3/utilities/flex/#justify-content) on the element.
**Solution using [Bootstrap 4.0](https://getbootstrap.com/docs/4.0/):**
```html
* [Home](#pills-home)
* [Profile](#pills-profile)
* [Contact](#pills-contact)
Home
Profile
Contact
```
**This also works for the following Bootstrap versions:**
Bootstrap 4.1 ([documentation](https://getbootstrap.com/docs/4.1/)):
```html
* [Home](#pills-home)
* [Profile](#pills-profile)
* [Contact](#pills-contact)
Home
Profile
Contact
```
Bootstrap 4.2 ([documentation](https://getbootstrap.com/docs/4.2/)):
```html
* [Home](#pills-home)
* [Profile](#pills-profile)
* [Contact](#pills-contact)
Home
Profile
Contact
```
Bootstrap 4.3 ([documentation](https://getbootstrap.com/docs/4.3/)):
```html
* [Home](#pills-home)
* [Profile](#pills-profile)
* [Contact](#pills-contact)
Home
Profile
Contact
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Follow this line of code:
```html
* [Home](#pills-home)
* [Profile](#pills-profile)
* [Contact](#pills-contact)
...
...
...
```
I have added contain `"text-align: center;"` and added css `"display: inline-block;"` in . Now the list item is aligned properly. Good Luck!
Upvotes: 0 <issue_comment>username_3: ```
.nav-pills{
list-style: none;
padding: 0;
margin: 0;
display: flex;
justify-content: center;
}
.nav-item{
padding: 15px;
}
```
Upvotes: 1 <issue_comment>username_4: You need to remove `float: left` and use `display: inline-flex`..in addition to it..use `text-align:center` in `ul`
```css
.nav-pills > li {
text-align: center;
margin: 0px auto;
display:inline-flex !important;
float:none !important;
}
.nav{
text-align: center;
}
```
```html
Bootstrap
* [Home](#pills-home)
* [Profile](#pills-profile)
* [Contact](#pills-contact)
...
...
...
```
Upvotes: 0 <issue_comment>username_5: just add a class "justify-content-center" to ul. so now your ul become like this
Upvotes: 0 |
2018/03/21 | 1,650 | 4,239 | <issue_start>username_0: i have updated the package.json in my Angular Project,using command ncu -u after update getting below error when i run **ng serve**
**ERROR in ./node\_modules/@angular/core/esm5/core.js
Module not found: TypeError: dep.isEqualResource is not a function**
tried uninstalling node modules and re- installation but no luck
Adding Package.json below.
```
{
"name": "material",
"private": true,
"version": "1.0.0",
"main": "",
"scripts": {
"ng": "ng",
"start": "ng serve",
"hmr": "ng serve --hmr -e=hmr",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"clean": "rimraf node_modules",
"clean-all": "rimraf node_modules dist dll && npm cache clean",
"reinstall": "rimraf node_modules && rm -f package-lock.json && npm install"
},
"dependencies": {
"@angular/animations": "^5.2.9",
"@angular/cdk": "^5.2.4",
"@angular/common": "^5.2.9",
"@angular/compiler": "^5.2.9",
"@angular/core": "^5.2.9",
"@angular/forms": "^5.2.9",
"@angular/http": "^5.2.9",
"@angular/material": "5.2.4",
"@angular/platform-browser": "^5.2.9",
"@angular/platform-browser-dynamic": "^5.2.9",
"@angular/platform-server": "^5.2.9",
"@angular/router": "^5.2.9",
"@types/underscore": "^1.8.8",
"angular-localstorage": "^1.1.5",
"angular2-csv": "^0.2.5",
"angular2-debounce": "^1.0.4",
"classlist.js": "^1.1.20150312",
"core-js": "^2.5.3",
"cors": "^2.8.4",
"easy-pie-chart": "^2.1.7",
"echarts": "^4.0.4",
"font-awesome": "^4.7.0",
"intl": "^1.2.5",
"jquery": "^3.3.1",
"jquery-slimscroll": "^1.3.8",
"jsonwebtoken": "^8.2.0",
"jspdf": "^1.3.5",
"jspdf-autotable": "^2.3.2",
"ng-circle-progress": "^0.9.9",
"ng2-toasty": "^4.0.3",
"ng2modules-easypiechart": "0.0.4",
"ngx-filter-pipe": "^2.1.0",
"reflect-metadata": "^0.1.12",
"rxjs": "^5.5.7",
"underscore": "^1.8.3",
"webfontloader": "^1.6.28",
"zone.js": "^0.8.20"
},
"devDependencies": {
"@angular/cli": "1.7.3",
"@angular/compiler-cli": "^5.2.9",
"@angularclass/hmr": "^2.1.3",
"@angularclass/hmr-loader": "^3.0.4",
"@auth0/angular-jwt": "^1.1.0",
"@types/core-js": "^0.9.46",
"@types/hammerjs": "^2.0.34",
"@types/jasmine": "^2.8.6",
"@types/jquery": "^3.3.1",
"@types/node": "^9.4.7",
"add-asset-html-webpack-plugin": "^2.1.3",
"angular-router-loader": "^0.8.2",
"angular2-template-loader": "^0.6.2",
"autoprefixer": "^8.1.0",
"awesome-typescript-loader": "^4.0.1",
"bootstrap": "^4.0.0",
"clarity-angular": "^0.10.27",
"codelyzer": "^4.2.1",
"copy-webpack-plugin": "^4.5.1",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.11",
"hammerjs": "^2.0.8",
"html-webpack-plugin": "^3.0.7",
"json-loader": "^0.5.4",
"material-design-lite": "^1.3.0",
"moment": "^2.21.0",
"ng-router-loader": "^2.1.0",
"node-sass": "^4.8.2",
"postcss-loader": "^2.1.3",
"raw-loader": "^0.5.1",
"rimraf": "^2.6.2",
"sass-loader": "^6.0.7",
"style-loader": "^0.20.3",
"ts-helpers": "^1.1.2",
"ts-node": "^5.0.1",
"tslib": "^1.9.0",
"tslint": "^5.9.1",
"tslint-loader": "^3.6.0",
"typescript": "^2.7.2",
"webpack": "^4.2.0",
"webpack-dev-server": "^3.1.1",
"webpack-dll-bundles-plugin": "^1.0.0-beta.5",
"webpack-merge": "^4.1.2"
},
"engines": {
"node": ">=6.9.0",
"npm": ">= 3"
}
}
```<issue_comment>username_1: It's probably to do with your engine versions, try setting them to
```
"node": "8.10.0",
"npm": "5.6.0"
```
as this is what is working for me at the moment and run npm install
Upvotes: 0 <issue_comment>username_2: I had the same issue. I solved it by removing webpack related packages on devDepencies list. `"@angular/cli"` package handles all webpack works.
in your example remove that lines than run `npm install` command again:
```
"webpack": "^4.2.0",
"webpack-dev-server": "^3.1.1",
"webpack-dll-bundles-plugin": "^1.0.0-beta.5",
"webpack-merge": "^4.1.2"
```
I hope it will work for you.
Upvotes: 2 [selected_answer] |
Subsets and Splits