text:
Q: Mutations can apparently be @shareable in Federation 2. Does this mean mutations are just fields on a Mutation object? We have a federated graph composed of multiple subgraphs. We wish to migrate the implementation of Subgraph X from Service A to a new Service B that is using some new fancy tech, as one does. We wish to complete this migration without having to make any changes to the clients consuming the supergraph.
OK, no problem! We updated our gateway to use Federation 2 composition. Federation 2 composition allows us to resolve @shareable fields from multiple subgraphs. We spun up Service B and now our supergraph is sending queries that used to be resolved only by Service A to both Service A and Service B.
However, we also have a mutation that Service A resolves. There is nothing in the docs that says we can't share mutations between services, and sure enough, we tried marking this mutation as @shareable and we now have a supergraph that can send mutations to either Service A or Service B. Wow!
The documentation for the @shareable directive says

The @shareable directive is used to indicate that a field can be resolved by multiple subgraphs. Any subgraph that includes a shareable field can potentially resolve a query for that field.

The word query is used here, but not the word mutation.
The fact that we can share a mutation between multiple subgraph services indicates to me that a mutation is just a field on a Mutation object. Is my mental model correct?

Note: Of course, this is only possible because Service A and Service B use the same datastore.


text:
Q: Create custom command in tmux I know how to bind a key to a command in tmux, but I want to create a custom command (that you can type with prefix key + colon). In this custom command, I want to execute a couple of other commands.
My idea is to have something like this:
no-side-status() {
    set status-left-length 0
    set status-right-length 0
}

side-status() {
    set status-left-length 50
    set status-right-length 150
}

So I can type :no-side-status to hide the left and right status bars, and type :side-status to restore the left and right status bars.
Is it possible to create such custom commands? If so how? If not, any other way to achieve what I want?

A: Originally, tmux doesn't have any support for custom commands except for running external shell scripts.
There's a mod adding full-fledged scripting support to tmux: http://ershov.github.io/tmux/
It also allows to create user commands. For example, yours would look like:
proc no-side-status {} {
    set status-left-length 0
    set status-right-length 0
}

proc side-status {} {
    set status-left-length 50
    set status-right-length 150
}

To use from tmux command line just type C-b : and side-status or no-side-status.
To bind it to a key use bind C-p tcl side-status.

A: bind C-p run "/usr/bin/notify-send Foo"

A: This is the full answer. You can have two tmux configuration.
One contain
set status-left-length 0
set status-right-length 0
bind-key R source-file ~/.tmux.alternative.conf \; \
                    display-message "Alternative configuration loaded"

The other contain
set status-left-length 50
set status-right-length 15
bind-key R source-file ~/.tmux.conf \; \
                    display-message "Default configuration loaded"

A: The closest experience you can get right now is:

*

*create tmux shell script and put it in $PATH

*run the script inside tmux using the run-shell command (short: ru)

Example in tmux (say the script is named tm.xx)
c-b :ru tm.xx

So you are typing three extra characters - ru

A: tmux supports float windows now. You could popup a window by using tmux display-popup. And then in this popup window, run the script you want to use.

A: Define a command alias by adding something like this to your .tmux.conf:
set -s command-alias[10] widevim='splitw -bvfp 80 "vim -O2"'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to fill a form with Scrapy FormRequest, unexpected results I'm trying to fill the form that is at www.wetseal.com/Stores that allows selecting the state to show stores from.
<form action="http://www.wetseal.com/Stores?dwcont=C73689620" method="post" id="dwfrm_storelocator_state">
                    <fieldset>

                                State
                                *

                            <select id="dwfrm_storelocator_address_states_stateUSCA" class="input-select required" name="dwfrm_storelocator_address_states_stateUSCA">
                                <option value="">Select...</option>

                                    <option value="AK">Alaska</option>

                                    <option value="AZ">Arizona</option>

                                    <option value="AR">Arkansas</option>

                                    <option value="CA">California</option>

                                    <option value="CO">Colorado</option>

                                    <option value="CT">Connecticut</option>

                                    <option value="DE">Delaware</option>

                                    <option value="FL">Florida</option>

                                    <option value="GA">Georgia</option>

                                    <option value="HI">Hawaii</option>

                                    <option value="ID">Idaho</option>

                                    <option value="IL">Illinois</option>

                                    <option value="IN">Indiana</option>

                                    <option value="KS">Kansas</option>

                                    <option value="KY">Kentucky</option>

                                    <option value="MD">Maryland</option>

                                    <option value="MA">Massachusetts</option>

                                    <option value="MI">Michigan</option>

                                    <option value="MN">Minnesota</option>

                                    <option value="MS">Mississippi</option>

                                    <option value="MO">Missouri</option>

                                    <option value="NE">Nebraska</option>

                                    <option value="NV">Nevada</option>

                                    <option value="NH">New Hampshire</option>

                                    <option value="NJ">New Jersey</option>

                                    <option value="NM">New Mexico</option>

                                    <option value="NY">New York</option>

                                    <option value="NC">North Carolina</option>

                                    <option value="ND">North Dakota</option>

                                    <option value="OH">Ohio</option>

                                    <option value="OK">Oklahoma</option>

                                    <option value="OR">Oregon</option>

                                    <option value="PA">Pennsylvania</option>

                                    <option value="PR">Puerto Rico</option>

                                    <option value="RI">Rhode Island</option>

                                    <option value="SC">South Carolina</option>

                                    <option value="SD">South Dakota</option>

                                    <option value="TN">Tennessee</option>

                                    <option value="TX">Texas</option>

                                    <option value="VA">Virginia</option>

                                    <option value="WA">Washington</option>

                                    <option value="WV">West Virginia</option>

                                    <option value="WI">Wisconsin</option>

                            </select>

                        <button type="submit" name="dwfrm_storelocator_findbystate" value="Search">
                            Search
                        </button>
                    </fieldset>
                </form>

Looking with Chrome I can see the request being made and the form params:

That said, I have a very simple spider that, looking at the docs, sends a FormRequest to that URL to fill the form (In this case I'm testing for Arizona shops - AZ):
class WetSealStoreSpider(Spider):
    name = "wetseal_store_spider"
    allowed_domains = ["wetseal.com"]
    start_urls = [
        "http://www.wetseal.com/Stores"
    ]

    def parse(self, response):
        yield FormRequest.from_response(response,
                                    formname='dwfrm_storelocator_state',
                                    formdata={'dwfrm_storelocator_address_states_stateUSCA': 'AZ',
                                              'dwfrm_storelocator_findbystate': 'Search'},
                                    callback=self.parse1)

    def parse1(self, response):
        print response.status
        print response.body

When it gets to make the FormRequest, looking at the response, everything seems OK:

But in the callback method, I see this in the response:

It looked like a GET request was made at the end, and the url is all wrong:
'http://www.wetseal.com/Search?q=&dwfrm_storelocator_findbystate=Search&dwfrm_storelocator_address_states_stateUSCA=AZ'

Any idea what I'm doing wrong?
Thanks!

A: You're using formname but the form doesn't have a name.
Try using formxpath='id("dwfrm_storelocator_state")' instead.

A: try this
states = response.xpath(
        ".//select[@id='dwfrm_storelocator_address_states_stateUSCA']//option[@value!='']/@value").extract()
    url = self.get_text_from_node(response.xpath("//form[@id='dwfrm_storelocator_state']/@action"))
    for state in states:
        form_data = {'dwfrm_storelocator_address_states_stateUSCA': state,
                     "dwfrm_storelocator_findbystate": "Search"}
        yield FormRequest(url,
                          formdata=form_data,
                          callback=self.your_Callback)


text:
Q: Direct assignment to the reverse side of a related set is prohibited. Use time_interval.set() instead I have 3 models: Order, orderTimelocation and timeInterval. Order has a relation one to many with orderTimelocation and this has a relation one to many with timeInterval:
class Order(models.Model):
    customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer')
    retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer')
    date_publish = models.DateField()
    date_available = models.DateField()
    weight = models.DecimalField(decimal_places=2, max_digits=5)

class orderTimelocation(models.Model):
    longitude = models.DecimalField(decimal_places=8, max_digits=12)
    latitude = models.DecimalField(decimal_places=8, max_digits=12)
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='ordertimelocation', null=True)

class timeInterval(models.Model):
    start = models.DateTimeField()
    end = models.DateTimeField()
    order_timelocation = models.ForeignKey(orderTimelocation, related_name='time_interval', on_delete=models.CASCADE)

I am using Writable nested serializers as the documentation suggests.
class OrderSerializer(serializers.ModelSerializer):
    ordertimelocation = orderTimelocationSerializer(many=True)

    class Meta:
        model = Order
        fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation']

    def create(self, validated_data):
        timelocations_data = validated_data.pop('ordertimelocation')
        order = Order.objects.create(**validated_data)

        for timelocation_data in timelocations_data:
            orderTimelocation.objects.create(order=order, **timelocation_data)
        return order

class orderTimelocationSerializer(serializers.ModelSerializer):
    time_interval = timeIntervalSerializer(many= True)

    class Meta:
        model = orderTimelocation
        fields = ('longitude', 'latitude', 'time_interval')

    def create(self, validated_data):
        time_intervals_data = validated_data.pop('time_interval')
        ordertimelocation = orderTimelocation.objects.create(**validated_data)
        for time_interval_data in time_intervals_data:
           orderTimelocation.objects.create(ordertimelocation=ordertimelocation, **time_interval_data)
        return ordertimelocation

class timeIntervalSerializer(serializers.ModelSerializer):
    class Meta:
        model = timeInterval
        fields = ['start', 'end']

The error is the following:
Traceback (most recent call last):
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback
    return callback(request, *args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/generics.py", line 190, in post
    return self.create(request, *args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/mixins.py", line 19, in create
    self.perform_create(serializer)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/mixins.py", line 24, in perform_create
    serializer.save()
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/rest_framework/serializers.py", line 205, in save
    self.instance = self.create(validated_data)
  File "/home/miguel/workspace/projeto-final/backend/delivery_api/serializers/order_serializer.py", line 17, in create
    orderTimelocation.objects.create(order=order, **timelocation_data)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/db/models/query.py", line 451, in create
    obj = self.model(**kwargs)
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/db/models/base.py", line 498, in __init__
    _setattr(self, prop, kwargs[prop])
  File "/home/miguel/workspace/projeto-final/backend/env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 545, in __set__
    raise TypeError(
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use time_interval.set() instead.

I don't know what I am doing wrong becouse my code is similar to the code in the docs.

A: The issue is because in OrderSerializer.create, every timelocation_data has time_interval. You need to pop it, then handle:
class OrderSerializer(serializers.ModelSerializer):
    ordertimelocation = orderTimelocationSerializer(many=True)

    class Meta:
        model = Order
        fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation']

    def create(self, validated_data):
        timelocations_data = validated_data.pop('ordertimelocation')
        order = Order.objects.create(**validated_data)

        for timelocation_data in timelocations_data:
            time_intervals_data = validated_data.pop('time_interval') # <-- This will fix the error
            ordertimelocation = orderTimelocation.objects.create(order=order, **timelocation_data)
            for time_interval_data in time_intervals_data:
                timeInterval.objects.create(order_timelocation=ordertimelocation, **time_interval_data)

        return order

or just use orderTimelocationSerializer for timelocations_data and let it handle itself:
class OrderSerializer(serializers.ModelSerializer):
    ordertimelocation = orderTimelocationSerializer(many=True)

    class Meta:
        model = Order
        fields = ['customer', 'retailer', 'date_publish', 'date_available', 'weight', 'ordertimelocation']

    def create(self, validated_data):
        timelocations_data = validated_data.pop('ordertimelocation')
        order = Order.objects.create(**validated_data)

        for timelocation_data in timelocations_data:
            order_time_location_serializer = orderTimelocationSerializer(data=timelocation_data)
            order_time_location_serializer.is_valid(raise_exception=True)
            order_time_location = order_time_location_serializer.save()
            order_time_location.order = order
            order_time_location.save()

        return order


text:
Q: MVC (templates): is it OK to call functions with arguments from the View? In a MVC scenario, is it OK to pass arguments to functions from the View to satisfy different formatting needs?
For example: let's say that the model has a DateTime object and the view must show this date in various format (sometimes as "01-Jan-2020", sometimes as "Monday, 01-Jan-2020 08:00" sometimes in some other way, possibly on the same screen).
Scenario 1:
The view receives different variable for each format:
DateShort: "01-Jan-2020"
DateLong: "Monday, 01-Jan-2020 08:00"

...

echo {{ DateShort }}
echo {{ DateLong }}

Pros: the View is super-simple: no function call, just print variables (yay!). The available formats are centralized and consistent across the whole project (no hotshot printing the date based on their cultural preference)
Cons: slippery separation of concerns: displaying+formatting content should be the View responsibility. This makes the model exposing the DateTime object bloated with extra, unrelated code. Strong coupling: to display the DateTime in another, new format, we need to change the model (!!)
Scenario 2:
The view receives the object directly, then it formats it as-needed:
Date: (object)DateTime

...

echo {{ Date.format('%D %M %Y') }}

//variant: format is actually exposed as a constant
echo {{ Date.format(Formats::DATETIME_FORMAT_DATELONG) }}

Pros: better separation of concerns, better decoupling.
Cons: calling functions from the View feels awful. What if, somewhere, the {{ Date }} variable doesn't have a format() method because it's of another type?
My feeling: the benefit of the Scenario 2 vastly outweighs the cons. Still, it feels bad and can get very ugly, very fast: {{ Price.format_currency('EUR', {fraction_digit: 2}) }} become acceptable, which "feels" terrible.
Is there a best practice or SOLID rule I can apply to choose one way over the other with confidence?

A: Clearly how to display the datetime is a View responsibility.
For example, my control wants to display the time as a clock image. Neither if the two Model strings provided allow me to do this.
Having said that most good MVC is more like VMVC, with a view model tailored to the individual view and containing any logic that's simply inconvenient to do in the view itself.
Here it would be totally acceptable to do the formatting in the view model, as my hypothetical view would have a different view model, which perhaps would expose things like hourhandAngle etc


text:
Q: SSIS How to ForceExecutionResult Success for the Grandparent Container Your help and insight is greatly appreciated
In SSIS I need to ForceExecutionResult = Success for the Grandparent Container
This is how I have my package set up currently:
Parent Package = A
Child Package = B

- An Execute Package Task calls B from A
- If B fails with a specific error code, I retry B

I retry B by way of the OnError event handler in A's Execute Package Task using a Script Task.

To my way of thinking:
- A's Execute Package Task OnError event handler is the Script Task's Parent Container
- A's Execute Package Task is the Script Task's Grandparent Container

How do I ForceExecutionResult = Success for the Grandparent Container (A's Execute Package Task) when the B retry succeeds?
Right now even when the B retry succeeds, A's Execute Package Task still shows Red = failure as a result of the failure that happens on the first B attempt.
Looking for a programmatic way of doing this with C# or VB inside a script task.
I am using SSIS 2008
Thanks for reading

A: Main advise is not to rerun package B after OnError event. You need to call B, make sure it does not fail package A, evalute outcome of package B and decide what to do.

*

*Create a For Loop container and make it run for a set number of times (= max numbers of runs, like in while i < 5 do).

*Set Execute Package task not to fail parent and whole package on error.

*Evaluate execution code in a Script Task and exit For Loop container on success / failure condition. (like by setting i=5).
Probably you can execute package B from C# Script Task - check object model how to do that. I'll update my answer if I find how to.


text:
Q: Eclipse 3,6 (Helios) referenced project has main method, cannot access from run config when targeting referencing project I have two projects in a workspace, one is a fancy application that is configured by xml (project 1), the other contains some code specific to a task (project 2) and utilizes some classes and implements interfaces from the fancy app.
Project 1 contains the main method and is configured by an xml file to load a class from project 2 using reflection, so it needs to be launched from the context of project 2.
Project 2 references project 1 in the build path, and thus shows no errors and compiles, however when selected from the run configurations dialog, it does not show the class with a main method from project 1 as an option.
My work around for now is to generate a jar from project 1 and reference that from project 2, which then causes the class to show up.  This works, but I hate having to export the project to jar every time a change occurs in project 1.  I also hate having the EXACT same Class show up in open type twice, once from the jar, once from the project.
Is there something on top of adding the project to the build path I have to do to get this working?
Thanks

A: You can launch your application from project 1, just need to edit its Launch Configuration and add a project 2 at the Classpath tab.


text:
Q: Casting an inserted string to a date in the same insert SQL Server 2017 - although this post is quite old, I still referred to it: Using cast in insert statement (the answer with 6 votes), but I'm getting an error when trying to perform this simple INSERT statement:
INSERT INTO dbo.Table (Name, DateOfBirth, DateOfBirth_Normalized)
VALUES ('John Doe', '1943-09-08', CAST(DateOfBirth AS DateTime))

The error I'm getting is that the DateOfBirth inside the CAST statement is an invalid column name.
How can I achieve this?
FYI, DateOfBirth is nvarchar(50) and DateOfBirth_Normalized is DateTime.
EDIT 1: this is for a stored procedure, so the DateOfBirth value will be different for every INSERT and therefore can not simply be passed as the string value, as suggested in the comments.


text:
Q: Error al cargar rutas en laravel Route::get('foo', function (){
    return 'Hello World';
  });

Este es el ejemplo de la pagina oficial de Laravel, pero al momento te hacerlo me sale:

"Sorry, the page you are looking for could not be found."

Agradezco si me pueden ayudar en alguna cosa, ¡gracias!

A: creo que tienes que modificar la ruta a esta forma /foo
Route::get('/foo', function (){
  return 'Hello World';
});


text:
Q: SIngle Query from Multiple Table MySql I have tables that contain same field, for example:
p_central_ticket        p_south_ticket             p_west_ticket
=====================================================================
- t_id                  - t_id                     - t_id
- t_open_by             - t_open_by                - t_open_by
- t_closed_by           - t_closed_by              - t_closed_by
- t_open_time           - t_open_time              - t_open_time
- t_closed_time         - t_closed_time            - t_closed_time

One thing that i expect is output just like this, but definitely for 3 table above in single query:
Name                today      weekly     monthly     yearly
=================================================================
test1@random.com         2           10          70        1000
test2@random.com         5           14          60        1234

But, my query right now just for calculate 1 table.
SELECT t_closed_by As Username, ixt_user_type.user_owner As Role,
    COUNT( case when t_closed_time > curdate() - interval 1 day THEN 1 END ) as today,
    COUNT( case when t_closed_time > curdate() - interval 7 day THEN 1 END ) as weekly,
    COUNT( case when t_closed_time > curdate() - interval 1 month THEN 1 END ) as monthly,
    COUNT( case when t_closed_time > curdate() - interval 1 year THEN 1 END ) as yearly
FROM p_central_ticket
LEFT JOIN m_event_type ON p_central_ticket.t_req_type = m_event_type.ev_type
LEFT JOIN ixt_user_type ON m_event_type.ev_user_type_target = ixt_user_type.user_type
WHERE t_status = 9
GROUP BY t_closed_by;

My question is, how should i do, to make my query calculate from 3 tables but in single query ?

A: You can use UNION to merge three tables and apply all your join on that merged table like below -
SELECT t_closed_by As Username, ixt_user_type.user_owner As Role,
    COUNT( case when t_closed_time > curdate() - interval 1 day THEN 1 END ) as today,
    COUNT( case when t_closed_time > curdate() - interval 7 day THEN 1 END ) as weekly,
    COUNT( case when t_closed_time > curdate() - interval 1 month THEN 1 END ) as monthly,
    COUNT( case when t_closed_time > curdate() - interval 1 year THEN 1 END ) as yearly
FROM
( select * from p_central_ticket
  union
  select * from p_south_ticket
  union
  select * from p_west_ticket
)A
LEFT JOIN m_event_type ON A.t_req_type = m_event_type.ev_type
LEFT JOIN ixt_user_type ON m_event_type.ev_user_type_target = ixt_user_type.user_type
WHERE t_status = 9
GROUP BY t_closed_by


text:
Q: How to do 1 URL re-write rule for multiple ids? I have these URLs:
https://www.example.com/amp/articles/10/title
https://www.example.com/amp/videos/11/title
I need to redirect only specific ids to non amp as follows:
https://www.example.com/articles/10/title
https://www.example.com/videos/11/title
Here's what I tried but there's no URL redirection, nothing occurs:
    <rule name="redirect_to_non_amp_for_specific_ids" stopProcessing="true">
      <match url="^amp/(articles|videos)/(10|11)/([^/]+)/?$"/>
          <conditions>
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
      <action type="Redirect" redirectType="Permanent" url="{R:1}/{R:2}/{R:3}"/>
    </rule>

Note I need to avoid multiple url-rewrite rules.

A: My rule is correct. I figured out I had to place it before other article rules, for priority, for the rule to take effect.
From microsoft: The rules are evaluated in the same order in which they are specified.
Reference: https://learn.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration-reference


text:
Q: Async functions on Angular2 I want to make functions on this service asynchronous, the last function should wait to a response of the one above it and so on. I am getting 'property subscribe does not exist on type void' on the second line of createPlaylist() and I don't know why.
Imports:
import { Injectable } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';

Code:
getUserId(token:string = localStorage.getItem('myToken')) {
  const url = 'https://api.spotify.com/v1/me';
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  this.http.get(url, {headers : headers}).map((res: Response) => res.json())
  .subscribe(result => {
    this.currentUser = result.id;
    console.log(this.currentUser);
    return Observable.of(result);
  });
}

createPlaylist(token:string = localStorage.getItem('myToken')) {
  this.getUserId().subscribe(user => {
  const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists`;
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/json');
  const body = {
    'name': 'searchDDD playlist'
  };
  this.http.post(url, body, { headers } )
  .subscribe(result => {
    console.log(result.json().name);
    console.log(result.status);
    this.playlistID = result.json().id;
  });
  });
}

addSongs(token:string = localStorage.getItem('myToken')) {
  this.createPlaylist();
  const url = `https://api.spotify.com/v1/users/${this.currentUser}/playlists/${this.playlistID}/tracks`;
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/json');
  const body = {'uris': ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh',
  'spotify:track:1301WleyT98MSxVHPZCA6M']};
  this.http.post(url, body, { headers } )
  .subscribe(result => {
    console.log(result.status);
  });
}

A: Return from the getUserId function and remove the subscribe part. You can just one time subscribe to a Observable and put the logic inside the single subscribe or just write an intermediate logic via do function.
getUserId(token:string = localStorage.getItem('myToken')) {
  const url = 'https://api.spotify.com/v1/me';
  const headers = new Headers();
  headers.append('Authorization', 'Bearer ' + token);
  return this.http.get(url, {headers : headers})
                  .map((res: Response) => res.json())
                  .do(result => this.currentUser = result.id);
}


text:
Q: remove the workflow via the Java code at bootstartup I need to remove the workflow via the Java code at bootstartup. My code works correctly at runtime, but it throw exception if I run it at boot startup. What should I do to remove the workflow at bootstartup via the Java code?
for example:
my-example-context.xml:
<bean id="my-example" class="MyExamle" init-method="init">
        <property name="workflowService">
            <ref bean="WorkflowService"/>
        </property>
</bean>

MyExamle.java:
public class MyExamle {
    ...
    private WorkflowService workflowService;

    public void init() {
        PropertyCheck.mandatory(this, "workflowService", workflowService);

        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Integer>() {
            @Override
            public Integer doWork() throws Exception {
                 Integer count = 0;
                 WorkflowDefinition reviewDef = workflowService.getDefinitionByName(
                            "activiti$activitiReview"
                 );
                 List<WorkflowInstance> workflowInstanceList = workflowService.getActiveWorkflows(
                            reviewDef.getId()
                 );
                 count = workflowInstanceList.size();
                 for (WorkflowInstance workflowInstance : workflowInstanceList) {
                          workflowService.deleteWorkflow(
                                workflowInstance.getId()
                          );
                 }
                 return count;
            }
        }, AuthenticationUtil.getSystemUserName());
    }
    ...
}

this code throw exception: org.alfresco.service.namespace.NamespaceException: Namespace prefix wf is not mapped to a namespace URI
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mrem-extention-bootstartup' defined in URL [jar:file:/C:/Alfresco/tomcat/webapps/alfresco/WEB-INF/lib/moldavia-rem.jar!/alfresco/extension/mrem-bootstartup-context.xml]: Invocation of init method failed; nested exception is org.alfresco.service.namespace.NamespaceException: Namespace prefix wf is not mapped to a namespace URI
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.alfresco.web.app.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:63)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4135)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4630)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:637)
    at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:563)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:498)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445)
    at org.apache.catalina.core.StandardService.start(StandardService.java:519)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.alfresco.service.namespace.NamespaceException: Namespace prefix wf is not mapped to a namespace URI
    at org.alfresco.service.namespace.QName.createQName(QName.java:99)
    at org.alfresco.service.namespace.QName.createQName(QName.java:121)
    at org.alfresco.repo.workflow.WorkflowQNameConverter.convertNameToQName(WorkflowQNameConverter.java:103)
    at org.alfresco.repo.workflow.WorkflowQNameConverter.convertNameToQName(WorkflowQNameConverter.java:85)
    at org.alfresco.repo.workflow.WorkflowQNameConverter.mapNameToQName(WorkflowQNameConverter.java:71)
    at org.alfresco.repo.workflow.WorkflowObjectFactory.getTaskTypeDefinition(WorkflowObjectFactory.java:409)
    at org.alfresco.repo.workflow.WorkflowObjectFactory.createTaskDefinition(WorkflowObjectFactory.java:209)
    at org.alfresco.repo.workflow.activiti.ActivitiTypeConverter.getTaskDefinition(ActivitiTypeConverter.java:155)
    at org.alfresco.repo.workflow.activiti.ActivitiTypeConverter.convert(ActivitiTypeConverter.java:144)
    at org.alfresco.repo.workflow.activiti.ActivitiWorkflowEngine.getDefinitionByName(ActivitiWorkflowEngine.java:487)
    at org.alfresco.repo.workflow.WorkflowServiceImpl.getDefinitionByName(WorkflowServiceImpl.java:342)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.alfresco.repo.security.permissions.impl.AlwaysProceedMethodInterceptor.invoke(AlwaysProceedMethodInterceptor.java:34)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.alfresco.repo.security.permissions.impl.ExceptionTranslatorMethodInterceptor.invoke(ExceptionTranslatorMethodInterceptor.java:46)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.alfresco.repo.audit.AuditMethodInterceptor.invoke(AuditMethodInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at $Proxy71.getDefinitionByName(Unknown Source)
    at ru.moldavia.alfresco.workflow.WorkflowFactory.removeAllActivitiReviewWorkflow(Unknown Source)
    at ru.moldavia.alfresco.workflow.WAO.removeAllNotificationWorkflows(Unknown Source)
    at ru.moldavia.alfresco.workflow.bootstartup.WorkflowBootstartupExtention.extend(Unknown Source)
    at ru.moldavia.alfresco.bootstartup.ExtentionBootstartup.runExtentions(Unknown Source)
    at ru.moldavia.alfresco.bootstartup.ExtentionBootstartup.init(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1544)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
    ... 37 more

A: I think exception you provided is not related to your question. Check your data model definition.
In all cases - back to your question - try to use onBootstrap() instead of init(), just extend AbstractLifecycleBean class and Override onBootstrap(ApplicationEvent event) and onShutdown(ApplicationEvent event). There may be uninitialized parts of Alfresco system while calling init().


text:
Q: Deleted /var/patch/applied -- Can I recreate it? I was cleaning out old patches in my Xenserver and accidentally deleted the applied directory in /var/patch. I know which patches have been applied so can I recreate that folder? Is there an example of what was inside of it?
Noob mistake and no backup.


text:
Q: All other prime gaps (except between $2$ and $3$) are even. How can one show that except for the first prime gap (between $2$ and $3$), all prime gaps are even?
Prime gap means the difference of two consecutive primes.
For example: $5-3=2$ (even) or $17-13=4$ (even) or $23-19=4$ (even).
I have no idea how to start.

A: Since all prime numbers except $2$ are odd, then if a prime gap $g$ between primes $p_1,p_2$ would be odd, then $p_2=p_1+g$ would be the sum of two odd numbers which is even, and since the only prime which is even equals $2$, thus we get the desired contradiction.

A: All primes other than $2$ are odd, hence gap between them is even (as difference of two odd numbers is always even).

A: $1$. The only even prime is $2$ and all other are odd primes.
$2$. Difference between two odd numbers is always even.
First posted as hint but now @Cato asked for a proof so here We go:
Proof of $1$:
Suppose that there is another prime which is even (other than $2$), then it must be of the form $2k$ where $k$ being a positive integer, so that prime number can be written as $2 \times k$ which is enough to say that it is composite (Or not prime). A contradiction.
Proof of $2$.
As known (I don't think it also need a proof), every odd number is of the form $2k+1$, where $k$ is an integer. We just have to calculate the difference b/w two odd primes (Remember the word odd) so let first one be $2k_1+1$and second one be $2k_2+1$. Difference $= (2k_2+1-(2k_1+1))= 2k_2-2k_1=2(k_2-k_1)=$ even number.
I think it is enough. :) :)


text:
Q: Ensure that devices connect to a specific access point I have the following setup in my apartment:
A Fritz!Box is connected to the internet and broadcasts my wifi signal. To improve reception, a TP Link router configured as  access point is connected through a powerline adapter to serve the other side of the apartment. The TP link runs dd-wrt. Only the Fritz!Box runs a DHCP server.
I now bought a Sonos speaker which will stand more or less exactly at the spot where the two signals from the TP Link and the Fritz!Box overlap. Since powerline is not supported by Sonos (and does cause some trouble in my setup), I would like to ensure that the Sonos always connects to the wifi signal from the Fritz!Box, not the TP Link.
How can I achieve this?

A: Partial answer:
According to the Sonos description, the problem seems to be the delay when using a powerline adapter, not the powerline adapter itself.
So this means the Sonos is only usable by applications connecting to the same access point (AP), whichever you choose. Because if Sonos is connected to one AP and the Application to the other, the powerline between both routers will cause the delay.
Given that, I'd really recommend the two SSID approach - this will mean you'll clearly know which devices can use the Sonos and which can't.
If you don't do this and use one SSID, even if you manage to coerce the Sonos to connect to the AP you want, a device with an application using Sonos could still silently connect to the other AP (or decide to switch while being connected), leading to the above problems.


text:
Q: Phase-symmetric normal matrix I define a complex matrix A as phase-symmetric if for every pair of elements elements $a_{ij}$ and $a_{ji}$,
$$a_{ij} = r_1\angle{\theta}$$
$$a_{ji} = r_2\angle{\theta}$$
where $r1,r2$ are real and $-\frac{\pi}{2}\le\theta\le\frac{\pi}{2}$. ie: both elements have the same complex phase.
I want to prove that a complex normal matrix is phase-symmetric if and only if it is symmetric.
Any hints would be great. This is not a homework or textbook question. Just from my own personal investigations.

A: For example, $$\pmatrix{0 &  e^{i\theta}\cr - e^{i\theta} & 0\cr}$$ is normal and complex phase-symmetric, according to your definition, but not symmetric.


text:
Q: How do you pass data out of a React component using a callback? I'm new to React and my first project involves creating a form (created with react-hook-form) which includes date pickers (using React Datepicker). Everything's working fine so far except my date picker which when clicked does not update the form field with the new selected date.
The project is structured as follows:
index.js
   V
Form.js
   V
ChooseInputType.js (this is looking at a json file of the form questions and choosing what form input to display)
   V
FormDate.js (A date picker will be shown if the json file says it's a date field).

FormDate.js
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { Controller } from 'react-hook-form';
function FormDate({ name, question, register, control, type }) {
  const [startDate, setStartDate] = useState(new Date());
  return (

      {question}

        <Controller
          as={
            <DatePicker
              selected={startDate}
              onChange={date => setStartDate(date)}
              selectsStart
              startDate={startDate}
            />
          }
          control={control}
          name={name}
          ref={register}
          id={name}
        />

  );
}
export default FormDate;

I have used the Controller component as per the react-hook-form Controller documentation as I will eventually need to use conditional logic and thought that was the right thing to do? But other than that it appears to be the same as the date range sample code. I've received a hint from someone elsewhere that the issue is as follows:

The issue is the Controller component that you have your date pickers
  wrapped in. They are consuming the onChange callback and not allowing
  it to propagate the child component.
From reading the documentation you can only use uncontrolled
  components within them, things like html  tags, anything that
  requires React to directly manipulate their state will function here.
You'll have to look at passing the data you require from the form
  elements, like your date pickers, back up to your main form and
  compiling what you need to be submitted there manually. You can pass
  data back out of components using either callbacks, React.context or
  some other global state management system like Redux. Personally, I'd
  recommend sticking to callbacks whilst the complexity of the app is
  still manageable and only look at the other options if things start to
  get really complicated.

Is anyone able to help me (as a noob!) understand how to do this, perhaps with an example? Or is there any documentation that might help me out?
Many thanks,
Katie

A: Following Bill's answer in the comments attached to my original question, I have amended my code to look like this and it now updates the date field inside the Controller! Thanks Bill. Bill has also included examples of how you would use the Controller with many different types inputs, so please give him a thank you if you find that useful.
import React from 'react';
import ReactDatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import { Controller } from 'react-hook-form';
function FormDate({ name, question, register, control}) {
  return (

      {question}

        <Controller
          as={
            <DatePicker
              dateFormat="dd/MM/yyyy"
              placeHolderText="Select date"
              className="input"
            />
          }
          control={control}
          name={name}
          ref={register}
          id={name}
          valueName="selected" //This is key!
          onChange={([selected]) => selected} //This is key!
        />

  );
}
export default FormDate;

I wanted to format the date and this is a useful list of props that you can pass into the date picker component
Thanks again Bill - your examples are a fantastic help!


text:
Q: Removing once from C++ List I have the following example:
// remove from list
#include <iostream>
#include <list>
using namespace std;

int main ()
{
  int myints[]= {17,89,89,7,14};
  list<int> mylist (myints,myints+5);

  mylist.remove(89);

  cout << "mylist contains:";
  for (list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
        cout << " " << *it;
  cout << endl;

  return 0;
}

The result is:
17, 7, 14

The problem with this is that it removes both instances of 89.
Is there any easy way to just remove one instance of 89?

A: No, there isn't. You might do however:
mylist.erase(find(mylist.begin(), mylist.end(), 89));


text:
Q: How to get individual items from tweepy stream I can't seem to get individual items i.e. getting just the text or just the user.
I've tried to use it as a dictionary or list but nothing seems to work. I don't, however, know how trustworthy my testing is as I'm an amateur.
def on_data(self, data):
        try:
            print(data.text(?))
            with open(self.fetched_tweets_filename, 'a') as tf:
                tf.write(data)
            return True
        except BaseException as e:
            print("Error on_data %s" % str(e))
        return True

I want "Sample tweet" however I'm getting various can't be parsed errors

A: The on_data method of StreamListener receives raw data as a string.
You can use json.loads to deserialize the JSON to a dictionary to access the "text" key.
See https://github.com/tweepy/tweepy/blob/29bae1fde3ae0636fa13e5ed69f68f2af75c110b/tweepy/streaming.py#L42-L48.
Alternatively, you can use on_status instead to obtain a Status object, which has the text attribute.


text:
Q: How to pass response from one function to another function using ajax in django HTML? I am trying to pass flight data which is in dictionary form and this is generated when user searches for flight and selects offer.
What I want is the flight data should be passed in the url but user should not be able to read or modify it.
Currently, I have passed flight data with
  {% for  flight in response %}
      href="{% url 'get_detail' flight %}"
  {% endfor %}

but it shows flight information in URL like 127.0.0.1/get_detail/{flightinfohere}
. Is there any idea so that I can save this flight data for another function without passing in URL or I can hide this data or encode it?
Any help would be appreciated.
I tried to use AJAX, but I don't know how to pass the flight data in ajax as it is response of another views.py function.

A: you can use post request or set cookie.
but the cookie method is easier
in template use :
{% for  flight in response %}
    <a href="{% url 'get_detail'%}" class="use-post" data-flight="{flight}">
{% endfor %}

....
<script type="text/javascript" src="{% static 'js/jquery-3.4.1.min.js'%}"></script>
<script>
    $( ".user-post" ).click(function( event ) {
        event.preventDefault();
        const value = $(this).attr('href');
        const data = $(this).data('flight')
        $.cookie("flight_info",data)
        document.location.href = $(this).attr('href');
});

in view :
...

    flight_info = request.COOKIES.get('flight_info')


text:
Q: "Fatal: too many params" when calling bash command from python, no error using same command directly in git bash Expanding on a previously working function, I ran into a problem with the $(echo -e"...")-part, subprocess.call returns "fatal: too many params".
If i copy the printed bashCmd and paste it directly in Git Bash, I end up with the expected result (new tag created with heading, and some formatted presentation of the "body" of the tag; "new functions: ... \n bugfixes: ...\n" etc.
The printed bashCmd string passed as argument to subprocess.call:
git tag -a v1.4.9 -m "new tag description" -m"$(echo -e "==New Features==\n  no new features\n  but feature 1\n  and feature 2\n==Bugfixes==\n  fixed whitespace\n  hopefully it works\n==Known Issues==\n  No Known Issues Reported.\n")"
bashCmd = 'git tag -a v' + str(major) + '.' + str(minor) + '.' + str(bugfix) +' -m'+ ''' "''' + heading + '''" '''+'-m'+ '''"$(echo -e'''+ ''' "'''  +body+'''"''' ''')"'''

subprocess.call(bashCmd, shell=True)
print(bashCmd)

A: There is no reason for using the shell here. Use the list form for the first argument to call. Note this will require you to modify body, but that will
make it simpler.
body = """\
==New Features==
still not working

==Bugfixes==
0 bugs fixed

==Known Issues==
infinite amounts of bugs left"""

commit_msg = "heading\n\n" + body
version_str = '.'.join(['v', str(major), str(minor), str(bugfix)]),

git_cmd = [
    'git',
    'tag',
    '-a',
    version_str,
    '-m',
    commit_msg
]

subprocess.call(git_cmd)


text:
Q: Can I make reference for whole resource folder? I would like to support many different screen types with the drawable resources.
But I can use some drawables with the same size on more screens.
For example: -xxhdpi-normal and -mdpi-xlarge could use the same sized drawable image
I don't wan't to make 2 folders (drawables-xxhdpi-normal and drawables-mdpi-xlarge), because then the .apk will be bigger.
I know that if I just put simply every drawable resource into drawables folder with different names. Then I can make the layout for every screen. It is a lot of work but makes a smaller .apk
I know that it is easier to maintaine my code if I use refs.xml instead of the differnet layout.xml-s
(about refs.xml: http://blog.vogella.com/2013/08/13/using-xml-layout-references-in-android/)
 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <item type="layout" name="activity_main">@layout/activity_second</item>
</resources>

But in this case I will still have a lot of work with the resource naming, and I can't use tools like (cut and slice me - photoshop plug-in that exports drawables for different dpi-s)
Is there a way, I can just say to the system:
If the device is -mdpi-xlarge use the drawables-xxdpi folder to make the layout?

A: the system use automatically the resource folder (when avalable) closest to your resolution or one scale and appear best
for example
if you use only xxxxdpi it will alway down scale them , so single folder and quite decent image quality
if you want to use different assets for some resolutions just override that files in that folder


text:
Q: MySQL now() in database I'm trying to put the time of a post into my database table but i can't get it to work. maybe someone here can explain what i'm doing wrong.
This is my code:
<?php

if (isset($_POST['upload_message'])) {
    $message_title = $_POST['message_title'];
    $message_content = $_POST['message_content'];
}

$table_name = "posts";
$add_query = "INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', 'SELECT NOW()')";

if (mysql_query($add_query)) { //executes query and error check
    echo "het artikel staat in de database";
}
else { //error message
    echo "fout bij het toevoegen" . "<br />" . mysql_error();
}

?>

and this is a screen shot of my db table : http://gyazo.com/17019f143eab6e5818752c33824bde29
When I run mysql_error is get the following message :

Incorrect datetime value: 'SELECT NOW()' for column 'date' at row 1

A: You don't have to SELECT NOW(), just NOW()
$add_query = "INSERT INTO $table_name (name, content, date)
    VALUES ('$message_title', '$message_content', NOW())";

You should use prepared statements with binded parameters using mysqli_ or PDO.

A: NOW() is a mysql function, you don't have to "select it" just call it.
Replace the "SELECT NOW()" for just "NOW()".
INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', 'NOW()')

A: Or you can use CURRENT_TIMESTAMP
INSERT INTO $table_name (name, content, date) VALUES ('$message_title', '$message_content', CURRENT_TIMESTAMP);

A: Mysql_query is deprecated as of PHP 5.5.0.
Use PDO or Mysqli !
And secure your code, we can do injection sql.


text:
Q: Knockout Mapping: Object not Filled I am learning Knockout and cannot get Knockout.mapping.fromJS to work. Here is my code:
$.getJSON("data/status.json", function(data) {
        var members = ko.mapping.fromJS(data);
});
ko.applyBindings(members);

I am using a template. Here is the template:

And the markup...

Members

The JSON data loads correctly, but the "members" object is "undefined." (Members.dname is one object property among many.)
Can anyone tell me what I'm doing wrong? Thanks in advance!

A: More than happy: your members variable is outside of scope, so it gets lost after our AJAX call completes. You want something either like this.
$.ajax({url:"/echo/json/", data:json, type:"POST", success:function(data) {
  var viewModel = ko.mapping.fromJS(data);
  ko.applyBindings(viewModel)
}});

So you apply the bindings inside of the scope of the AJAX call or something like this.
var self = this
self.members = ko.observableArray([]);
$.ajax({url:"/echo/json/", data:json, type:"POST", success:function(data) {
  var members = ko.mapping.fromJS(data);
  self.members(members);
}});
// do the binding elsewhere

Which binds your response inside a closure. Remember that an AJAX call is a promise pattern, so you really don't know when the response is completed. Here's a code with a working example.


text:
Q: Gradle - Test tasks results not cached "Test" tasks in my multi-module build are not being cached by Gradle. Incremental build works fine and reports everything as up-to-date, but if I perform clean build tests are always executed.
I am seeing this message Non-cacheable because 'Task outputs cacheable' not satisfied [ENABLE_CONDITION_NOT_SATISFIED] for all the test tasks if org.gradle.caching.debug parameter set to true. All fingerprints are identical between executions.
Any ideas what does it mean and/or how to fix it?
P.S. Using Gradle 6.7 with Junit 5 and JaCoCo. Disabling JaCoCo does not change anything.


text:
Q: How to get all custom fields of a particular record type in Netsuite using RESTlet? I can create a customer, lead, contact using RESTlet. But my code is used by someone who created custom fields with required option. When I try to create a customer, I am getting error by custom required fields.
I want to pass the data for custom required fields too. How to know the all custom fields categorized by required and none required using RESTlet?

A: You can use
var record = nlapiCreateRecord(RECORD_TYPE);
var fields = record.getAllFields();
var requiredFields = [];
fields.forEach(function(fieldName){
 var field = record.getField(fieldName);
 //I am not very sure, its true or T but, below code will work
 if(field.mandatory === true || field.mandatory === 'T'){
   requiredFields.push(field.getName()) //getLabel() for UI label, as getName returns id;
 }
});

//requiredFields array is your need.

A: Actually in this situation I take one of two approaches (or combine them):
The first is to just ignore mandatory fields. You view your code's job is to get information into Netsuite and users will have to be responsible for future updates. You do this by telling Netsuite to ignore mandatory fields when your code saves them:
nlapiSubmitRecord(nlobjRecord, doSourcing, ignoreMandatoryFields); //doSourcing and ignoreMandatoryFields are booleans

or I add a text area parameter to the restlet where the person configuring the restlet has to enter a list of extra fields you want to do something with (e.g. display in a dialog and make required)


text:
Q: How to enable push notification in quickblox groupchat I have been trying quickblox chat api and i have gotten stucked at some place.
I have registered and setup gcm notifications and i am able to received notifications that are been sent from Google Developer Console.
I am able to receive notifications that are sent from QuickBlox Admin panel. I subscribe to notifications each time the activity is started and am able to receive messages that are sent on the group chat but if i go offline, i do not receive notifications when the messages are sent. I don't know if i have to register the groupchat for notificatons in some way. Please what do i do to be able to receive notifications when the app is closed or when the user was offline and messages were sent.


text:
Q: dns set up using bind9 behind a router I used to have a server running Ubuntu 17.04 server with static IP, I have a nameserver config on that machine following some instructions on a page on the internet.
Now I do not want to spend money on the server and want to set up the nameserver on my personal machine at home which saves me monthly expenses on the server and it is a lot faster than the configuration I had in the previous one. Now I want to point the domain to this new IP. As the IP address often change, I have created an application which will check my updated public IP and update the DNS provider with the latest IP. I have already done the port forwarding for SSH and the port 80 for Web Server.
But I have some questions below.
What are the problems I may arise?
what IP address should I use on the named.conf.local file and the named.conf.options, etc?
Is there a documentation or a guide available to set this up.
I do not want to use No-IP or other tools.
Thanks in advance.

A: I don't think it will work for you.
If example.com wants to use ns1.example.com as one of its nameservers of record (for others to use for lookups to find www.example.com, etc) then the registrar for the domain (godaddy, google, network solutions, whoever) needs to add what are called "glue records" so that a domain can reference itself.  With an IP that changes on a fairly regular basis, this won't work.
Even if you had say a linode or other VPS, you couldn't run a master from your home connection in a secure way - domain transfers are typically locked down by what IP is allowed to pull a copy - so you'd have to update your DNS config in order to update your records.
What would work is what you said you don't want to do - use noip or some other dynamic dns service.  You could do that, and then set up CNAME records for your "real" domain that point to your noip hostname which would be kept in synch with your IP address.
Personally, between power issues, extra heat, extra noise, etc. I moved my server from my home to a linode.com account 12 years ago and haven't looked back, and that is what I'd recommend that you do as well...

A: It's possible. Somewhat. But it's not recommended.
I do it, and it's painful.
First of all, I have a No-IP record, for the public IP. Let's call this foo.no-ip.com.
The NS of example.com points to foo.no-ip.com, and a second (external) Slave NS, that is simply replicating the master. Slave DNS is often included for free from the registrar.
Bind9 is set up as authorative DNS server for example.com, and port 53 TCP and UDP is allowed trough to Bind. Normally DNS uses only UDP, but for zone transfer to the slave NS, TCP is used.
The zone file is rather standard:
$TTL 60
;
$ORIGIN example.com.
example.com.     IN  SOA foo.no-ip.com.      admin.example.com. (
        2017012101 ; serial
        1h ; refresh
        1h ; retry
        1h ; expire
        1m ; default_ttl
        )
@ IN NS foo.no-ip.com
@ IN NS slave-ns.example.org
@ 600 IN A 127.0.0.1

I wouldn't really recommend hosting DNS at home. Go with a provider that gives you Dynamic DNS updates, for instance I believe google does this. Then you can use the nsupdate tool to dynamically manipulate your NS records.
DNS is great stuff, but it's at times rather fragile too.
It's technically possible to do it with glue records as well, but they are prone to errors when IP changes, so that's not recommended if you're on a changing address.
If you want to go with glue records, add a record in your zone file with some name, e.g. ns 600 IN A 1.2.3.4 pointing to your public IP. Specify ns.example.com as NS, and create a glue record at your registrar. How this is done differs from vendor to vendor. Whenever you update your external IP, you have to update the glue record.


text:
Q: Assigning function output to variable I have this:
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Iphlpapi.h>
#include <Assert.h>
#include <sstream>

#pragma comment(lib, "iphlpapi.lib")

using namespace std;

// Prints the MAC address stored in a 6 byte array to stdout
static void PrintMACaddress(unsigned char MACData[])
{

    printf("%02X-%02X-%02X-%02X-%02X-%02X",
        MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

}

// Fetches the MAC address and prints it
static void GetMACaddress(void)
{
    IP_ADAPTER_INFO AdapterInfo[16];            // Allocate information for up to 16 NICs
    DWORD dwBufLen = sizeof(AdapterInfo);       // Save the memory size of buffer

    DWORD dwStatus = GetAdaptersInfo(           // Call GetAdapterInfo
        AdapterInfo,                            // [out] buffer to receive data
        &dwBufLen);                             // [in] size of receive data buffer
    assert(dwStatus == ERROR_SUCCESS);          // Verify return value is valid, no buffer overflow

    PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;// Contains pointer to current adapter info
    do {
        PrintMACaddress(pAdapterInfo->Address); // Print MAC address
        pAdapterInfo = pAdapterInfo->Next;      // Progress through linked list
    }
    while(pAdapterInfo);                        // Terminate if last adapter
}

    int _tmain(int argc, _TCHAR* argv[])
    {
    char mac[100];

        GetMACaddress(); // output is 00-19-D7-53-2D-14

    std::stringstream buffer;
    buffer << "Text" << std::endl;
    cout << buffer.str();
        return 0;
    }

My question is how do I assign function GetMACaddress(); output to variable. This: mac = GetMACaddress(); // output is 00-19-D7-53-2D-14 don't worked. Help me please. Thank you.
The data type for returning MAC address is unsigned char.

A: If the data type for returning mac address is unsigned char, you can store that in it.
unsigned char output = GetMACaddress() ;

If its a sting of characters, use std::string to store the mac address returned, if as you say something of the output of the pattern 00-19-D7-53-2D-14.
std::string output = GetMACaddress() ;

If it is some other type, you can let the compiler decide that at runtime. If you are using C++11, you can use auto or decltype.
auto return_val = GetMACaddress() ;

A: You need to redirect the stdout buffer to a stringstream, as below:
stringstream ss;
streambuf* old = std::cout.rdbuf(ss.rdbuf()); // redirect stdout, and also save the old one

GetMACAddress();

string theStr = ss.str();
cout << theStr << endl;

// when you are done, redirect back to the "real" stdout
cout.rdbuf(old);

A: Your function PrintMACaddress prints the MAC address; you need a similar function that receives unsigned char MACData[] but returns a MAC address instead of printing it.
// Converts the MAC address stored in a 6 byte array to a string
std::string ConvertMACaddressToString(unsigned char MACData[])
{
    ...
}

To implement it, first replace printf by sprintf:
char result[18]; // 18 bytes are just enough to hold the MAC address
sprintf(result, "%02X-%02X-%02X-%02X-%02X-%02X",
    MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

Then return the value from the function:
return result;


text:
Q: StaleDataException with dialog I am trying to show a dialog with a listview with names from my database but I keep getting a StaleDataException. I know that usually means I am trying to use data from a closed cursor but the cursor does not close until I get all the data so I dont understand why I am getting this
d = new Dialog(this);
d.setContentView(R.layout.dialog_layout);
d.setTitle("Select Bowler");

ListView lv = (ListView)d.findViewById(R.id.dialog_list);
Cursor c = getContentResolver().query(
    BowlersDB.CONTENT_URI,
    new String[] {
        BowlersDB.ID, BowlersDB.FIRST_NAME, BowlersDB.LAST_NAME
    },
    null,
    null,
    BowlersDB.LAST_NAME + " COLLATE LOCALIZED ASC"
);

if (c.moveToFirst() && c != null) {
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(
        this,
        R.layout.names_listview,
        c,
        new String[] {
            BowlersDB.FIRST_NAME, BowlersDB.LAST_NAME
        },
        new int[] {
            R.id.bListTextView, R.id.bListTextView2
        },
        0
    );
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
            bowlerClickedID = id;
            updateName(id);
        }
    });
    d.show();
}
c.close();

error
android.database.StaleDataException:
   Attempting to access a closed CursorWindow.
   Most probable cause: cursor is deactivated prior to calling this method.

   at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:139)
   at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
   at android.database.CursorWrapper.getString(CursorWrapper.java:114)
   at android.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:150)
   at android.widget.CursorAdapter.getView(CursorAdapter.java:250)
   at android.widget.AbsListView.obtainView(AbsListView.java:2267)
   at android.widget.ListView.measureHeightOfChildren(ListView.java:1244)
   at android.widget.ListView.onMeasure(ListView.java:1156)
   at android.view.View.measure(View.java:15172)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
   at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
   at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
   at android.view.View.measure(View.java:15172)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
   at android.view.View.measure(View.java:15172)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
   at android.view.View.measure(View.java:15172)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
   at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
   at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
   at android.view.View.measure(View.java:15172)
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
   at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148)
   at android.view.View.measure(View.java:15172)
   ...

EDIT:
If I comment out the c.close() line it works fine but I cant just leave the cursor open though so what do I do?

A: You're getting your error because you're closing the Cursor while the SimpleCursorAdapter you create might still be trying to access data from it.
If you want to use a CursorLoader, as you should be doing.

*

*Keep a reference to your adapter as an instance variable

*Create your simple cursor adapter with a reference to null for the cursor

*Have your class implement LoaderManager.LoaderCallbacks<Cursor>

*Actually create the CursorLoader in the onCreateLoader

*In onLoadFinished(), swap the cursors with adapter.swapCursor(cursor)

*In onLoaderReset(), swap the cursor with a null cursor as adapter.swapCursor(null)`

You should also end up putting your data in a ContentProvider - it's not that bad!

A: You cannot close the cursor until CursorAdapter is no longer needed. So you can close it in onDestroy() method:
@Override
public void onDestroy() {
 super.onDestroy();

 ListView lv = (ListView) d.findViewById(R.id.dialog_list);
 ((CursorAdapter) lv.getAdapter()).getCursor().close();
 database.close();
}

A: I used to rely on startManagingCursor method to leave the hassle of opening and closing Cursors to the system. Now that it is deprecated (it still works but I would not recommend using it), consider using the CursorLoader class with LoaderManager and leave it to the system to handle the Cursor closing.


text:
Q: How to format presto api response as JSON using outputFormat and useIndexJoin? How to add two maps of key to values(array) together in Presto?
I can see the sample in the shared link. I need help with the implementation.


text:
Q: Set of non-isomorphic abelian groups of a large order Define a set
$A:=\{G: G$ is abelian group; $\operatorname{order}(G)=10.000$, no two groups are isomorphic $\}$.
What is the largest size of $A$?

A: This is an easy application of the Fundamental Theorem of Finitely Generated Abelian Groups. Since $|G|=2^4\times 5^4$, then $G\cong G_2\times G_5$, where $G_p$ is the $p$-part of $G$.
Thus, the problem reduces to asking how many different abelian groups of order $p^4$ there are. Since an abelian $p$-group must be a direct sum/product of cyclic groups of prime power order, the answer is that there are as many abelian groups of order $p^n$ as there are partitions of $n$.
So there are as many possibilities for $G_2$ as there are partitions of $4$, and also as many possibilities for $G_5$ as there are partitions of $4$, and hence the number will be the product of these two, the square of the number of partitions of $4$.


text:
Q: Getting '500 - Internal server error' while running an Azure project
500 - Internal server error.
  There is a problem with the resource you are looking for, and it cannot be displayed.

I have also added my IP to the firewall rule. I am a beginner in Azure.
I am getting the above error while trying to run the azure web project. I have added following tags after going through some articles but none help me.
 <validation validateIntegratedModeConfiguration="false"/>
 <identity impersonate="false"/>

A: Basically, your application is throwing an unhandled error.  You will want to know what the real error is, as Error 500 is just a generic way of saying: something happened.
You can deploy your app with customerrors being OFF so you can actually see the real error (Check this link for sample instructions: http://www.serverintellect.com/support/programming/custom-errors.aspx ).
Alternatively, if you're using WebRoles, you can RDP into a server instance and check Windows EventViewer, the details of the error will likely show up there.

A: In my case, I was using code downloaded from durandaljs.com.  The "Build Action" on my default page (index.html) was set to "None", so this file was not uploaded to Azure during publish. Fixed by changing the "Build Action" to "Content".
Troubleshooting IIS via Remote Desktop really helped me figure this out.  Choosing the "Enable Remote Desktop for all roles" when you publish, then in Server Explorer, expand Cloud Services, etc., then right-click your instance and choose "Connect using Remote Desktop".

A: This may be a proxy related issue.
Try adding these to your *.config files:
<system.net>
    <defaultProxy useDefaultCredentials="true" />
</system.net>


text:
Q: Video become interlaced of the Motion Menu (DVD) in Adobe Encore CS6 This problem only occur on DVD menu, video is progressive and with Text in the menu. in Blu-Ray disc, motion menu works perfect.
I tested created a simple menu with video as background (720 x 480 progressive 29.97 m2v). the dvd motion menu works fine, the video looks great in the menu.
but if i add the text in the same menu, the created DVD motion menu will be interlaced !
is this a bug ?

A: Found the problem myself.
the problem is my VM (windows 8.1 running on Parallel, Macbook Pro 2013 late 15" Retina with intel iris pro 5200)
i copy the rendered motion menu video file to other pc there is no interlaced on the video !!
i am using K-Lite_Codec_Pack_1090_Standard in the VM.


text:
Q: Installing STM32CubeProgrammer on macOS Big Sur I'm trying to install STM32CubeProgrammer on MacOS BigSur, I have followed this steps from the website: https://community.st.com/s/question/0D50X0000BmnqrB/how-to-run-stm32cubeprogrammer-on-macos-catalina-10151-19b88?t=1620993010340. Although when I run the program with terminal, it gives me an error saying that I couldn't found jre folder. But when downloading from the website, it comes with the jre folder, SetupSTM32CubeProgrammer-2.7.0.exe and SetupSTM32CubeProgrammer-2.7.0.app.
This is the error line:
JRE Folder not found!

jre not found

A: macOS GUI setup doesn't work, although seems it can be executed via packaged console executable.
Use appropriate version for the command:
./SetupSTM32CubeProgrammerx.y.z.app/Contents/MacOs/SetupSTM32CubeProgrammer-x_y_z_macos

Source: ST Community


text:
Q: Makefile with msys on Windows strange behaviour using the include directive (On linux works perfectly) Problems using the INCLUDE directive inside a makefile using msys.
I added MSYS in PATH and is ok until here:
PS C:\Users\Roxanji> Get-Command make

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     make.exe                                           0.0.0.0    C:\Program Files\msys\bin\make.exe

PS C:\Users\Roxanji> Get-Command bash

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     bash.exe                                           0.0.0.0    C:\Program Files\msys\bin\bash.exe

Makefile example:
-include a1

a1:
    @echo something: > a1

.PHONY: clean
clean:
    $(RM) a1

On Windows cmd/powershell:
PS C:\Users\Roxanji\eclipse-workspace\prototype\tst> ls

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        15.11.2020     05:53             81 Makefile

PS C:\Users\Roxanji\eclipse-workspace\prototype\tst> make

make.exe": /c/Users/Roxanji/eclipse-workspace/prototype/tst/"C:/Program Files/msys/bin/make.exe": Command not found

PS C:\Users\Roxanji\eclipse-workspace\prototype\tst> ls

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        15.11.2020     06:03             11 a1
-a----        15.11.2020     05:53             81 Makefile

On Windows using bash from msys:
PS C:\Users\Roxanji\eclipse-workspace\prototype\tst> bash
bash.exe"-3.1$ pwd
/c/Users/Roxanji/eclipse-workspace/prototype/tst
bash.exe"-3.1$ ls
Makefile
bash.exe"-3.1$ make
make: Nothing to be done for `something'.
bash.exe"-3.1$ ls
Makefile  a1
bash.exe"-3.1$

Facts using cmd/powershell:

*

*The file 'a1' is generated.

*Command not found message.

Facts using msys bash:

*

*-The file 'a1' is generated.

What I think is going on?

*

*I see that there are some mixing of windows slash "\" and unix slash
"/"

*I see that the make "location" seems different under bash from msys:
bash.exe"-3.1$ which make
/usr/bin/make.exe

*I see that also under msys/bash there is this message make: Nothing to be done for 'something'.
I think that when make hits include another make.exe is spawned to read this other file, but is called from within make, that has a different PATH for make, and this causes some problems.
Someone can give explanations about this phenomena??
Edit 1:
using powershell:
PS C:\Users\Roxanji\eclipse-workspace\prototype\tst> make -np | grep MAKE_COMMAND
MAKE = $(MAKE_COMMAND)
MAKE_COMMAND := /c/Users/Roxanji/eclipse-workspace/prototype/tst/"C:/Program Files/msys/bin/make.exe"

Shouldn't the MAKE_COMMAND variable bee equal to just "make"?
like: MAKE_COMMAND := make ?
Edit 2:
I think the problem can be tracked down to the fact that I can't run msys.bat under C:\Program Files\ because apparently there is a space in "Program files"??

A: As mentioned, the most reliable solution on Windows is a native Windows make build. I was able to run your Makefile directly from Powershell using such native build without any errors, regardless of make being located in a directory with space:
> ls

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          11/26/2020  4:11 PM             86 Makefile

> & 'C:\Program Files\make\make.exe'
make: Nothing to be done for 'something'.

> ls

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---          11/26/2020  4:17 PM             13 a1
-a---          11/26/2020  4:11 PM             86 Makefile

MAKE_COMMAND also looks good:
> & 'C:\Program Files\make\make.exe' -np | ? { $_ -match "MAKE_COMMAND" }
MAKE = $(MAKE_COMMAND)
MAKE_COMMAND := C:/Program Files/make/make

All tests done with:
> & 'C:\Program Files\make\make.exe' --version
GNU Make 4.2.1
Built for Windows32
Copyright (C) 1988-2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Built directly from source using Visual Studio.


text:
Q: Unable to set spark driver memory I am building a spark(Running on Apache Spark version 2.4.3) session from Jupiter notebook as follows
spark_session  = SparkSession.builder
                      .master("yarn-client")
                      .enableHiveSupport()
                      .getOrCreate()

spark_session.conf.set("spark.executor.memory", '8g')
spark_session.conf.set('spark.executor.cores', '3')
spark_session.conf.set('spark.cores.max', '3')
spark_session.conf.set("spark.driver.memory",'8g')
sc = spark_session.sparkContext

I can see from the application master that all the parameters are being set properly expect the spark.driver.memory. spark.driver.memory no matter what I set its using only 1GB for it.
I have checked spark-default.conf but I there are no parameters such as for spark.driver.memory. To check if its with the session builder/ Jupiter I ran an application using spark-submit from the command-line and to my surprise its picking the driver memory what I am passing.
Can someone please shed some light on this? What could be the reason why its not picking just the spark.driver.memory from the jupyter

A: Jupyter notebook will launch the pyspark with yarn-client mode, the driver memory and some configs cannot be set with property 'conf' as the JVM driver has already started. you must set it in the command line.
So, to your question - When you run spark in client mode setting a property via "conf.set" will not work as the JVM driver has already started at that point with default config. That's why when you pass the property from the command line it is picking them.
a simple way to start pyspark is
pyspark --driver-memory 2g --executor-memory 2g

Update:
To start jupyter with custom pyspark arguments, create a custom kernel, more on getting started with jupyter kernel: http://cleverowl.uk/2016/10/15/installing-jupyter-with-the-pyspark-and-r-kernels-for-spark-development/
and when you are defining "kernel.json" add --driver-memory 2g --executor-memory 2g to PYSPARK_SUBMIT_ARGS option.


text:
Q: Number of ways to choose 4 among 10 if repetition is allowed Q: In how many ways can you choose 4 things among 10 if the order does not matter and you can choose the same item several times?
I am trying to understand the intuition behind the answer.
The answer is:
$$ \binom{13}{9} = 715$$
I am told the problem can be mapped to:
$$x_1+x_2+x_3...x_{10}=4$$
But how does the $\binom{13}{9}$ map to $x_1+x_2...x_{10}=4?$

A: I frame the problem as choosing (order doesn't matter) 4 items from 10 categories (each category may be repeatedly picked)?
Or, more generally, picking $r$ items from $n$ categories (repetition allowed).
For each selection, use $(n-1)$ vertical bars as separators to illustrate the $n$ categories, and represent the $r$ selected items by filling $r$ stars in the according categories.
Notice that every selection contains $[(n-1)+r]$ placeholders/positions all filled by stars & bars, and that selections are distinguished by the $r$ stars filling in different combinations of positions (the vertical bars filling in the remaining positions).
Therefore, the total number of selections is the number of ways to choose $r$ positions from $[(n-1)+r]$ positions, i.e., $$\binom{n-1+r}{r}.$$
So for our problem at hand, the answer is $$\binom{10-1+4}{4}=\binom{13}{4}=\binom{13}{9}=715.$$

A: To make the mapping from your problem to
$$x_1 + x_2 + \cdots + x_{10} = 4$$
more explicit: each $x_i$ must lie in $\{0,1,2,3,4\}$, depending how many times the element $i$ has been chosen; then this sum will be 4 iff exactly four items in total have been chosen. "Order does not matter" is captured by the commutativity of addition.
For a given assignment of values to $x_i$'s, we could write this out using ordinary digits. But if we instead write $0$ as $0$, $1$ as $S(0)$, $2$ as $S(S(0))$, and so on (here $S$ stands for "successor" and in general $S(n) = n+1$), then we can see that every assignment of values to this equation will involve four $S$s and ten zeros.
To be syntactically correct we need the last symbol to be a 0, but the four $S$'s and remaining nine zeros may appear in any order. In other words, we have a binary string of length 13 which has 9 zeros in it, and the number of such strings is exactly $\binom{13}{9}$.
By the way -- this is exactly the "stars and bars" link provided in the comment, with 0s in place of bars and $S$ in place of stars.


text:
Q: Error al consumir un servicio REST API con el metodo POST usando AngularJS Estoy consumiendo un servicio REST API con angularJS y el metodo POST, pero al consumir el servicio me envia una peticion con el metodo OPTIONS. No entiendo por que?
He leido y deje en el web.config del sitio las siguientes lineas:
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Credentials" value="true"/>
      <add name="Access-Control-Allow-Origin" value="https://www.zonapagos.com" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
  <validation validateIntegratedModeConfiguration="false" />
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <!--<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />-->
    <remove name="WebDAV" />
  </handlers>
  <modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule" />
  </modules>
  </system.webServer>

pero me sigue enviando primero la peticion OPTIONS
Tiene algo que ver con CORS pero no encuentro como solucionarlo

A: hayes un error comun con angular integrandolo con Java o .NET, tienes dos opciones la primera debes agregar la linea en el app.js
.config(function(...., $httpProvider  ) {

  $httpProvider.defaults.headers.post = {};
    $httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

la segunda: modificar cada funcion de tu http
$http({
    url: "tu url",
    method: "POST",
   params: {
      valor1: 'valor1',
      valor2: 'valor2'
    },
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});


text:
Q: Can't get Spring to inject my dependencies I've been trying to get Spring to inject an @Autowired dependency into my application without avail. What am I doing wrong?
I created a bean called TimeService. Its job is to return the current time to anyone that asks.
package com.foxbomb.springtest.domain.time;

import java.util.Date;
import org.springframework.stereotype.Service;

@Service
public class TimeService {

    public TimeService() {
        super();
        System.out.println("Instantiating TimeService...");
    }

    public Date getTime() {
        return new Date();
    }
}

Of course, I need to tell Spring about this, so I added the following to web.xml:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-context.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Great, and some Spring configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:annotation-config base-package="com.foxbomb.springtest.domain" />

</beans>

Now all we need is a calling class that would like to use this dependency. Unfortunately, the @Autowired here seems to do nothing:
package com.foxbomb.springtest;

import...

@Configurable
public class TimeManager {

    public TimeManager() {
        super();
        System.out.println("Instantiating TimeManager...");
    }

    @Autowired
    private TimeService timeService;

    public Date getTime() {
        return timeService.getTime();
    }

}

And lastly, a JSP that wants to display the time:
<%@page import="com.foxbomb.springtest.ApplicationContextImpl"%>
<%@page import="com.foxbomb.springtest.TimeManager"%>

        <title>Spring Test</title>

Autowired Dependencies....

            Time is now <%=new TimeManager().getTime()%>!

But all I get is:
java.lang.NullPointerException
    com.foxbomb.springtest.TimeManager.getTime(TimeManager.java:26)

A: When you access TimeManager object like this:
Time is now <%=new TimeManager().getTime()%>!

Spring does not know anything about this class. You are basically creating a new object, that's it!
Probably Spring creates an instance of TimeManager and injects dependencies properly (however you should use @Service rather than @Configuration annotation), but you are not using this instance in your JSP. Instead you are creating new, unmanaged instance, that is completely independent and unaware of Spring and dependencies...
I think this will work:
<%= WebApplicationContextUtils.
  getWebApplicationContext(application).
  getBean(TimeManager.class).
  getTime() %>

Ugly? Sure. Because the whole approach of accessing services from JSP (view) is ugly. You should at least have a servlet that accesses Spring beans and puts result in request attributes. These attributes can then be accessed in JSP that you forward to - without ugly scriptlets.
If you really want to do this "the right" way, try Spring MVC or other popular Java web framework.

A: The @Autowire annotation in TimeManager was not recognized, because you told spring to start searching for annotation configuration information in the wrong package.
TimeManager is in com.foxbomb.springtest.
You have this configuration:
<context:annotation-config base-package="com.foxbomb.springtest.domain"/>

Notice that "com.foxbomb.springtest != com.foxbomb.springtest.domain".
Change your configuration to include this:
<context:annotation-config base-package="com.foxbomb.springtest"/>

Edit: Spring must instantiate TimeManager.
You will need to:

*

*Have TimeManager be a data member of the controller class.

*@Autowire TimeManager into the controller class (or get it from spring somehow).

*Add the TimeManager to some appropriate scope (maybe session, maybe request, maybe application).

*Access this TimeManager on your jsp page.  Maybe something like this: It is now ${MyTimeManager.time} balonia watch time.

A: I tend to agree with @TomaszNurkiewicz; use a framework. However, a framework is way overkill for a lot of applications. If it's overkill for you, this answer details how to do it without all the manual work of getting the bean yourself. IMO doing it manually defeats the purpose.

A: You should be using @Component (or a child stereotype annotation) rather than @Configuration, and annotating your TimeManager with that.  @Configuration is used for Java based container configuration, which is not what you are doing here.

A: Finally!
I got it working with the code in the above example. The trick was to set up Aspect/J and Weaving. This allows the @Configurable annotated class to automatically realize that its dependent on Spring to inject dependencies.
There wasn't much wrong with the base package :) I accidentally made a xml typo, trying to add the base-package attribute to the context:annotation-config tag. The correct definition was:
<context:annotation-config/>
<context:component-scan base-package="com.foxbomb.springtest"/>

I need actually eventually need to change it to com.foxbomb.springtext to include the class that was trying to access the bean too - as in the end it's also annotated.
Thanks everyone for your help!


text:
Q: How to shorten a formula with a OR comparing several RIGHT functions in Google Sheets? I'm trying to solve this problem:
I need to shorten the following formula:
=IFS(
OR(
RIGHT(A1,1)="^",
RIGHT(A1,1)="*",
RIGHT(A1,2)="@@",
RIGHT(A1,2)="%%"),
1,TRUE,0)

I thought of using the pipe symbol like this:
=IFS(
OR(
RIGHT(A1,1)="^|*",
RIGHT(A1,2)="@@|%%"),
1,TRUE,0)

But it's not working.
How to shorten this formula?

A: | can be used only in regex formulas. what about this:
=N(REGEXMATCH(A1, "\^$|\*$|@@$|%%$"))